blob: 3686f2d4844fbe7c375622932978d478c31d1773 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie44481e72016-04-20 07:49:57 +020091void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
92 audio_policy_dev_state_t state,
93 const String8 &device_address)
94{
95 AudioParameter param(device_address);
96 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070097 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020098 param.addInt(key, device);
99 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
100}
101
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800103 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800104 const char *device_address,
105 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106{
Paul McLeane743a472015-01-28 11:07:31 -0800107 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800108 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700109
110 // connect/disconnect only 1 device at a time
111 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
112
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<DeviceDescriptor> devDesc =
114 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800115
Eric Laurente552edb2014-03-10 17:42:56 -0700116 // handle output devices
117 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700118 SortedVector <audio_io_handle_t> outputs;
119
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // save a copy of the opened output descriptors before any output is opened or closed
123 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
124 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 switch (state)
126 {
127 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800128 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700130 ALOGW("setDeviceConnectionState() device already connected: %x", device);
131 return INVALID_OPERATION;
132 }
133 ALOGV("setDeviceConnectionState() connecting device %x", device);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 index = mAvailableOutputDevices.add(devDesc);
137 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100138 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700139 if (module == 0) {
140 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
141 device);
142 mAvailableOutputDevices.remove(devDesc);
143 return INVALID_OPERATION;
144 }
Paul McLeane743a472015-01-28 11:07:31 -0800145 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 } else {
147 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 }
149
François Gaffie44481e72016-04-20 07:49:57 +0200150 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
151 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffieaca677c2018-05-03 10:47:50 +0200152 broadcastDeviceConnectionState(device, state, devDesc->address());
François Gaffie44481e72016-04-20 07:49:57 +0200153
François Gaffieaca677c2018-05-03 10:47:50 +0200154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->address()) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700155 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200156
157 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffieaca677c2018-05-03 10:47:50 +0200158 devDesc->address());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700159 return INVALID_OPERATION;
160 }
François Gaffie2110e042015-03-24 08:41:51 +0100161 // Propagate device availability to Engine
162 mEngine->setDeviceConnectionState(devDesc, state);
163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700164 // outputs should never be empty here
165 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
166 "checkOutputsForDevice() returned no outputs but status OK");
167 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
168 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169
Eric Laurent3ae5f312015-02-03 17:12:08 -0800170 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700171 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700172 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700174 ALOGW("setDeviceConnectionState() device not connected: %x", device);
175 return INVALID_OPERATION;
176 }
177
Paul McLean5c477aa2014-08-20 16:47:57 -0700178 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
179
Paul McLeane743a472015-01-28 11:07:31 -0800180 // Send Disconnect to HALs
François Gaffieaca677c2018-05-03 10:47:50 +0200181 broadcastDeviceConnectionState(device, state, devDesc->address());
Paul McLean5c477aa2014-08-20 16:47:57 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700185
François Gaffieaca677c2018-05-03 10:47:50 +0200186 checkOutputsForDevice(devDesc, state, outputs, devDesc->address());
François Gaffie2110e042015-03-24 08:41:51 +0100187
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700190 } break;
191
192 default:
193 ALOGE("setDeviceConnectionState() invalid state: %x", state);
194 return BAD_VALUE;
195 }
196
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 checkForDeviceAndOutputChanges([&]() {
198 // outputs must be closed after checkOutputForAllStrategies() is executed
199 if (!outputs.isEmpty()) {
200 for (audio_io_handle_t output : outputs) {
201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
202 // close unused outputs after device disconnection or direct outputs that have been
203 // opened by checkOutputsForDevice() to query dynamic parameters
204 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
205 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
206 (desc->mDirectOpenCount == 0))) {
207 closeOutput(output);
208 }
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
211 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 return false;
214 });
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurent87ffa392015-05-22 10:32:38 -0700216 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
218 updateCallRouting(newDevice);
219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -0800220 const audio_devices_t msdOutDevice = getModuleDeviceTypes(
221 mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
224 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
225 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700226 // do not force device change on duplicated output because if device is 0, it will
227 // also force a device 0 for the two outputs it is duplicated to which may override
228 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100229 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
230 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100231 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // always force when disconnecting (a non-duplicated device)
233 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700234 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700235 }
Eric Laurente552edb2014-03-10 17:42:56 -0700236 }
237
Eric Laurentd60560a2015-04-10 11:31:20 -0700238 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
239 cleanUpForDevice(devDesc);
240 }
241
Eric Laurent72aa32f2014-05-30 18:51:48 -0700242 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700243 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } // end if is output device
245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // handle input devices
247 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700248 SortedVector <audio_io_handle_t> inputs;
249
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700251 switch (state)
252 {
253 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700254 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700256 ALOGW("setDeviceConnectionState() device already connected: %d", device);
257 return INVALID_OPERATION;
258 }
François Gaffie53615e22015-03-19 09:24:12 +0100259 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700260 if (module == NULL) {
261 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
262 device);
263 return INVALID_OPERATION;
264 }
François Gaffie44481e72016-04-20 07:49:57 +0200265
266 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
267 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffieaca677c2018-05-03 10:47:50 +0200268 broadcastDeviceConnectionState(device, state, devDesc->address());
François Gaffie44481e72016-04-20 07:49:57 +0200269
François Gaffieaca677c2018-05-03 10:47:50 +0200270 if (checkInputsForDevice(devDesc, state, inputs, devDesc->address()) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200271 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffieaca677c2018-05-03 10:47:50 +0200272 devDesc->address());
Eric Laurentd4692962014-05-05 18:13:44 -0700273 return INVALID_OPERATION;
274 }
275
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 index = mAvailableInputDevices.add(devDesc);
277 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800278 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 } else {
280 return NO_MEMORY;
281 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800282
François Gaffie2110e042015-03-24 08:41:51 +0100283 // Propagate device availability to Engine
284 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700288 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700290 ALOGW("setDeviceConnectionState() device not connected: %d", device);
291 return INVALID_OPERATION;
292 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700293
294 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
295
296 // Set Disconnect to HALs
François Gaffieaca677c2018-05-03 10:47:50 +0200297 broadcastDeviceConnectionState(device, state, devDesc->address());
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
François Gaffieaca677c2018-05-03 10:47:50 +0200299 checkInputsForDevice(devDesc, state, inputs, devDesc->address());
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700301
François Gaffie2110e042015-03-24 08:41:51 +0100302 // Propagate device availability to Engine
303 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700304 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700305
306 default:
307 ALOGE("setDeviceConnectionState() invalid state: %x", state);
308 return BAD_VALUE;
309 }
310
Eric Laurentd4692962014-05-05 18:13:44 -0700311 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700312 // As the input device list can impact the output device selection, update
313 // getDeviceForStrategy() cache
314 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700315
Eric Laurent87ffa392015-05-22 10:32:38 -0700316 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700317 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
318 updateCallRouting(newDevice);
319 }
320
Eric Laurentd60560a2015-04-10 11:31:20 -0700321 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
322 cleanUpForDevice(devDesc);
323 }
324
Eric Laurentb52c1522014-05-20 11:27:36 -0700325 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700326 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700327 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700328
329 ALOGW("setDeviceConnectionState() invalid device: %x", device);
330 return BAD_VALUE;
331}
332
Eric Laurente0720872014-03-11 09:30:41 -0700333audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100334 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700335{
Eric Laurent634b7142016-04-20 13:48:02 -0700336 sp<DeviceDescriptor> devDesc =
337 mHwModules.getDeviceDescriptor(device, device_address, "",
338 (strlen(device_address) != 0)/*matchAddress*/);
339
340 if (devDesc == 0) {
341 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
342 device, device_address);
343 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
344 }
François Gaffie53615e22015-03-19 09:24:12 +0100345
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 DeviceVector *deviceVector;
347
Eric Laurente552edb2014-03-10 17:42:56 -0700348 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 deviceVector = &mAvailableInputDevices;
352 } else {
353 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
354 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 }
Eric Laurent634b7142016-04-20 13:48:02 -0700356
357 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
358 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800359}
360
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800361status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
362 const char *device_address,
363 const char *device_name)
364{
365 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700366 String8 reply;
367 AudioParameter param;
368 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800369
370 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
371 device, device_address, device_name);
372
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800373 // connect/disconnect only 1 device at a time
374 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
375
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800376 // Check if the device is currently connected
377 sp<DeviceDescriptor> devDesc =
378 mHwModules.getDeviceDescriptor(device, device_address, device_name);
379 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
380 if (index < 0) {
381 // Nothing to do: device is not connected
382 return NO_ERROR;
383 }
384
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700385 // For offloaded A2DP, Hw modules may have the capability to
386 // configure codecs. Check if any of the loaded hw modules
387 // supports this.
388 // If supported, send a set parameter to configure A2DP codecs
389 // and return. No need to toggle device state.
390 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
391 reply = mpClientInterface->getParameters(
392 AUDIO_IO_HANDLE_NONE,
393 String8(AudioParameter::keyReconfigA2dpSupported));
394 AudioParameter repliedParameters(reply);
395 repliedParameters.getInt(
396 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
397 if (isReconfigA2dpSupported) {
398 const String8 key(AudioParameter::keyReconfigA2dp);
399 param.add(key, String8("true"));
400 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
401 return NO_ERROR;
402 }
403 }
404
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800405 // Toggle the device state: UNAVAILABLE -> AVAILABLE
406 // This will force reading again the device configuration
407 status = setDeviceConnectionState(device,
408 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
409 device_address, device_name);
410 if (status != NO_ERROR) {
411 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
412 status);
413 return status;
414 }
415
416 status = setDeviceConnectionState(device,
417 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
418 device_address, device_name);
419 if (status != NO_ERROR) {
420 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
421 status);
422 return status;
423 }
424
425 return NO_ERROR;
426}
427
Eric Laurentdc462862016-07-19 12:29:53 -0700428uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429{
430 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700431 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700432
Andy Hunga76c7de2016-12-13 19:14:31 -0800433 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700434 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700435 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800436 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
438
439 // release existing RX patch if any
440 if (mCallRxPatch != 0) {
441 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
442 mCallRxPatch.clear();
443 }
444 // release TX patch if any
445 if (mCallTxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
447 mCallTxPatch.clear();
448 }
449
450 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
451 // via setOutputDevice() on primary output.
452 // Otherwise, create two audio patches for TX and RX path.
453 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700454 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700455 // If the TX device is also on the primary HW module, setOutputDevice() will take care
456 // of it due to legacy implementation. If not, create a patch.
457 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
458 == AUDIO_DEVICE_NONE) {
459 createTxPatch = true;
460 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700461 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800462 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 createTxPatch = true;
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
467 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469 return muteWaitMs;
470}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700471
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
473 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700474 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 sp<DeviceDescriptor> txSourceDeviceDesc;
477 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700478 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
479 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800480 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700481 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
482 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 }
484
485 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
486 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800487 audio_io_handle_t output = selectOutput(outputs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 // request to reuse existing output stream if one is already opened to reach the target device
489 if (output != AUDIO_IO_HANDLE_NONE) {
490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
491 ALOG_ASSERT(!outputDesc->isDuplicated(),
492 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700493 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800494 }
495
496 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700497 // terminate active capture if on the same HW module as the call TX source device
498 // FIXME: would be better to refine to only inputs whose profile connects to the
499 // call TX device but this information is not in the audio patch and logic here must be
500 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800501 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800502 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700503 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700504 }
505 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700506 }
Eric Laurentdc462862016-07-19 12:29:53 -0700507
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800508 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700509 status_t status = mpClientInterface->createAudioPatch(
510 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800511 ALOGW_IF(status != NO_ERROR,
512 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
513 sp<AudioPatch> audioPatch;
514 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700515 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800516 audioPatch->mAfPatchHandle = afPatchHandle;
517 audioPatch->mUid = mUidCached;
518 }
519 return audioPatch;
520}
521
Mikhail Naganovdc769682018-05-04 15:34:08 -0700522sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100523 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700524 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800525 ALOG_ASSERT(!deviceList.isEmpty(),
526 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528}
529
Mikhail Naganov100f0122018-11-29 11:22:16 -0800530audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
531 const DeviceVector& devices, const char *moduleId) const {
532 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
533 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
534}
535
536bool AudioPolicyManager::isDeviceOfModule(
537 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
538 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
539 if (module != 0) {
540 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
541 .indexOf(devDesc) != NAME_NOT_FOUND
542 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
543 .indexOf(devDesc) != NAME_NOT_FOUND;
544 }
545 return false;
546}
547
Eric Laurente0720872014-03-11 09:30:41 -0700548void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700549{
550 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100551 // store previous phone state for management of sonification strategy below
552 int oldState = mEngine->getPhoneState();
553
554 if (mEngine->setPhoneState(state) != NO_ERROR) {
555 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 return;
557 }
François Gaffie2110e042015-03-24 08:41:51 +0100558 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700559 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700560 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 }
564
François Gaffie2110e042015-03-24 08:41:51 +0100565 /**
566 * Switching to or from incall state or switching between telephony and VoIP lead to force
567 * routing command.
568 */
569 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
570 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700573 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700574
Eric Laurente552edb2014-03-10 17:42:56 -0700575 int delayMs = 0;
576 if (isStateInCall(state)) {
577 nsecs_t sysTime = systemTime();
578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700580 // mute media and sonification strategies and delay device switch by the largest
581 // latency of any output where either strategy is active.
582 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100583 if ((isStrategyActive(desc, STRATEGY_MEDIA,
584 SONIFICATION_HEADSET_MUSIC_DELAY,
585 sysTime) ||
586 isStrategyActive(desc, STRATEGY_SONIFICATION,
587 SONIFICATION_HEADSET_MUSIC_DELAY,
588 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700589 (delayMs < (int)desc->latency()*2)) {
590 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700591 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 setStrategyMute(STRATEGY_MEDIA, true, desc);
593 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700594 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
596 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700597 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
598 }
599 }
600
Eric Laurent87ffa392015-05-22 10:32:38 -0700601 if (hasPrimaryOutput()) {
602 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
603 // the device returned is not necessarily reachable via this output
604 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
605 // force routing command to audio hardware when ending call
606 // even if no device change is needed
607 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
608 rxDevice = mPrimaryOutput->device();
609 }
Eric Laurente552edb2014-03-10 17:42:56 -0700610
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 if (state == AUDIO_MODE_IN_CALL) {
612 updateCallRouting(rxDevice, delayMs);
613 } else if (oldState == AUDIO_MODE_IN_CALL) {
614 if (mCallRxPatch != 0) {
615 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
616 mCallRxPatch.clear();
617 }
618 if (mCallTxPatch != 0) {
619 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
620 mCallTxPatch.clear();
621 }
622 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
623 } else {
624 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700626 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627
628 // reevaluate routing on all outputs in case tracks have been started during the call
629 for (size_t i = 0; i < mOutputs.size(); i++) {
630 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
631 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
632 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800633 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700634 }
635 }
636
Eric Laurente552edb2014-03-10 17:42:56 -0700637 if (isStateInCall(state)) {
638 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700639 // force reevaluating accessibility routing when call starts
640 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700641 }
642
643 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 if (state == AUDIO_MODE_RINGTONE &&
645 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700646 mLimitRingtoneVolume = true;
647 } else {
648 mLimitRingtoneVolume = false;
649 }
650}
651
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700652audio_mode_t AudioPolicyManager::getPhoneState() {
653 return mEngine->getPhoneState();
654}
655
Eric Laurente0720872014-03-11 09:30:41 -0700656void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700657 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700658{
François Gaffie2110e042015-03-24 08:41:51 +0100659 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700660 if (config == mEngine->getForceUse(usage)) {
661 return;
662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663
François Gaffie2110e042015-03-24 08:41:51 +0100664 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
665 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
666 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700667 }
François Gaffie2110e042015-03-24 08:41:51 +0100668 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
669 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
670 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700671
672 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700673 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800674
Eric Laurentdc462862016-07-19 12:29:53 -0700675 //FIXME: workaround for truncated touch sounds
676 // to be removed when the problem is handled by system UI
677 uint32_t delayMs = 0;
678 uint32_t waitMs = 0;
679 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
680 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
681 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700684 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700687 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
688 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
689 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700690 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
691 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700694 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
696 }
697
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800698 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800699 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700700 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800701 if (activeDesc->mProfile->getSupportedDevices().types() &
702 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
703 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700704 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800705 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700706 }
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708}
709
Eric Laurente0720872014-03-11 09:30:41 -0700710void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700711{
712 ALOGV("setSystemProperty() property %s, value %s", property, value);
713}
714
Michael Chana94fbb22018-04-24 14:31:19 +1000715// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
716// search to profiles for direct outputs.
717sp<IOProfile> AudioPolicyManager::getProfileForOutput(
718 audio_devices_t device,
719 uint32_t samplingRate,
720 audio_format_t format,
721 audio_channel_mask_t channelMask,
722 audio_output_flags_t flags,
723 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700724{
Michael Chana94fbb22018-04-24 14:31:19 +1000725 if (directOnly) {
726 // only retain flags that will drive the direct output profile selection
727 // if explicitly requested
728 static const uint32_t kRelevantFlags =
729 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
730 AUDIO_OUTPUT_FLAG_VOIP_RX);
731 flags =
732 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
733 }
Eric Laurent861a6282015-05-18 15:40:16 -0700734
735 sp<IOProfile> profile;
736
Mikhail Naganovd4120142017-12-06 15:49:22 -0800737 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800738 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700740 samplingRate, NULL /*updatedSamplingRate*/,
741 format, NULL /*updatedFormat*/,
742 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700743 flags)) {
744 continue;
745 }
746 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100747 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700748 continue;
749 }
Michael Chana94fbb22018-04-24 14:31:19 +1000750 if (!directOnly) return curProfile;
751 // when searching for direct outputs, if several profiles are compatible, give priority
752 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100753 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700754 continue;
755 }
756 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100757 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700758 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700759 }
Eric Laurente552edb2014-03-10 17:42:56 -0700760 }
761 }
Eric Laurent861a6282015-05-18 15:40:16 -0700762 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700763}
764
Eric Laurentf4e63452017-11-06 19:31:46 +0000765audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700766{
Eric Laurent3b73df72014-03-11 09:06:29 -0700767 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800769
770 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
771 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
772 // format, flags, etc. This may result in some discrepancy for functions that utilize
773 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
774 // and AudioSystem::getOutputSamplingRate().
775
Eric Laurentf4e63452017-11-06 19:31:46 +0000776 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
jiabin40573322018-11-08 12:08:02 -0800777 audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700778
Eric Laurentf4e63452017-11-06 19:31:46 +0000779 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
780 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781}
782
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700783status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
784 const audio_attributes_t *srcAttr,
785 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700787 if (srcAttr != NULL) {
788 if (!isValidAttributes(srcAttr)) {
789 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
790 __func__,
791 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
792 srcAttr->tags);
793 return BAD_VALUE;
794 }
795 *dstAttr = *srcAttr;
796 } else {
797 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
798 ALOGE("%s: invalid stream type", __func__);
799 return BAD_VALUE;
800 }
801 stream_type_to_audio_attributes(srcStream, dstAttr);
802 }
803 return NO_ERROR;
804}
805
806status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
807 audio_io_handle_t *output,
808 audio_session_t session,
809 const audio_attributes_t *attr,
810 audio_stream_type_t *stream,
811 uid_t uid,
812 const audio_config_t *config,
813 audio_output_flags_t *flags,
814 audio_port_handle_t *selectedDeviceId)
815{
Eric Laurent8fc147b2018-07-22 19:13:55 -0700816 DeviceVector outputDevices;
817 routing_strategy strategy;
818 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700819 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820 audio_devices_t msdDevice =
821 getModuleDeviceTypes(mAvailableOutputDevices, AUDIO_HARDWARE_MODULE_ID_MSD);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700822
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700823 status_t status = getAudioAttributes(resultAttr, attr, *stream);
824 if (status != NO_ERROR) {
825 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700826 }
827
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700828 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700829 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700830 __func__,
831 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Eric Laurent97ac8712018-07-27 18:59:02 -0700832 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700833
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700834 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700835
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700836 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700837
Scott Randolph7b1fd232018-06-18 15:33:03 -0700838 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700839 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
840 sp<DeviceDescriptor> deviceDesc =
841 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
842 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700843 } else {
844 // If no explict route, is there a matching dynamic policy that applies?
845 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700846 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700847 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
848 if (!audio_has_proportional_frames(config->format)) {
849 return BAD_VALUE;
850 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700851 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700852 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700853 AudioMix *mix = desc->mPolicyMix;
854 sp<DeviceDescriptor> deviceDesc =
855 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
856 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700857 ALOGV("%s returns output %d", __func__, *output);
858 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700859 }
860
861 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700862 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
863 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700864 return BAD_VALUE;
865 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700866 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700867 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700868
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700869 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200870 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700871 }
872
Nadav Barb2f18162018-07-18 13:01:53 +0300873 // Set incall music only if device was explicitly set, and fallback to the device which is
874 // chosen by the engine if not.
875 // FIXME: provide a more generic approach which is not device specific and move this back
876 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200877 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300878 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700879 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300880 audio_is_linear_pcm(config->format) &&
881 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700882 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300883 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
884 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700885 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300886 device = mEngine->getDeviceForStrategy(strategy);
887 }
888 }
889
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700890 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800891 "flags %#x",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700892 __func__, device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700893
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100894 *output = AUDIO_IO_HANDLE_NONE;
895 if (msdDevice != AUDIO_DEVICE_NONE) {
896 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
897 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
898 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
899 __func__, msdDevice, device);
900 device = msdDevice;
901 } else {
902 *output = AUDIO_IO_HANDLE_NONE;
903 }
904 }
905 if (*output == AUDIO_IO_HANDLE_NONE) {
906 *output = getOutputForDevice(device, session, *stream, config, flags);
907 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800908 if (*output == AUDIO_IO_HANDLE_NONE) {
909 return INVALID_OPERATION;
910 }
Paul McLeanaa981192015-03-21 09:55:15 -0700911
Eric Laurent8fc147b2018-07-22 19:13:55 -0700912 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +0200913 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700914
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700915 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
916
917 return NO_ERROR;
918}
919
920status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
921 audio_io_handle_t *output,
922 audio_session_t session,
923 audio_stream_type_t *stream,
924 uid_t uid,
925 const audio_config_t *config,
926 audio_output_flags_t *flags,
927 audio_port_handle_t *selectedDeviceId,
928 audio_port_handle_t *portId)
929{
930 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
931 if (*portId != AUDIO_PORT_HANDLE_NONE) {
932 return INVALID_OPERATION;
933 }
934 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
935 audio_attributes_t resultAttr;
936 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
937 config, flags, selectedDeviceId);
938 if (status != NO_ERROR) {
939 return status;
940 }
941
Eric Laurent8fc147b2018-07-22 19:13:55 -0700942 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
943 .format = config->format,
944 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700945 *portId = AudioPort::getNextUniqueId();
946
Eric Laurent8fc147b2018-07-22 19:13:55 -0700947 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700948 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Eric Laurent97ac8712018-07-27 18:59:02 -0700949 requestedDeviceId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700951 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700952 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700953 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700954
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700955 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
956 __func__, *output, requestedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700957
Eric Laurente83b55d2014-11-14 10:06:21 -0800958 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700959}
960
961audio_io_handle_t AudioPolicyManager::getOutputForDevice(
962 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800963 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800965 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200966 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967{
Andy Hungc88b0642018-04-27 15:42:35 -0700968 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700969 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700970
Eric Laurente552edb2014-03-10 17:42:56 -0700971 // open a direct output if required by specified parameters
972 //force direct flag if offload flag is set: offloading implies a direct output stream
973 // and all common behaviors are driven by checking only the direct flag
974 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200975 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
976 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700977 }
Nadav Bar766fb022018-01-07 12:18:03 +0200978 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
979 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700980 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800981 // only allow deep buffering for music stream type
982 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200983 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700984 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200985 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700986 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
987 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200988 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800989 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700990 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200991 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700992 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200993 audio_is_linear_pcm(config->format) &&
994 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200995 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700996 AUDIO_OUTPUT_FLAG_DIRECT);
997 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700998 }
Eric Laurente552edb2014-03-10 17:42:56 -0700999
Nadav Bar766fb022018-01-07 12:18:03 +02001000
Eric Laurentb732cf52014-09-24 19:08:21 -07001001 sp<IOProfile> profile;
1002
1003 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001004 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001005 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001006 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1007 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001008 goto non_direct_output;
1009 }
1010
Andy Hung2ddee192015-12-18 17:34:44 -08001011 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1012 // This prevents creating an offloaded track and tearing it down immediately after start
1013 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001014 // FIXME: We should check the audio session here but we do not have it in this context.
1015 // This may prevent offloading in rare situations where effects are left active by apps
1016 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001017
Nadav Bar766fb022018-01-07 12:18:03 +02001018 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001019 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Michael Chana94fbb22018-04-24 14:31:19 +10001020 profile = getProfileForOutput(device,
1021 config->sample_rate,
1022 config->format,
1023 config->channel_mask,
1024 (audio_output_flags_t)*flags,
1025 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
Eric Laurent1c333e22014-05-20 10:48:17 -07001028 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001029 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1030 for (size_t i = 0; i < mOutputs.size(); i++) {
1031 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1032 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1033 // reuse direct output if currently open by the same client
1034 // and configured with same parameters
1035 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001036 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001037 (config->channel_mask == desc->mChannelMask) &&
1038 (session == desc->mDirectClientSession)) {
1039 desc->mDirectOpenCount++;
1040 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
1041 mOutputs.keyAt(i), session);
1042 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 }
1044 }
1045 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001046
1047 if (!profile->canOpenNewIo()) {
1048 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
Eric Laurent861a6282015-05-18 15:40:16 -07001050
Eric Laurent3974e3b2017-12-07 17:58:43 -08001051 sp<SwAudioOutputDescriptor> outputDesc =
1052 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001053
Mikhail Naganov708e0382018-05-30 09:53:04 -07001054 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +02001055 String8 address = getFirstDeviceAddress(outputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001056
Dean Wheatley3023b382018-08-09 07:42:40 +10001057 // MSD patch may be using the only output stream that can service this request. Release
1058 // MSD patch to prioritize this request over any active output on MSD.
1059 AudioPatchCollection msdPatches = getMsdPatches();
1060 for (size_t i = 0; i < msdPatches.size(); i++) {
1061 const auto& patch = msdPatches[i];
1062 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1063 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1064 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1065 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1066 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1067 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1068 releaseAudioPatch(patch->mHandle, mUidCached);
1069 break;
1070 }
1071 }
1072 }
1073
Nadav Bar766fb022018-01-07 12:18:03 +02001074 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001075
1076 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001077 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001078 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001079 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001080 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1081 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1082 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1083 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1084 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001085 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001086 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001088 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001089 if (audio_is_linear_pcm(config->format) &&
1090 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001091 goto non_direct_output;
1092 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001093 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001094 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001096 outputDesc->mDirectClientSession = session;
1097
Eric Laurente552edb2014-03-10 17:42:56 -07001098 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001099 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001100 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001101 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001102 return output;
1103 }
1104
Eric Laurentb732cf52014-09-24 19:08:21 -07001105non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001106
1107 // A request for HW A/V sync cannot fallback to a mixed output because time
1108 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001109 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001110 return AUDIO_IO_HANDLE_NONE;
1111 }
1112
Eric Laurente552edb2014-03-10 17:42:56 -07001113 // ignoring channel mask due to downmix capability in mixer
1114
1115 // open a non direct output
1116
1117 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001118 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001119 // get which output is suitable for the specified stream. The actual
1120 // routing change will happen when startOutput() will be called
1121 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1122
Eric Laurent8838a382014-09-08 16:44:28 -07001123 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001124 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001125 output = selectOutput(outputs, *flags, config->format,
1126 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001127 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001128 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001129 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001130 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001131
Eric Laurente552edb2014-03-10 17:42:56 -07001132 return output;
1133}
1134
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001135sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001136 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001137 if (msdModule != 0) {
1138 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1139 msdModule->getHandle());
1140 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1141 }
1142 return 0;
1143}
1144
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001145const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1146 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001147 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1148 if (msdModule != 0) {
1149 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1150 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1151 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1152 const struct audio_port_config *source = &patch->mPatch.sources[j];
1153 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1154 source->ext.device.hw_module == msdModule->getHandle()) {
1155 msdPatches.addAudioPatch(patch->mHandle, patch);
1156 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 }
1158 }
1159 }
1160 return msdPatches;
1161}
1162
1163status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1164 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1165{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001166 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001167 if (msdModule == nullptr) {
1168 ALOGE("%s() unable to get MSD module", __func__);
1169 return NO_INIT;
1170 }
1171 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1172 if (deviceModule == nullptr) {
1173 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1174 return NO_INIT;
1175 }
1176 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1177 if (inputProfiles.isEmpty()) {
1178 ALOGE("%s() no input profiles for MSD module", __func__);
1179 return NO_INIT;
1180 }
1181 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1182 if (outputProfiles.isEmpty()) {
1183 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1184 return NO_INIT;
1185 }
1186 AudioProfileVector msdProfiles;
1187 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1188 for (const auto &inProfile : inputProfiles) {
1189 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1190 msdProfiles.appendVector(inProfile->getAudioProfiles());
1191 }
1192 }
1193 AudioProfileVector deviceProfiles;
1194 for (const auto &outProfile : outputProfiles) {
1195 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1196 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1197 }
1198 }
1199 struct audio_config_base bestSinkConfig;
1200 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1201 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1202 &bestSinkConfig);
1203 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001204 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1205 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001206 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001207 }
1208 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1209 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1210 sinkConfig->format = bestSinkConfig.format;
1211 // For encoded streams force direct flag to prevent downstream mixing.
1212 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1213 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1214 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1215 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1216 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1217 sourceConfig->format = bestSinkConfig.format;
1218 // Copy input stream directly without any processing (e.g. resampling).
1219 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1220 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1221 if (hwAvSync) {
1222 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1223 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1224 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1225 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1226 }
1227 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1228 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1229 sinkConfig->config_mask |= config_mask;
1230 sourceConfig->config_mask |= config_mask;
1231 return NO_ERROR;
1232}
1233
1234PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1235{
1236 PatchBuilder patchBuilder;
1237 patchBuilder.addSource(getMsdAudioInDevice()).
1238 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1239 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1240 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1241 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1242 // For now, we just forcefully try with HwAvSync first.
1243 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1244 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1245 getBestMsdAudioProfileFor(
1246 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1247 if (res == NO_ERROR) {
1248 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1249 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1250 }
1251 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1252 " supporting PCM format conversion.", __func__);
1253 return patchBuilder;
1254}
1255
1256status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1257 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1258 if (outputDevice == AUDIO_DEVICE_NONE) {
1259 // Use media strategy for unspecified output device. This should only
1260 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1261 // therefore invalidate explicit routing requests.
1262 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1263 }
1264 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1265 const struct audio_patch* patch = patchBuilder.patch();
1266 const AudioPatchCollection msdPatches = getMsdPatches();
1267 if (!msdPatches.isEmpty()) {
1268 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1269 "The current MSD prototype only supports one output patch");
1270 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1271 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1272 return NO_ERROR;
1273 }
1274 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1275 }
1276 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1277 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1278 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1279 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1280 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1281 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1282 return status;
1283}
1284
Eric Laurente0720872014-03-11 09:30:41 -07001285audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001286 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001287 audio_format_t format,
1288 audio_channel_mask_t channelMask,
1289 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001290{
1291 // select one output among several that provide a path to a particular device or set of
1292 // devices (the list was previously build by getOutputsForDevice()).
1293 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001294 // 1: the output supporting haptic playback when requesting haptic playback
1295 // 2: the output with the highest number of requested policy flags
1296 // 3: the output with the bit depth the closest to the requested one
1297 // 4: the primary output
1298 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001299
1300 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
1303 if (outputs.size() == 1) {
1304 return outputs[0];
1305 }
1306
1307 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001308 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1309 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001310 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1311 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1312 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001313 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1314 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001315
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001316 for (audio_io_handle_t output : outputs) {
1317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001318 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001319 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1320 continue;
1321 }
jiabin40573322018-11-08 12:08:02 -08001322 // If haptic channel is specified, use the haptic output if present.
1323 // When using haptic output, same audio format and sample rate are required.
1324 if (hapticChannelCount > 0) {
1325 // If haptic channel is specified, use the first output that
1326 // support haptic playback.
1327 if (audio_channel_count_from_out_mask(
1328 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1329 && format == outputDesc->mFormat
1330 && samplingRate == outputDesc->mSamplingRate) {
1331 return output;
1332 }
1333 } else {
1334 // When haptic channel is not specified, skip haptic output.
1335 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1336 continue;
1337 }
1338 }
1339
Eric Laurent8838a382014-09-08 16:44:28 -07001340 // if a valid format is specified, skip output if not compatible
1341 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001342 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001343 continue;
1344 }
Eric Laurente6930022016-02-11 10:20:40 -08001345 if (AudioPort::isBetterFormatMatch(
1346 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001347 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001348 bestFormat = outputDesc->mFormat;
1349 }
Eric Laurent8838a382014-09-08 16:44:28 -07001350 }
1351
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001352 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001353 if (commonFlags >= maxCommonFlags) {
1354 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001355 if (format != AUDIO_FORMAT_INVALID
1356 && AudioPort::isBetterFormatMatch(
1357 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001358 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001359 bestFormatForFlags = outputDesc->mFormat;
1360 }
1361 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001362 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001363 maxCommonFlags = commonFlags;
1364 bestFormatForFlags = outputDesc->mFormat;
1365 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001366 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001367 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001368 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001369 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001370 }
1371 }
1372 }
1373
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001374 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001375 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001376 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001377 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001378 return outputForFormat;
1379 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001380 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001381 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001382 }
1383
1384 return outputs[0];
1385}
1386
Eric Laurent8fc147b2018-07-22 19:13:55 -07001387status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001388{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001389 ALOGV("%s portId %d", __FUNCTION__, portId);
1390
1391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1392 if (outputDesc == 0) {
1393 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001394 return BAD_VALUE;
1395 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001396 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001397
Eric Laurent8fc147b2018-07-22 19:13:55 -07001398 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001399 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001400
Eric Laurent733ce942017-12-07 12:18:25 -08001401 status_t status = outputDesc->start();
1402 if (status != NO_ERROR) {
1403 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001404 }
1405
Eric Laurent97ac8712018-07-27 18:59:02 -07001406 uint32_t delayMs;
1407 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001408
1409 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001410 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001411 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001412 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001413 if (delayMs != 0) {
1414 usleep(delayMs * 1000);
1415 }
1416
1417 return status;
1418}
1419
Eric Laurent97ac8712018-07-27 18:59:02 -07001420status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1421 const sp<TrackClientDescriptor>& client,
1422 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001423{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001424 // cannot start playback of STREAM_TTS if any other output is being used
1425 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001426
1427 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001428 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001429 if (stream == AUDIO_STREAM_TTS) {
1430 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001431 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001432 return INVALID_OPERATION;
1433 } else {
1434 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1435 }
1436 } else {
1437 // some playback other than beacon starts
1438 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1439 }
1440
Eric Laurent77305a62016-07-25 16:39:22 -07001441 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001442 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001443 bool force = !outputDesc->isActive() &&
1444 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001445
Eric Laurent97ac8712018-07-27 18:59:02 -07001446 audio_devices_t device = AUDIO_DEVICE_NONE;
1447 AudioMix *policyMix = NULL;
1448 const char *address = NULL;
1449 if (outputDesc->mPolicyMix != NULL) {
1450 policyMix = outputDesc->mPolicyMix;
1451 address = policyMix->mDeviceAddress.string();
1452 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1453 device = policyMix->mDeviceType;
1454 } else {
1455 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1456 }
1457 }
1458
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001459 // requiresMuteCheck is false when we can bypass mute strategy.
1460 // It covers a common case when there is no materially active audio
1461 // and muting would result in unnecessary delay and dropped audio.
1462 const uint32_t outputLatencyMs = outputDesc->latency();
1463 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1464
Eric Laurente552edb2014-03-10 17:42:56 -07001465 // increment usage count for this stream on the requested output:
1466 // NOTE that the usage count is the same for duplicated output and hardware output which is
1467 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001468 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001469
1470 if (client->hasPreferredDevice(true)) {
1471 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1472 if (device != outputDesc->device()) {
1473 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1474 }
1475 }
Eric Laurente552edb2014-03-10 17:42:56 -07001476
Eric Laurent36829f92017-04-07 19:04:42 -07001477 if (stream == AUDIO_STREAM_MUSIC) {
1478 selectOutputForMusicEffects();
1479 }
1480
Eric Laurent592dd7b2018-08-05 18:58:48 -07001481 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001482 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001483 if (device == AUDIO_DEVICE_NONE) {
1484 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001485 }
Eric Laurent36829f92017-04-07 19:04:42 -07001486
Eric Laurente552edb2014-03-10 17:42:56 -07001487 routing_strategy strategy = getStrategy(stream);
1488 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001489 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1490 (beaconMuteLatency > 0);
1491 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001492 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001494 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001495 // An output has a shared device if
1496 // - managed by the same hw module
1497 // - supports the currently selected device
1498 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1499 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1500
Eric Laurent77305a62016-07-25 16:39:22 -07001501 // force a device change if any other output is:
1502 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001503 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001504 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001505 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001506 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001507 // change the device currently selected by the other output.
1508 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001509 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001510 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001511 force = true;
1512 }
1513 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001514 // a notification so that audio focus effect can propagate, or that a mute/unmute
1515 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001516 const uint32_t latencyMs = desc->latency();
1517 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1518
1519 if (shouldWait && isActive && (waitMs < latencyMs)) {
1520 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001521 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001522
1523 // Require mute check if another output is on a shared device
1524 // and currently active to have proper drain and avoid pops.
1525 // Note restoring AudioTracks onto this output needs to invoke
1526 // a volume ramp if there is no mute.
1527 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001528 }
1529 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001530
1531 const uint32_t muteWaitMs =
1532 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001533
Eric Laurente552edb2014-03-10 17:42:56 -07001534 // apply volume rules for current stream and device if necessary
1535 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001536 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001537 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001538 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001539
1540 // update the outputs if starting an output with a stream that can affect notification
1541 // routing
1542 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001543
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001544 // force reevaluating accessibility routing when ringtone or alarm starts
1545 if (strategy == STRATEGY_SONIFICATION) {
1546 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1547 }
Eric Laurentdc462862016-07-19 12:29:53 -07001548
1549 if (waitMs > muteWaitMs) {
1550 *delayMs = waitMs - muteWaitMs;
1551 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001552
1553 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1554 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1555 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1556 // change occurs after the MixerThread starts and causes a stream volume
1557 // glitch.
1558 //
1559 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001560 }
Eric Laurentdc462862016-07-19 12:29:53 -07001561
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001562 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1563 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1564 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1565 }
1566
Eric Laurent97ac8712018-07-27 18:59:02 -07001567 // Automatically enable the remote submix input when output is started on a re routing mix
1568 // of type MIX_TYPE_RECORDERS
1569 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1570 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1571 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1572 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1573 address,
1574 "remote-submix");
1575 }
1576
Eric Laurente552edb2014-03-10 17:42:56 -07001577 return NO_ERROR;
1578}
1579
Eric Laurent8fc147b2018-07-22 19:13:55 -07001580status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001581{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001582 ALOGV("%s portId %d", __FUNCTION__, portId);
1583
1584 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1585 if (outputDesc == 0) {
1586 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001587 return BAD_VALUE;
1588 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001589 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001590
Eric Laurent97ac8712018-07-27 18:59:02 -07001591 ALOGV("stopOutput() output %d, stream %d, session %d",
1592 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001593
Eric Laurent97ac8712018-07-27 18:59:02 -07001594 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001595
Eric Laurent733ce942017-12-07 12:18:25 -08001596 if (status == NO_ERROR ) {
1597 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001598 }
1599 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001600}
1601
Eric Laurent97ac8712018-07-27 18:59:02 -07001602status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1603 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001604{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001605 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001606 audio_stream_type_t stream = client->stream();
1607
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001608 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1609
Eric Laurent592dd7b2018-08-05 18:58:48 -07001610 if (outputDesc->streamActiveCount(stream) > 0) {
1611 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001612 // Automatically disable the remote submix input when output is stopped on a
1613 // re routing mix of type MIX_TYPE_RECORDERS
1614 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1615 outputDesc->mPolicyMix != NULL &&
1616 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1617 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1618 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1619 outputDesc->mPolicyMix->mDeviceAddress,
1620 "remote-submix");
1621 }
1622 }
1623 bool forceDeviceUpdate = false;
1624 if (client->hasPreferredDevice(true)) {
1625 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1626 forceDeviceUpdate = true;
1627 }
1628
Eric Laurente552edb2014-03-10 17:42:56 -07001629 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001630 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001633 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001634 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001635 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001636 // delay the device switch by twice the latency because stopOutput() is executed when
1637 // the track stop() command is received and at that time the audio track buffer can
1638 // still contain data that needs to be drained. The latency only covers the audio HAL
1639 // and kernel buffers. Also the latency does not always include additional delay in the
1640 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001641 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001642
1643 // force restoring the device selection on other active outputs if it differs from the
1644 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001645 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001646 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001647 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001648 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001649 desc->isActive() &&
1650 outputDesc->sharesHwModuleWith(desc) &&
1651 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001652 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1653 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001654
Eric Laurentc75307b2015-03-17 15:29:32 -07001655 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001656 newDevice2,
1657 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001658 delayMs);
1659 // re-apply device specific volume if not done by setOutputDevice()
1660 if (!force) {
1661 applyStreamVolumes(desc, newDevice2, delayMs);
1662 }
Eric Laurente552edb2014-03-10 17:42:56 -07001663 }
1664 }
1665 // update the outputs if stopping one with a stream that can affect notification routing
1666 handleNotificationRoutingForStream(stream);
1667 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001668
1669 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1670 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1671 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1672 }
1673
Eric Laurent36829f92017-04-07 19:04:42 -07001674 if (stream == AUDIO_STREAM_MUSIC) {
1675 selectOutputForMusicEffects();
1676 }
Eric Laurente552edb2014-03-10 17:42:56 -07001677 return NO_ERROR;
1678 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001679 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001680 return INVALID_OPERATION;
1681 }
1682}
1683
Eric Laurent8fc147b2018-07-22 19:13:55 -07001684void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001685{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001686 ALOGV("%s portId %d", __FUNCTION__, portId);
1687
1688 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1689 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001690 // If an output descriptor is closed due to a device routing change,
1691 // then there are race conditions with releaseOutput from tracks
1692 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1693 // destroyed shortly thereafter.
1694 //
1695 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001696 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001697 return;
1698 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001699
1700 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001701
Eric Laurent8fc147b2018-07-22 19:13:55 -07001702 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1703 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001704 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001705 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001706 return;
1707 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001708 if (--outputDesc->mDirectOpenCount == 0) {
1709 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001710 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001711 }
1712 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001713 // stopOutput() needs to be successfully called before releaseOutput()
1714 // otherwise there may be inaccurate stream reference counts.
1715 // This is checked in outputDesc->removeClient below.
1716 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001717}
1718
Eric Laurentcaf7f482014-11-25 17:50:47 -08001719status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1720 audio_io_handle_t *input,
1721 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001722 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001723 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001724 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001725 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001726 input_type_t *inputType,
1727 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001728{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001729 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001730 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001731 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001732
Eric Laurentad2e7b92017-09-14 20:06:42 -07001733 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001734 // handle legacy remote submix case where the address was not always specified
1735 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001736 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001737 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001738 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001740 sp<AudioInputDescriptor> inputDesc;
1741 sp<RecordClientDescriptor> clientDesc;
1742 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001743 bool isSoundTrigger;
1744 audio_devices_t device;
1745
1746 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1747 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1748 return INVALID_OPERATION;
1749 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001750
Eric Laurentfe231122017-11-17 17:48:06 -08001751 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1752 inputSource = AUDIO_SOURCE_MIC;
1753 }
1754
Paul McLean466dc8e2015-04-17 13:15:36 -06001755 // Explicit routing?
François Gaffieaca677c2018-05-03 10:47:50 +02001756 sp<DeviceDescriptor> deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001757
Eric Laurentad2e7b92017-09-14 20:06:42 -07001758 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1759 // possible
1760 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1761 *input != AUDIO_IO_HANDLE_NONE) {
1762 ssize_t index = mInputs.indexOfKey(*input);
1763 if (index < 0) {
1764 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1765 status = BAD_VALUE;
1766 goto error;
1767 }
1768 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001769 RecordClientVector clients = inputDesc->getClientsForSession(session);
1770 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001771 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1772 status = BAD_VALUE;
1773 goto error;
1774 }
1775 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1776 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001777 // corresponds to a new client and is only permitted from the same UID.
1778 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001779 if (clients.size() > 1) {
1780 for (const auto& client : clients) {
1781 // The client map is ordered by key values (portId) and portIds are allocated
1782 // incrementaly. So the first client in this list is the one opened by audio flinger
1783 // when the mmap stream is created and should be ignored as it does not correspond
1784 // to an actual client
1785 if (client == *clients.cbegin()) {
1786 continue;
1787 }
1788 if (uid != client->uid() && !client->isSilenced()) {
1789 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1790 uid, client->portId(), client->uid());
1791 status = INVALID_OPERATION;
1792 goto error;
1793 }
Eric Laurent331679c2018-04-16 17:03:16 -07001794 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001795 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001796 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001797 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001798
Eric Laurent8f42ea12018-08-08 09:08:25 -07001799 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001800 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001801 }
1802
1803 *input = AUDIO_IO_HANDLE_NONE;
1804 *inputType = API_INPUT_INVALID;
1805
Eric Laurentad2e7b92017-09-14 20:06:42 -07001806 halInputSource = inputSource;
1807
Eric Laurentc447ded2015-01-06 08:47:05 -08001808 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001809 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1811 if (status != NO_ERROR) {
1812 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001813 }
1814 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001815 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1816 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001817 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001818 if (deviceDesc != 0) {
1819 device = deviceDesc->type();
1820 } else {
1821 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1822 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001823 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001824 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001825 status = BAD_VALUE;
1826 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001827 }
Eric Laurentc722f302014-12-10 11:21:49 -08001828 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001829 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001830 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1831 // there is an external policy, but this input is attached to a mix of recorders,
1832 // meaning it receives audio injected into the framework, so the recorder doesn't
1833 // know about it and is therefore considered "legacy"
1834 *inputType = API_INPUT_LEGACY;
1835 } else {
1836 // recording a mix of players defined by an external policy, we're rerouting for
1837 // an external policy
1838 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1839 }
Eric Laurentc722f302014-12-10 11:21:49 -08001840 } else if (audio_is_remote_submix_device(device)) {
1841 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001842 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001843 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1844 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001845 } else {
1846 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001847 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001848
Eric Laurent599c7582015-12-07 18:05:55 -08001849 }
1850
Eric Laurent8f42ea12018-08-08 09:08:25 -07001851 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001852 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001853 policyMix);
1854 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001855 status = INVALID_OPERATION;
1856 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001857 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001858
Eric Laurent8f42ea12018-08-08 09:08:25 -07001859exit:
1860
Mikhail Naganov708e0382018-05-30 09:53:04 -07001861 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
François Gaffieaca677c2018-05-03 10:47:50 +02001862 *selectedDeviceId = getFirstDeviceId(inputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001863
Eric Laurent8f42ea12018-08-08 09:08:25 -07001864 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1865 mSoundTriggerSessions.indexOfKey(session) > 0;
1866 *portId = AudioPort::getNextUniqueId();
1867
Eric Laurent8fc147b2018-07-22 19:13:55 -07001868 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001869 *attr, *config, requestedDeviceId,
1870 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001871 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001872 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001873
1874 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1875 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001876
Eric Laurent599c7582015-12-07 18:05:55 -08001877 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001878
1879error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001880 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001881}
1882
1883
1884audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1885 String8 address,
1886 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001887 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001888 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001889 audio_input_flags_t flags,
1890 AudioMix *policyMix)
1891{
1892 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1893 audio_source_t halInputSource = inputSource;
1894 bool isSoundTrigger = false;
1895
1896 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1897 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1898 if (index >= 0) {
1899 input = mSoundTriggerSessions.valueFor(session);
1900 isSoundTrigger = true;
1901 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1902 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1903 } else {
1904 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001905 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001906 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001907 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001908 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001909 }
1910
Andy Hungf129b032015-04-07 13:45:50 -07001911 // find a compatible input profile (not necessarily identical in parameters)
1912 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001913 // sampling rate and flags may be updated by getInputProfile
1914 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1915 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001916 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001917 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001918 audio_input_flags_t profileFlags = flags;
1919 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001920 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001921 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001922 profileSamplingRate, profileFormat, profileChannelMask,
1923 profileFlags);
1924 if (profile != 0) {
1925 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001926 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1927 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001928 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1929 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1930 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001931 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001932 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1933 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001934 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001935 }
Eric Laurente552edb2014-03-10 17:42:56 -07001936 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001937 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001938 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001939 if (samplingRate == 0) {
1940 samplingRate = profileSamplingRate;
1941 }
Eric Laurente552edb2014-03-10 17:42:56 -07001942
Eric Laurent322b4d22015-04-03 15:57:54 -07001943 if (profile->getModuleHandle() == 0) {
1944 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001945 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001946 }
1947
Eric Laurent3974e3b2017-12-07 17:58:43 -08001948 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001949 for (size_t i = 0; i < mInputs.size(); ) {
1950 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1951 if (desc->mProfile != profile) {
1952 continue;
1953 }
1954 // if sound trigger, reuse input if used by other sound trigger on same session
1955 // else
1956 // reuse input if active client app is not in IDLE state
1957 //
1958 RecordClientVector clients = desc->clientsList();
1959 bool doClose = false;
1960 for (const auto& client : clients) {
1961 if (isSoundTrigger != client->isSoundTrigger()) {
1962 continue;
1963 }
1964 if (client->isSoundTrigger()) {
1965 if (session == client->session()) {
1966 return desc->mIoHandle;
1967 }
1968 continue;
1969 }
1970 if (client->active() && client->appState() != APP_STATE_IDLE) {
1971 return desc->mIoHandle;
1972 }
1973 doClose = true;
1974 }
1975 if (doClose) {
1976 closeInput(desc->mIoHandle);
1977 } else {
1978 i++;
1979 }
1980 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001981 }
1982
Eric Laurentfe231122017-11-17 17:48:06 -08001983 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001984
Eric Laurentfe231122017-11-17 17:48:06 -08001985 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1986 lConfig.sample_rate = profileSamplingRate;
1987 lConfig.channel_mask = profileChannelMask;
1988 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001989
Eric Laurent53b810e2017-12-10 17:25:10 -08001990 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001991 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001992 // the inputs vector must be of size >= 1, but we don't want to crash here
François Gaffieaca677c2018-05-03 10:47:50 +02001993 address = getFirstDeviceAddress(inputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001994 }
1995
Eric Laurentfe231122017-11-17 17:48:06 -08001996 status_t status = inputDesc->open(&lConfig, device, address,
1997 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001998
1999 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002000 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002001 (profileSamplingRate != lConfig.sample_rate) ||
2002 !audio_formats_match(profileFormat, lConfig.format) ||
2003 (profileChannelMask != lConfig.channel_mask)) {
2004 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002005 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002006 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002007 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002008 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002009 }
Eric Laurent599c7582015-12-07 18:05:55 -08002010 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002011 }
2012
Eric Laurentc722f302014-12-10 11:21:49 -08002013 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002014
Eric Laurent599c7582015-12-07 18:05:55 -08002015 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002016 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002017
Eric Laurent599c7582015-12-07 18:05:55 -08002018 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002019}
2020
Eric Laurent4eb58f12018-12-07 16:41:02 -08002021status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002022{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002023 ALOGV("%s portId %d", __FUNCTION__, portId);
2024
2025 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2026 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002027 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002028 return BAD_VALUE;
2029 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002030 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002031 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002032 if (client->active()) {
2033 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2034 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002035 }
2036
Eric Laurent8f42ea12018-08-08 09:08:25 -07002037 audio_session_t session = client->session();
2038
Eric Laurent4eb58f12018-12-07 16:41:02 -08002039 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002040
Eric Laurent4eb58f12018-12-07 16:41:02 -08002041 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002042
Eric Laurent4eb58f12018-12-07 16:41:02 -08002043 status_t status = inputDesc->start();
2044 if (status != NO_ERROR) {
2045 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002046 }
Eric Laurente552edb2014-03-10 17:42:56 -07002047
Eric Laurent4eb58f12018-12-07 16:41:02 -08002048 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002049 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002050 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002051
Eric Laurent8f42ea12018-08-08 09:08:25 -07002052 // indicate active capture to sound trigger service if starting capture from a mic on
2053 // primary HW module
2054 audio_devices_t device = getNewInputDevice(inputDesc);
2055 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002056
Eric Laurent8f42ea12018-08-08 09:08:25 -07002057 if (inputDesc->activeCount() == 1) {
2058 // if input maps to a dynamic policy with an activity listener, notify of state change
2059 if ((inputDesc->mPolicyMix != NULL)
2060 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2061 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2062 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002063 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002064
Eric Laurent8f42ea12018-08-08 09:08:25 -07002065 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2066 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2067 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2068 SoundTrigger::setCaptureState(true);
2069 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002070
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 // automatically enable the remote submix output when input is started if not
2072 // used by a policy mix of type MIX_TYPE_RECORDERS
2073 // For remote submix (a virtual device), we open only one input per capture request.
2074 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2075 String8 address = String8("");
2076 if (inputDesc->mPolicyMix == NULL) {
2077 address = String8("0");
2078 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2079 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002080 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002081 if (address != "") {
2082 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2083 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2084 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002085 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002086 }
Eric Laurente552edb2014-03-10 17:42:56 -07002087 }
2088
Eric Laurent8f42ea12018-08-08 09:08:25 -07002089 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002090
Eric Laurente552edb2014-03-10 17:42:56 -07002091 return NO_ERROR;
2092}
2093
Eric Laurent8fc147b2018-07-22 19:13:55 -07002094status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002095{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002096 ALOGV("%s portId %d", __FUNCTION__, portId);
2097
2098 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2099 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002100 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002101 return BAD_VALUE;
2102 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002103 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002104 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002105 if (!client->active()) {
2106 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002107 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002108 }
2109
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002111
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112 inputDesc->stop();
2113 if (inputDesc->isActive()) {
2114 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2115 } else {
2116 // if input maps to a dynamic policy with an activity listener, notify of state change
2117 if ((inputDesc->mPolicyMix != NULL)
2118 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2119 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2120 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002121 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122
2123 // automatically disable the remote submix output when input is stopped if not
2124 // used by a policy mix of type MIX_TYPE_RECORDERS
2125 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2126 String8 address = String8("");
2127 if (inputDesc->mPolicyMix == NULL) {
2128 address = String8("0");
2129 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2130 address = inputDesc->mPolicyMix->mDeviceAddress;
2131 }
2132 if (address != "") {
2133 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2134 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2135 address, "remote-submix");
2136 }
2137 }
2138
2139 audio_devices_t device = inputDesc->mDevice;
2140 resetInputDevice(input);
2141
2142 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2143 // primary HW module
2144 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2145 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2146 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2147 SoundTrigger::setCaptureState(false);
2148 }
2149 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002150 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002151 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002152}
2153
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002155{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002156 ALOGV("%s portId %d", __FUNCTION__, portId);
2157
2158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2159 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002161 return;
2162 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002163 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002164 audio_io_handle_t input = inputDesc->mIoHandle;
2165
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002167
Andy Hung39efb7a2018-09-26 15:39:28 -07002168 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002169
Andy Hung39efb7a2018-09-26 15:39:28 -07002170 if (inputDesc->getClientCount() > 0) {
2171 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002172 return;
2173 }
2174
Eric Laurent05b90f82014-08-27 15:32:29 -07002175 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002176 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002177 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002178}
2179
Eric Laurent8f42ea12018-08-08 09:08:25 -07002180void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002181{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002182 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002183
2184 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002185 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002186 }
2187}
2188
Eric Laurent8f42ea12018-08-08 09:08:25 -07002189void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2190{
2191 stopInput(portId);
2192 releaseInput(portId);
2193}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002194
Eric Laurentd4692962014-05-05 18:13:44 -07002195void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002196 bool patchRemoved = false;
2197
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002198 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002199 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002200 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002201 if (patch_index >= 0) {
2202 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002203 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002204 mAudioPatches.removeItemsAt(patch_index);
2205 patchRemoved = true;
2206 }
Eric Laurentfe231122017-11-17 17:48:06 -08002207 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002208 }
2209 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002210 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002211 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002212
2213 if (patchRemoved) {
2214 mpClientInterface->onAudioPatchListUpdate();
2215 }
Eric Laurentd4692962014-05-05 18:13:44 -07002216}
2217
Eric Laurente0720872014-03-11 09:30:41 -07002218void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002219 int indexMin,
2220 int indexMax)
2221{
2222 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002223 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002224
2225 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002226 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2227 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002228 continue;
2229 }
2230 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002231 }
Eric Laurente552edb2014-03-10 17:42:56 -07002232}
2233
Eric Laurente0720872014-03-11 09:30:41 -07002234status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002235 int index,
2236 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002237{
2238
Nadav Bar7c605f62017-12-25 00:01:52 +02002239 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2240 // app that has MODIFY_PHONE_STATE permission.
2241 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2242 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002243 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002244 return BAD_VALUE;
2245 }
2246 if (!audio_is_output_device(device)) {
2247 return BAD_VALUE;
2248 }
2249
2250 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002251 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002252
Eric Laurent1fd372e2016-04-06 14:23:53 -07002253 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002254 stream, device, index);
2255
Eric Laurent28d09f02016-03-08 10:43:05 -08002256 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002257 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2258 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002259 continue;
2260 }
2261 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2262 }
Eric Laurente552edb2014-03-10 17:42:56 -07002263
Eric Laurent1fd372e2016-04-06 14:23:53 -07002264 // update volume on all outputs and streams matching the following:
2265 // - The requested stream (or a stream matching for volume control) is active on the output
2266 // - The device (or devices) selected by the strategy corresponding to this stream includes
2267 // the requested device
2268 // - For non default requested device, currently selected device on the output is either the
2269 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002270 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2271 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002272 status_t status = NO_ERROR;
2273 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002274 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002275 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002276 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002277 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002279 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002280 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002281 continue;
2282 }
Eric Laurent794fde22016-03-11 09:50:45 -08002283 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002284 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2285 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002286 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2287 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002288 continue;
2289 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002290 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002291 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002292 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002293 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002294 } else {
2295 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002296 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002297 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002298 // rescale index before applying to curStream as ranges may be different for
2299 // stream and curStream
2300 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002301 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002302 //FIXME: workaround for truncated touch sounds
2303 // delayed volume change for system stream to be removed when the problem is
2304 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002305 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002306 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002307 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002308 if (volStatus != NO_ERROR) {
2309 status = volStatus;
2310 }
2311 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002312 }
Eric Laurente552edb2014-03-10 17:42:56 -07002313 }
2314 return status;
2315}
2316
Eric Laurente0720872014-03-11 09:30:41 -07002317status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002318 int *index,
2319 audio_devices_t device)
2320{
2321 if (index == NULL) {
2322 return BAD_VALUE;
2323 }
2324 if (!audio_is_output_device(device)) {
2325 return BAD_VALUE;
2326 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002327 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002328 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002329 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002330 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2331 }
François Gaffiedfd74092015-03-19 12:10:59 +01002332 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002333
François Gaffied1ab2bd2015-12-02 18:20:06 +01002334 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002335 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2336 return NO_ERROR;
2337}
2338
Eric Laurent36829f92017-04-07 19:04:42 -07002339audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002340{
2341 // select one output among several suitable for global effects.
2342 // The priority is as follows:
2343 // 1: An offloaded output. If the effect ends up not being offloadable,
2344 // AudioFlinger will invalidate the track and the offloaded output
2345 // will be closed causing the effect to be moved to a PCM output.
2346 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002347 // 3: The primary output
2348 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002349
Eric Laurent3b73df72014-03-11 09:06:29 -07002350 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002351 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002352 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002353
Eric Laurent36829f92017-04-07 19:04:42 -07002354 if (outputs.size() == 0) {
2355 return AUDIO_IO_HANDLE_NONE;
2356 }
Eric Laurente552edb2014-03-10 17:42:56 -07002357
Eric Laurent36829f92017-04-07 19:04:42 -07002358 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2359 bool activeOnly = true;
2360
2361 while (output == AUDIO_IO_HANDLE_NONE) {
2362 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2363 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2364 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2365
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002366 for (audio_io_handle_t output : outputs) {
2367 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002368 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2369 continue;
2370 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002371 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2372 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002373 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002374 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002375 }
2376 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002377 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002378 }
2379 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002380 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002381 }
2382 }
2383 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2384 output = outputOffloaded;
2385 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2386 output = outputDeepBuffer;
2387 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2388 output = outputPrimary;
2389 } else {
2390 output = outputs[0];
2391 }
2392 activeOnly = false;
2393 }
2394
2395 if (output != mMusicEffectOutput) {
2396 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2397 mMusicEffectOutput = output;
2398 }
2399
2400 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002401 return output;
2402}
2403
Eric Laurent36829f92017-04-07 19:04:42 -07002404audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2405{
2406 return selectOutputForMusicEffects();
2407}
2408
Eric Laurente0720872014-03-11 09:30:41 -07002409status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002410 audio_io_handle_t io,
2411 uint32_t strategy,
2412 int session,
2413 int id)
2414{
2415 ssize_t index = mOutputs.indexOfKey(io);
2416 if (index < 0) {
2417 index = mInputs.indexOfKey(io);
2418 if (index < 0) {
2419 ALOGW("registerEffect() unknown io %d", io);
2420 return INVALID_OPERATION;
2421 }
2422 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002423 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002424}
2425
Eric Laurentc241b0d2018-11-28 09:08:49 -08002426status_t AudioPolicyManager::unregisterEffect(int id)
2427{
2428 if (mEffects.getEffect(id) == nullptr) {
2429 return INVALID_OPERATION;
2430 }
2431
2432 if (mEffects.isEffectEnabled(id)) {
2433 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2434 setEffectEnabled(id, false);
2435 }
2436 return mEffects.unregisterEffect(id);
2437}
2438
2439status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2440{
2441 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2442 if (effect == nullptr) {
2443 return INVALID_OPERATION;
2444 }
2445
2446 status_t status = mEffects.setEffectEnabled(id, enabled);
2447 if (status == NO_ERROR) {
2448 mInputs.trackEffectEnabled(effect, enabled);
2449 }
2450 return status;
2451}
2452
Eric Laurentc75307b2015-03-17 15:29:32 -07002453bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2454{
Eric Laurent28d09f02016-03-08 10:43:05 -08002455 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002456 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2457 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002458 continue;
2459 }
2460 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2461 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002462 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002463}
2464
2465bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2466{
2467 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2468}
2469
Eric Laurente0720872014-03-11 09:30:41 -07002470bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002471{
2472 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002473 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002474 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002475 return true;
2476 }
2477 }
2478 return false;
2479}
2480
Eric Laurent275e8e92014-11-30 15:14:47 -08002481// Register a list of custom mixes with their attributes and format.
2482// When a mix is registered, corresponding input and output profiles are
2483// added to the remote submix hw module. The profile contains only the
2484// parameters (sampling rate, format...) specified by the mix.
2485// The corresponding input remote submix device is also connected.
2486//
2487// When a remote submix device is connected, the address is checked to select the
2488// appropriate profile and the corresponding input or output stream is opened.
2489//
2490// When capture starts, getInputForAttr() will:
2491// - 1 look for a mix matching the address passed in attribtutes tags if any
2492// - 2 if none found, getDeviceForInputSource() will:
2493// - 2.1 look for a mix matching the attributes source
2494// - 2.2 if none found, default to device selection by policy rules
2495// At this time, the corresponding output remote submix device is also connected
2496// and active playback use cases can be transferred to this mix if needed when reconnecting
2497// after AudioTracks are invalidated
2498//
2499// When playback starts, getOutputForAttr() will:
2500// - 1 look for a mix matching the address passed in attribtutes tags if any
2501// - 2 if none found, look for a mix matching the attributes usage
2502// - 3 if none found, default to device and output selection by policy rules.
2503
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002504status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002505{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2507 status_t res = NO_ERROR;
2508
2509 sp<HwModule> rSubmixModule;
2510 // examine each mix's route type
2511 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002512 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002513 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002516 break;
2517 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002518 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002521 rSubmixModule = mHwModules.getModuleFromName(
2522 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2523 if (rSubmixModule == 0) {
2524 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2525 i);
2526 res = INVALID_OPERATION;
2527 break;
2528 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002530
Eric Laurent97ac8712018-07-27 18:59:02 -07002531 String8 address = mix.mDeviceAddress;
2532 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2533 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2534 } else {
2535 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2536 }
François Gaffie036e1e92015-03-19 10:16:24 +01002537
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002539 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 res = INVALID_OPERATION;
2541 break;
2542 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 audio_config_t outputConfig = mix.mFormat;
2544 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2546 // stereo and let audio flinger do the channel conversion if needed.
2547 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2548 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2549 rSubmixModule->addOutputProfile(address, &outputConfig,
2550 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2551 rSubmixModule->addInputProfile(address, &inputConfig,
2552 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2556 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2557 address.string(), "remote-submix");
2558 } else {
2559 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2560 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2561 address.string(), "remote-submix");
2562 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2564 String8 address = mix.mDeviceAddress;
2565 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002566 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2567 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002569 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2571 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2572 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2573 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2574 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2575 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002576 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2577 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002578 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002579 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002580 } else {
2581 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002582 }
2583 break;
2584 }
2585 }
2586
2587 if (res != NO_ERROR) {
2588 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002589 i, device, address.string());
2590 res = INVALID_OPERATION;
2591 break;
2592 } else if (!foundOutput) {
2593 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2594 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 res = INVALID_OPERATION;
2596 break;
2597 }
Eric Laurentc722f302014-12-10 11:21:49 -08002598 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002599 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 if (res != NO_ERROR) {
2601 unregisterPolicyMixes(mixes);
2602 }
2603 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002604}
2605
2606status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2607{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002608 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 status_t res = NO_ERROR;
2610 sp<HwModule> rSubmixModule;
2611 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002612 for (const auto& mix : mixes) {
2613 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002614
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002616 rSubmixModule = mHwModules.getModuleFromName(
2617 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2618 if (rSubmixModule == 0) {
2619 res = INVALID_OPERATION;
2620 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 }
2622 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002623
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002624 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002625
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002626 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2627 res = INVALID_OPERATION;
2628 continue;
2629 }
2630
2631 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2632 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2633 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2634 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2635 address.string(), "remote-submix");
2636 }
2637 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2638 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2639 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2640 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2641 address.string(), "remote-submix");
2642 }
2643 rSubmixModule->removeOutputProfile(address);
2644 rSubmixModule->removeInputProfile(address);
2645
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002646 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2647 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002648 res = INVALID_OPERATION;
2649 continue;
2650 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002651 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002652 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002653 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002654}
2655
Mikhail Naganov100f0122018-11-29 11:22:16 -08002656void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2657{
2658 size_t i = 0;
2659 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2660 for (const auto& fmt : mManualSurroundFormats) {
2661 if (i++ != 0) dst->append(", ");
2662 std::string sfmt;
2663 FormatConverter::toString(fmt, sfmt);
2664 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2665 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2666 }
2667}
2668
Andy Hungc29d82b2018-10-05 12:23:17 -07002669void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002670{
Andy Hungc29d82b2018-10-05 12:23:17 -07002671 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2672 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002673 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002674 std::string stateLiteral;
2675 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002676 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002677 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2678 "communications", "media", "record", "dock", "system",
2679 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2680 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2681 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002682 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2683 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2684 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2685 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2686 dst->append(" (MANUAL: ");
2687 dumpManualSurroundFormats(dst);
2688 dst->append(")");
2689 }
2690 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002691 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002692 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2693 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2694 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2695 mAvailableOutputDevices.dump(dst, String8("Available output"));
2696 mAvailableInputDevices.dump(dst, String8("Available input"));
2697 mHwModulesAll.dump(dst);
2698 mOutputs.dump(dst);
2699 mInputs.dump(dst);
2700 mVolumeCurves->dump(dst);
2701 mEffects.dump(dst);
2702 mAudioPatches.dump(dst);
2703 mPolicyMixes.dump(dst);
2704 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002705}
2706
2707status_t AudioPolicyManager::dump(int fd)
2708{
2709 String8 result;
2710 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002711 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002712 return NO_ERROR;
2713}
2714
2715// This function checks for the parameters which can be offloaded.
2716// This can be enhanced depending on the capability of the DSP and policy
2717// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002718bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
2720 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002721 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002722 offloadInfo.sample_rate, offloadInfo.channel_mask,
2723 offloadInfo.format,
2724 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2725 offloadInfo.has_video);
2726
Andy Hung2ddee192015-12-18 17:34:44 -08002727 if (mMasterMono) {
2728 return false; // no offloading if mono is set.
2729 }
2730
Eric Laurente552edb2014-03-10 17:42:56 -07002731 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002732 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2733 ALOGV("offload disabled by audio.offload.disable");
2734 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736
2737 // Check if stream type is music, then only allow offload as of now.
2738 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2739 {
2740 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2741 return false;
2742 }
2743
2744 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002745 const bool allowOffloadWithVideo =
2746 property_get_bool("audio.offload.video", false /* default_value */);
2747 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002748 ALOGV("isOffloadSupported: has_video == true, returning false");
2749 return false;
2750 }
2751
2752 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002753 const int min_duration_secs = property_get_int32(
2754 "audio.offload.min.duration.secs", -1 /* default_value */);
2755 if (min_duration_secs >= 0) {
2756 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2757 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2758 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002759 return false;
2760 }
2761 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2762 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2763 return false;
2764 }
2765
2766 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2767 // creating an offloaded track and tearing it down immediately after start when audioflinger
2768 // detects there is an active non offloadable effect.
2769 // FIXME: We should check the audio session here but we do not have it in this context.
2770 // This may prevent offloading in rare situations where effects are left active by apps
2771 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002772 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002773 return false;
2774 }
2775
2776 // See if there is a profile to support this.
2777 // AUDIO_DEVICE_NONE
Michael Chana94fbb22018-04-24 14:31:19 +10002778 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002779 offloadInfo.sample_rate,
2780 offloadInfo.format,
2781 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002782 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2783 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002784 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2785 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002786}
2787
Michael Chana94fbb22018-04-24 14:31:19 +10002788bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2789 const audio_attributes_t& attributes) {
2790 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2791 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
2792 sp<IOProfile> profile = getProfileForOutput(AUDIO_DEVICE_NONE /*ignore device */,
2793 config.sample_rate,
2794 config.format,
2795 config.channel_mask,
2796 output_flags,
2797 true /* directOnly */);
2798 ALOGV("%s() profile %sfound with name: %s, "
2799 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2800 __FUNCTION__, profile != 0 ? "" : "NOT ",
2801 (profile != 0 ? profile->getTagName().string() : "null"),
2802 config.sample_rate, config.format, config.channel_mask, output_flags);
2803 return (profile != 0);
2804}
2805
Eric Laurent6a94d692014-05-20 11:18:06 -07002806status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2807 audio_port_type_t type,
2808 unsigned int *num_ports,
2809 struct audio_port *ports,
2810 unsigned int *generation)
2811{
2812 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2813 generation == NULL) {
2814 return BAD_VALUE;
2815 }
2816 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2817 if (ports == NULL) {
2818 *num_ports = 0;
2819 }
2820
2821 size_t portsWritten = 0;
2822 size_t portsMax = *num_ports;
2823 *num_ports = 0;
2824 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002825 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2826 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002828 for (const auto& dev : mAvailableOutputDevices) {
2829 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002830 continue;
2831 }
2832 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002833 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002834 }
2835 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002837 }
2838 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002839 for (const auto& dev : mAvailableInputDevices) {
2840 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002841 continue;
2842 }
2843 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002844 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002845 }
2846 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 }
2849 }
2850 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2851 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2852 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2853 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2854 }
2855 *num_ports += mInputs.size();
2856 }
2857 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002858 size_t numOutputs = 0;
2859 for (size_t i = 0; i < mOutputs.size(); i++) {
2860 if (!mOutputs[i]->isDuplicated()) {
2861 numOutputs++;
2862 if (portsWritten < portsMax) {
2863 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2864 }
2865 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002866 }
Eric Laurent84c70242014-06-23 08:46:27 -07002867 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002868 }
2869 }
2870 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002871 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002872 return NO_ERROR;
2873}
2874
Eric Laurent99fcae42018-05-17 16:59:18 -07002875status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002876{
Eric Laurent99fcae42018-05-17 16:59:18 -07002877 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2878 return BAD_VALUE;
2879 }
2880 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2881 if (dev != 0) {
2882 dev->toAudioPort(port);
2883 return NO_ERROR;
2884 }
2885 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2886 if (dev != 0) {
2887 dev->toAudioPort(port);
2888 return NO_ERROR;
2889 }
2890 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2891 if (out != 0) {
2892 out->toAudioPort(port);
2893 return NO_ERROR;
2894 }
2895 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2896 if (in != 0) {
2897 in->toAudioPort(port);
2898 return NO_ERROR;
2899 }
2900 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002901}
2902
Eric Laurent6a94d692014-05-20 11:18:06 -07002903status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2904 audio_patch_handle_t *handle,
2905 uid_t uid)
2906{
2907 ALOGV("createAudioPatch()");
2908
2909 if (handle == NULL || patch == NULL) {
2910 return BAD_VALUE;
2911 }
2912 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2913
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002914 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002915 return BAD_VALUE;
2916 }
2917 // only one source per audio patch supported for now
2918 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 return INVALID_OPERATION;
2920 }
Eric Laurent874c42872014-08-08 15:13:39 -07002921
2922 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 return INVALID_OPERATION;
2924 }
Eric Laurent874c42872014-08-08 15:13:39 -07002925 for (size_t i = 0; i < patch->num_sinks; i++) {
2926 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2927 return INVALID_OPERATION;
2928 }
2929 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002930
2931 sp<AudioPatch> patchDesc;
2932 ssize_t index = mAudioPatches.indexOfKey(*handle);
2933
Eric Laurent6a94d692014-05-20 11:18:06 -07002934 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2935 patch->sources[0].role,
2936 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002937#if LOG_NDEBUG == 0
2938 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002939 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002940 patch->sinks[i].role,
2941 patch->sinks[i].type);
2942 }
2943#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002944
2945 if (index >= 0) {
2946 patchDesc = mAudioPatches.valueAt(index);
2947 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2948 mUidCached, patchDesc->mUid, uid);
2949 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2950 return INVALID_OPERATION;
2951 }
2952 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002953 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 }
2955
2956 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002957 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002958 if (outputDesc == NULL) {
2959 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2960 return BAD_VALUE;
2961 }
Eric Laurent84c70242014-06-23 08:46:27 -07002962 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2963 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 if (patchDesc != 0) {
2965 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2966 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2967 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2968 return BAD_VALUE;
2969 }
2970 }
Eric Laurent874c42872014-08-08 15:13:39 -07002971 DeviceVector devices;
2972 for (size_t i = 0; i < patch->num_sinks; i++) {
2973 // Only support mix to devices connection
2974 // TODO add support for mix to mix connection
2975 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2976 ALOGV("createAudioPatch() source mix but sink is not a device");
2977 return INVALID_OPERATION;
2978 }
2979 sp<DeviceDescriptor> devDesc =
2980 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2981 if (devDesc == 0) {
2982 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2983 return BAD_VALUE;
2984 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002985
François Gaffie53615e22015-03-19 09:24:12 +01002986 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
François Gaffieaca677c2018-05-03 10:47:50 +02002987 devDesc->address(),
Eric Laurent874c42872014-08-08 15:13:39 -07002988 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002989 NULL, // updatedSamplingRate
2990 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002991 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002992 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002993 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002994 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002995 ALOGV("createAudioPatch() profile not supported for device %08x",
2996 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002997 return INVALID_OPERATION;
2998 }
2999 devices.add(devDesc);
3000 }
3001 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003002 return INVALID_OPERATION;
3003 }
Eric Laurent874c42872014-08-08 15:13:39 -07003004
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 // TODO: reconfigure output format and channels here
3006 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003007 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07003008 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 index = mAudioPatches.indexOfKey(*handle);
3010 if (index >= 0) {
3011 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3012 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3013 }
3014 patchDesc = mAudioPatches.valueAt(index);
3015 patchDesc->mUid = uid;
3016 ALOGV("createAudioPatch() success");
3017 } else {
3018 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3019 return INVALID_OPERATION;
3020 }
3021 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3022 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3023 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003024 // only one sink supported when connecting an input device to a mix
3025 if (patch->num_sinks > 1) {
3026 return INVALID_OPERATION;
3027 }
François Gaffie53615e22015-03-19 09:24:12 +01003028 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 if (inputDesc == NULL) {
3030 return BAD_VALUE;
3031 }
3032 if (patchDesc != 0) {
3033 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3034 return BAD_VALUE;
3035 }
3036 }
3037 sp<DeviceDescriptor> devDesc =
3038 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3039 if (devDesc == 0) {
3040 return BAD_VALUE;
3041 }
3042
François Gaffie53615e22015-03-19 09:24:12 +01003043 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
François Gaffieaca677c2018-05-03 10:47:50 +02003044 devDesc->address(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003045 patch->sinks[0].sample_rate,
3046 NULL, /*updatedSampleRate*/
3047 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003048 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003049 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003050 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003051 // FIXME for the parameter type,
3052 // and the NONE
3053 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003054 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003055 return INVALID_OPERATION;
3056 }
3057 // TODO: reconfigure output format and channels here
3058 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003059 devDesc->type(), inputDesc->mIoHandle);
3060 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 index = mAudioPatches.indexOfKey(*handle);
3062 if (index >= 0) {
3063 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3064 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3065 }
3066 patchDesc = mAudioPatches.valueAt(index);
3067 patchDesc->mUid = uid;
3068 ALOGV("createAudioPatch() success");
3069 } else {
3070 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3071 return INVALID_OPERATION;
3072 }
3073 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3074 // device to device connection
3075 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003076 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003077 return BAD_VALUE;
3078 }
3079 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003080 sp<DeviceDescriptor> srcDeviceDesc =
3081 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003082 if (srcDeviceDesc == 0) {
3083 return BAD_VALUE;
3084 }
Eric Laurent874c42872014-08-08 15:13:39 -07003085
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 //update source and sink with our own data as the data passed in the patch may
3087 // be incomplete.
3088 struct audio_patch newPatch = *patch;
3089 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003090
Eric Laurent874c42872014-08-08 15:13:39 -07003091 for (size_t i = 0; i < patch->num_sinks; i++) {
3092 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3093 ALOGV("createAudioPatch() source device but one sink is not a device");
3094 return INVALID_OPERATION;
3095 }
3096
3097 sp<DeviceDescriptor> sinkDeviceDesc =
3098 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3099 if (sinkDeviceDesc == 0) {
3100 return BAD_VALUE;
3101 }
3102 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3103
Eric Laurent3bcf8592015-04-03 12:13:24 -07003104 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003105 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003106 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003107 // - audio HAL version is >= 3.0 but no route has been declared between devices
Eric Laurentfb66dd92016-01-28 18:32:03 -08003108 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
François Gaffieaca677c2018-05-03 10:47:50 +02003109 (srcDeviceDesc->getModuleVersionMajor() < 3) ||
3110 !srcDeviceDesc->getModule()->supportsPatch(srcDeviceDesc, sinkDeviceDesc)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003111 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003112 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003113 return INVALID_OPERATION;
3114 }
Eric Laurent874c42872014-08-08 15:13:39 -07003115 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003116 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003117 // if the sink device is reachable via an opened output stream, request to go via
3118 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003119 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003120 if (output != AUDIO_IO_HANDLE_NONE) {
3121 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3122 if (outputDesc->isDuplicated()) {
3123 return INVALID_OPERATION;
3124 }
3125 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003126 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003127 newPatch.num_sources = 2;
3128 }
Eric Laurent83b88082014-06-20 18:31:16 -07003129 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003130 }
3131 // TODO: check from routing capabilities in config file and other conflicting patches
3132
Mikhail Naganovdc769682018-05-04 15:34:08 -07003133 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3134 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003135 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3136 status);
3137 return INVALID_OPERATION;
3138 }
3139 } else {
3140 return BAD_VALUE;
3141 }
3142 } else {
3143 return BAD_VALUE;
3144 }
3145 return NO_ERROR;
3146}
3147
3148status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3149 uid_t uid)
3150{
3151 ALOGV("releaseAudioPatch() patch %d", handle);
3152
3153 ssize_t index = mAudioPatches.indexOfKey(handle);
3154
3155 if (index < 0) {
3156 return BAD_VALUE;
3157 }
3158 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3159 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3160 mUidCached, patchDesc->mUid, uid);
3161 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3162 return INVALID_OPERATION;
3163 }
3164
3165 struct audio_patch *patch = &patchDesc->mPatch;
3166 patchDesc->mUid = mUidCached;
3167 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003168 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 if (outputDesc == NULL) {
3170 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3171 return BAD_VALUE;
3172 }
3173
Eric Laurentc75307b2015-03-17 15:29:32 -07003174 setOutputDevice(outputDesc,
3175 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 true,
3177 0,
3178 NULL);
3179 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3180 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003181 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003182 if (inputDesc == NULL) {
3183 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3184 return BAD_VALUE;
3185 }
3186 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003187 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 true,
3189 NULL);
3190 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003191 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3192 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3193 status, patchDesc->mAfPatchHandle);
3194 removeAudioPatch(patchDesc->mHandle);
3195 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003196 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003197 } else {
3198 return BAD_VALUE;
3199 }
3200 } else {
3201 return BAD_VALUE;
3202 }
3203 return NO_ERROR;
3204}
3205
3206status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3207 struct audio_patch *patches,
3208 unsigned int *generation)
3209{
François Gaffie53615e22015-03-19 09:24:12 +01003210 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003211 return BAD_VALUE;
3212 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003213 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003214 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003215}
3216
Eric Laurente1715a42014-05-20 11:30:42 -07003217status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003218{
Eric Laurente1715a42014-05-20 11:30:42 -07003219 ALOGV("setAudioPortConfig()");
3220
3221 if (config == NULL) {
3222 return BAD_VALUE;
3223 }
3224 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3225 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003226 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3227 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003228 }
3229
Eric Laurenta121f902014-06-03 13:32:54 -07003230 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003231 if (config->type == AUDIO_PORT_TYPE_MIX) {
3232 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003233 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003234 if (outputDesc == NULL) {
3235 return BAD_VALUE;
3236 }
Eric Laurent84c70242014-06-23 08:46:27 -07003237 ALOG_ASSERT(!outputDesc->isDuplicated(),
3238 "setAudioPortConfig() called on duplicated output %d",
3239 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003240 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003241 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003242 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003243 if (inputDesc == NULL) {
3244 return BAD_VALUE;
3245 }
Eric Laurenta121f902014-06-03 13:32:54 -07003246 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003247 } else {
3248 return BAD_VALUE;
3249 }
3250 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3251 sp<DeviceDescriptor> deviceDesc;
3252 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3253 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3254 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3255 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3256 } else {
3257 return BAD_VALUE;
3258 }
3259 if (deviceDesc == NULL) {
3260 return BAD_VALUE;
3261 }
Eric Laurenta121f902014-06-03 13:32:54 -07003262 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003263 } else {
3264 return BAD_VALUE;
3265 }
3266
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003267 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003268 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3269 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003270 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003271 audioPortConfig->toAudioPortConfig(&newConfig, config);
3272 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003273 }
Eric Laurenta121f902014-06-03 13:32:54 -07003274 if (status != NO_ERROR) {
3275 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003276 }
Eric Laurente1715a42014-05-20 11:30:42 -07003277
3278 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003279}
3280
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003281void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3282{
Eric Laurentd60560a2015-04-10 11:31:20 -07003283 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003284 clearAudioPatches(uid);
3285 clearSessionRoutes(uid);
3286}
3287
Eric Laurent6a94d692014-05-20 11:18:06 -07003288void AudioPolicyManager::clearAudioPatches(uid_t uid)
3289{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003290 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003291 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3292 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003293 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003294 }
3295 }
3296}
3297
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003298void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3299 audio_io_handle_t ouptutToSkip)
3300{
3301 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3302 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3303 for (size_t j = 0; j < mOutputs.size(); j++) {
3304 if (mOutputs.keyAt(j) == ouptutToSkip) {
3305 continue;
3306 }
3307 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3308 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3309 continue;
3310 }
3311 // If the default device for this strategy is on another output mix,
3312 // invalidate all tracks in this strategy to force re connection.
3313 // Otherwise select new device on the output mix.
3314 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003315 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003316 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3317 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3318 }
3319 }
3320 } else {
3321 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3322 setOutputDevice(outputDesc, newDevice, false);
3323 }
3324 }
3325}
3326
3327void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3328{
3329 // remove output routes associated with this uid
3330 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003331 for (size_t i = 0; i < mOutputs.size(); i++) {
3332 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003333 for (const auto& client : outputDesc->getClientIterable()) {
3334 if (client->hasPreferredDevice() && client->uid() == uid) {
3335 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3336 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003337 }
3338 }
3339 }
3340 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003341 for (const auto& strategy : affectedStrategies) {
3342 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003343 }
3344
3345 // remove input routes associated with this uid
3346 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003347 for (size_t i = 0; i < mInputs.size(); i++) {
3348 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003349 for (const auto& client : inputDesc->getClientIterable()) {
3350 if (client->hasPreferredDevice() && client->uid() == uid) {
3351 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3352 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003353 }
3354 }
3355 }
3356 // reroute inputs if necessary
3357 SortedVector<audio_io_handle_t> inputsToClose;
3358 for (size_t i = 0; i < mInputs.size(); i++) {
3359 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003360 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361 inputsToClose.add(inputDesc->mIoHandle);
3362 }
3363 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003364 for (const auto& input : inputsToClose) {
3365 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366 }
3367}
3368
Eric Laurentd60560a2015-04-10 11:31:20 -07003369void AudioPolicyManager::clearAudioSources(uid_t uid)
3370{
3371 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003372 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3373 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003374 stopAudioSource(mAudioSources.keyAt(i));
3375 }
3376 }
3377}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003378
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003379status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3380 audio_io_handle_t *ioHandle,
3381 audio_devices_t *device)
3382{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003383 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3384 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003385 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003386
François Gaffiedf372692015-03-19 10:43:27 +01003387 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003388}
3389
Eric Laurentd60560a2015-04-10 11:31:20 -07003390status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003391 const audio_attributes_t *attributes,
3392 audio_port_handle_t *portId,
3393 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003394{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003395 ALOGV("%s", __FUNCTION__);
3396 *portId = AUDIO_PORT_HANDLE_NONE;
3397
3398 if (source == NULL || attributes == NULL || portId == NULL) {
3399 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3400 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003401 return BAD_VALUE;
3402 }
3403
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3405 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003406 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3407 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003408 return INVALID_OPERATION;
3409 }
3410
3411 sp<DeviceDescriptor> srcDeviceDesc =
3412 mAvailableInputDevices.getDevice(source->ext.device.type,
3413 String8(source->ext.device.address));
3414 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003416 return BAD_VALUE;
3417 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003418
3419 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003420
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003421 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003422 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003423
3424 sp<SourceClientDescriptor> sourceDesc =
3425 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003426 streamTypefromAttributesInt(attributes),
3427 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003428
3429 status_t status = connectAudioSource(sourceDesc);
3430 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003431 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003432 }
3433 return status;
3434}
3435
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003436status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003437{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003438 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003439
3440 // make sure we only have one patch per source.
3441 disconnectAudioSource(sourceDesc);
3442
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003443 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003444 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003445 audio_stream_type_t stream = sourceDesc->stream();
3446 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003447
3448 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3449 sp<DeviceDescriptor> sinkDeviceDesc =
3450 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3451
3452 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003453
François Gaffie83d789d2018-05-29 13:29:19 +02003454 if (srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) &&
François Gaffieaca677c2018-05-03 10:47:50 +02003455 srcDeviceDesc->getModuleVersionMajor() >= 3 &&
3456 sinkDeviceDesc->getModule()->supportsPatch(srcDeviceDesc, sinkDeviceDesc) &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003457 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003458 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003459 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003460 // create patch between src device and output device
3461 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003462 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003463 audio_attributes_t resultAttr;
3464 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3465 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3466 config.sample_rate = sourceDesc->config().sample_rate;
3467 config.channel_mask = sourceDesc->config().channel_mask;
3468 config.format = sourceDesc->config().format;
3469 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3470 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3471 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3472 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003473 if (output == AUDIO_IO_HANDLE_NONE) {
3474 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3475 return INVALID_OPERATION;
3476 }
3477 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3478 if (outputDesc->isDuplicated()) {
3479 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3480 return INVALID_OPERATION;
3481 }
Eric Laurent733ce942017-12-07 12:18:25 -08003482 status_t status = outputDesc->start();
3483 if (status != NO_ERROR) {
3484 return status;
3485 }
3486
Eric Laurentd60560a2015-04-10 11:31:20 -07003487 // create a special patch with no sink and two sources:
3488 // - the second source indicates to PatchPanel through which output mix this patch should
3489 // be connected as well as the stream type for volume control
3490 // - the sink is defined by whatever output device is currently selected for the output
3491 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003492 PatchBuilder patchBuilder;
3493 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3494 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003495 &afPatchHandle,
3496 0);
3497 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3498 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003499 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003500 if (status != NO_ERROR) {
3501 ALOGW("%s patch panel could not connect device patch, error %d",
3502 __FUNCTION__, status);
3503 return INVALID_OPERATION;
3504 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003505
3506 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3507 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3508 return INVALID_OPERATION;
3509 }
3510 outputDesc->addClient(sourceDesc);
3511
Eric Laurentd60560a2015-04-10 11:31:20 -07003512 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003513 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003514
3515 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003516 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003517 return status;
3518 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003519 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003520 if (delayMs != 0) {
3521 usleep(delayMs * 1000);
3522 }
3523 }
3524
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003525 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3526 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003527
3528 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003529}
3530
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003531status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003532{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003533 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3534 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003535 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003536 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003537 return BAD_VALUE;
3538 }
3539 status_t status = disconnectAudioSource(sourceDesc);
3540
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003541 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003542 return status;
3543}
3544
Andy Hung2ddee192015-12-18 17:34:44 -08003545status_t AudioPolicyManager::setMasterMono(bool mono)
3546{
3547 if (mMasterMono == mono) {
3548 return NO_ERROR;
3549 }
3550 mMasterMono = mono;
3551 // if enabling mono we close all offloaded devices, which will invalidate the
3552 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3553 // for recreating the new AudioTrack as non-offloaded PCM.
3554 //
3555 // If disabling mono, we leave all tracks as is: we don't know which clients
3556 // and tracks are able to be recreated as offloaded. The next "song" should
3557 // play back offloaded.
3558 if (mMasterMono) {
3559 Vector<audio_io_handle_t> offloaded;
3560 for (size_t i = 0; i < mOutputs.size(); ++i) {
3561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3562 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3563 offloaded.push(desc->mIoHandle);
3564 }
3565 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003566 for (const auto& handle : offloaded) {
3567 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003568 }
3569 }
3570 // update master mono for all remaining outputs
3571 for (size_t i = 0; i < mOutputs.size(); ++i) {
3572 updateMono(mOutputs.keyAt(i));
3573 }
3574 return NO_ERROR;
3575}
3576
3577status_t AudioPolicyManager::getMasterMono(bool *mono)
3578{
3579 *mono = mMasterMono;
3580 return NO_ERROR;
3581}
3582
Eric Laurentac9cef52017-06-09 15:46:26 -07003583float AudioPolicyManager::getStreamVolumeDB(
3584 audio_stream_type_t stream, int index, audio_devices_t device)
3585{
3586 return computeVolume(stream, index, device);
3587}
3588
jiabin81772902018-04-02 17:52:27 -07003589status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3590 audio_format_t *surroundFormats,
3591 bool *surroundFormatsEnabled,
3592 bool reported)
3593{
3594 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3595 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3596 return BAD_VALUE;
3597 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003598 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3599 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003600
3601 size_t formatsWritten = 0;
3602 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003603 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003604 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003605 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003606 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003607 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3608 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3609 FormatVector supportedFormats =
3610 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3611 for (size_t j = 0; j < supportedFormats.size(); j++) {
3612 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3613 formats.insert(supportedFormats[j]);
3614 } else {
3615 for (const auto& pair : mConfig.getSurroundFormats()) {
3616 if (pair.second.count(supportedFormats[j]) != 0) {
3617 formats.insert(pair.first);
3618 break;
3619 }
3620 }
3621 }
3622 }
jiabin81772902018-04-02 17:52:27 -07003623 }
3624 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003625 for (const auto& pair : mConfig.getSurroundFormats()) {
3626 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003627 }
3628 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003629 *numSurroundFormats = formats.size();
3630 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3631 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003632 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003633 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003634 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003635 bool formatEnabled = true;
3636 switch (forceUse) {
3637 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3638 formatEnabled = mManualSurroundFormats.count(format) != 0;
3639 break;
3640 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3641 formatEnabled = false;
3642 break;
3643 default: // AUTO or ALWAYS => true
3644 break;
jiabin81772902018-04-02 17:52:27 -07003645 }
3646 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3647 }
jiabin81772902018-04-02 17:52:27 -07003648 }
3649 return NO_ERROR;
3650}
3651
3652status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3653{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003654 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003655 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3656 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003657 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003658 return BAD_VALUE;
3659 }
3660
Mikhail Naganov100f0122018-11-29 11:22:16 -08003661 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3662 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003663 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003664 return INVALID_OPERATION;
3665 }
3666
Mikhail Naganov100f0122018-11-29 11:22:16 -08003667 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003668 return NO_ERROR;
3669 }
3670
Mikhail Naganov100f0122018-11-29 11:22:16 -08003671 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003672 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003673 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003674 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003675 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003676 }
3677 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003678 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003679 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003680 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003681 }
3682 }
3683
3684 sp<SwAudioOutputDescriptor> outputDesc;
3685 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003686 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003687 AUDIO_DEVICE_OUT_HDMI);
3688 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3689 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003690 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003691 String8 name = hdmiOutputDevices[i]->getName();
3692 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3693 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3694 address.c_str(),
3695 name.c_str());
3696 if (status != NO_ERROR) {
3697 continue;
3698 }
3699 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 profileUpdated |= (status == NO_ERROR);
3704 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003705 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003706 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003707 AUDIO_DEVICE_IN_HDMI);
3708 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3709 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003710 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003711 String8 name = hdmiInputDevices[i]->getName();
3712 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3713 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3714 address.c_str(),
3715 name.c_str());
3716 if (status != NO_ERROR) {
3717 continue;
3718 }
3719 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3720 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3721 address.c_str(),
3722 name.c_str());
3723 profileUpdated |= (status == NO_ERROR);
3724 }
3725
jiabin81772902018-04-02 17:52:27 -07003726 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003727 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003728 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003729 }
3730
3731 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3732}
3733
Eric Laurentf32108e2018-10-04 17:22:04 -07003734void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003735{
Eric Laurentf32108e2018-10-04 17:22:04 -07003736 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentf32108e2018-10-04 17:22:04 -07003737
Eric Laurent4eb58f12018-12-07 16:41:02 -08003738 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003739
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003740 for (size_t i = 0; i < activeInputs.size(); i++) {
3741 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003742 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3743 for (const auto& client : clients) {
3744 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003745 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003746 }
3747 }
3748 }
3749}
3750
jiabin6012f912018-11-02 17:06:30 -07003751bool AudioPolicyManager::isHapticPlaybackSupported()
3752{
3753 for (const auto& hwModule : mHwModules) {
3754 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3755 for (const auto &outProfile : outputProfiles) {
3756 struct audio_port audioPort;
3757 outProfile->toAudioPort(&audioPort);
3758 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3759 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3760 return true;
3761 }
3762 }
3763 }
3764 }
3765 return false;
3766}
3767
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003768status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003769{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003770 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003771
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003772 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003773 if (patchDesc == 0) {
3774 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003775 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003776 return BAD_VALUE;
3777 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003778 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003779
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003780 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003781 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003782 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003783 if (status == NO_ERROR) {
3784 swOutputDesc->stop();
3785 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003786 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3787 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003788 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003789 if (hwOutputDesc != 0) {
3790 // release patch between src device and output device
3791 // close Hwoutput and remove from mHwOutputs
3792 } else {
3793 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3794 }
3795 }
3796 return NO_ERROR;
3797}
3798
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003799sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003800 audio_io_handle_t output, routing_strategy strategy)
3801{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003802 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003803 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003804 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3805 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003806 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003807 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003808 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3809 source = sourceDesc;
3810 break;
3811 }
3812 }
3813 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003814}
3815
Eric Laurente552edb2014-03-10 17:42:56 -07003816// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003817// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003818// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003819uint32_t AudioPolicyManager::nextAudioPortGeneration()
3820{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003821 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003822}
3823
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003824// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3825static const char *kConfigLocationList[] =
3826 {"/odm/etc", "/vendor/etc", "/system/etc"};
3827static const int kConfigLocationListSize =
3828 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3829
3830static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3831 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003832 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003833 status_t ret;
3834
Petri Gyntherf497f292018-04-17 18:46:10 -07003835 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3836 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3837 // A2DP offload supported but disabled: try to use special XML file
3838 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3839 }
3840 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3841
3842 for (const char* fileName : fileNames) {
3843 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003844 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3845 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003846 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003847 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003848 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003849 return ret;
3850 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003851 }
3852 }
3853 return ret;
3854}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003855
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003856AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3857 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003858 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003859 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003860 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003861 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003862 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863 mVolumeCurves(new VolumeCurvesCollection()),
3864 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003865 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003866 mAudioPortGeneration(1),
3867 mBeaconMuteRefCount(0),
3868 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003869 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003870 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003871 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003872 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003873{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003874}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003875
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003876AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3877 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3878{
3879 loadConfig();
3880 initialize();
3881}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003882
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003883// This check is to catch any legacy platform updating to Q without having
3884// switched to XML since its deprecation on O.
3885// TODO: after Q release, remove this check and flag as XML is now the only
3886// option and all legacy platform should have transitioned to XML.
3887#ifndef USE_XML_AUDIO_POLICY_CONF
3888#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003889#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003890
3891void AudioPolicyManager::loadConfig() {
3892 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003893 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003894 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003895 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003896}
3897
3898status_t AudioPolicyManager::initialize() {
3899 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003900
3901 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003902 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3903 if (!engineInstance) {
3904 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003905 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003906 }
3907 // Retrieve the Policy Manager Interface
3908 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3909 if (mEngine == NULL) {
3910 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003911 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003912 }
3913 mEngine->setObserver(this);
3914 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003915 if (status != NO_ERROR) {
3916 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3917 return status;
3918 }
François Gaffie2110e042015-03-24 08:41:51 +01003919
Eric Laurent3a4311c2014-03-17 12:00:47 -07003920 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003921 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3923 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003924 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003925 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003926 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3927 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003928 continue;
3929 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003930 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003931 // open all output streams needed to access attached devices
3932 // except for direct output streams that are only opened when they are actually
3933 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003934 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003935 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003936 if (!outProfile->canOpenNewIo()) {
3937 ALOGE("Invalid Output profile max open count %u for profile %s",
3938 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3939 continue;
3940 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003941 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003942 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 continue;
3944 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003946 mTtsOutputAvailable = true;
3947 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003948
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003949 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003950 continue;
3951 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003952 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003953 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3954 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003955 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003956 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003959 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003960 if ((profileType & outputDeviceTypes) == 0) {
3961 continue;
3962 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003963 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3964 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003965 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003966 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3967 profileType);
François Gaffieaca677c2018-05-03 10:47:50 +02003968 String8 address = getFirstDeviceAddress(devicesForType);
Eric Laurentd78f1532014-09-16 16:38:20 -07003969 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003970 status_t status = outputDesc->open(nullptr, profileType, address,
3971 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003972
3973 if (status != NO_ERROR) {
3974 ALOGW("Cannot open output stream for device %08x on hw module %s",
3975 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003976 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003978 for (const auto& dev : supportedDevices) {
3979 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003981 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003982 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003983 }
3984 }
3985 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003987 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003988 }
3989 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003991 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003992 true,
3993 0,
3994 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003995 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003996 }
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 // open input streams needed to access attached devices to validate
3999 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004000 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004001 if (!inProfile->canOpenNewIo()) {
4002 ALOGE("Invalid Input profile max open count %u for profile %s",
4003 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4004 continue;
4005 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004006 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004007 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 continue;
4009 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004010 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004011 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004012 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4013
Eric Laurentd78f1532014-09-16 16:38:20 -07004014 if ((profileType & inputDeviceTypes) == 0) {
4015 continue;
4016 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004017 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004018 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004019
Mikhail Naganov708e0382018-05-30 09:53:04 -07004020 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004021 // the inputs vector must be of size >= 1, but we don't want to crash here
François Gaffieaca677c2018-05-03 10:47:50 +02004022 String8 address = getFirstDeviceAddress(inputDevices);
Eric Laurent53b810e2017-12-10 17:25:10 -08004023 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4024 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4025
Eric Laurentd78f1532014-09-16 16:38:20 -07004026 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004027 status_t status = inputDesc->open(nullptr,
4028 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004029 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004030 AUDIO_SOURCE_MIC,
4031 AUDIO_INPUT_FLAG_NONE,
4032 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004033
4034 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004035 for (const auto& dev : inProfile->getSupportedDevices()) {
4036 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004037 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004038 if (index >= 0) {
4039 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4040 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004041 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004042 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004043 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004044 }
4045 }
Eric Laurentfe231122017-11-17 17:48:06 -08004046 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004047 } else {
4048 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004049 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004050 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004051 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004052 }
4053 }
4054 // make sure all attached devices have been allocated a unique ID
4055 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004056 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004057 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4059 continue;
4060 }
François Gaffie2110e042015-03-24 08:41:51 +01004061 // The device is now validated and can be appended to the available devices of the engine
4062 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4063 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 i++;
4065 }
4066 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004067 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004068 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004069 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4070 continue;
4071 }
François Gaffie2110e042015-03-24 08:41:51 +01004072 // The device is now validated and can be appended to the available devices of the engine
4073 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4074 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 i++;
4076 }
4077 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004078 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004079 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004080 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 }
jiabin9ff780e2018-03-19 18:19:52 -07004082 // If microphones address is empty, set it according to device type
4083 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004084 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004085 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
François Gaffieaca677c2018-05-03 10:47:50 +02004086 mAvailableInputDevices[i]->address() = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004087 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
François Gaffieaca677c2018-05-03 10:47:50 +02004088 mAvailableInputDevices[i]->address() = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004089 }
4090 }
4091 }
Eric Laurente552edb2014-03-10 17:42:56 -07004092
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004093 if (mPrimaryOutput == 0) {
4094 ALOGE("Failed to open primary output");
4095 status = NO_INIT;
4096 }
Eric Laurente552edb2014-03-10 17:42:56 -07004097
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004098 // Silence ALOGV statements
4099 property_set("log.tag." LOG_TAG, "D");
4100
Eric Laurente552edb2014-03-10 17:42:56 -07004101 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004102 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004103}
4104
Eric Laurente0720872014-03-11 09:30:41 -07004105AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004106{
Eric Laurente552edb2014-03-10 17:42:56 -07004107 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004108 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004109 }
4110 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004111 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004112 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 mAvailableOutputDevices.clear();
4114 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004115 mOutputs.clear();
4116 mInputs.clear();
4117 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004118 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004119 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004120}
4121
Eric Laurente0720872014-03-11 09:30:41 -07004122status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004123{
Eric Laurent87ffa392015-05-22 10:32:38 -07004124 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004125}
4126
Eric Laurente552edb2014-03-10 17:42:56 -07004127// ---
4128
Eric Laurent98e38192018-02-15 18:31:53 -08004129void AudioPolicyManager::addOutput(audio_io_handle_t output,
4130 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004131{
Eric Laurent1c333e22014-05-20 10:48:17 -07004132 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004133 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004134 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004135 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004136 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004137}
4138
François Gaffie53615e22015-03-19 09:24:12 +01004139void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4140{
4141 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004142 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004143}
4144
Eric Laurent98e38192018-02-15 18:31:53 -08004145void AudioPolicyManager::addInput(audio_io_handle_t input,
4146 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004147{
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004149 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004150}
Eric Laurente552edb2014-03-10 17:42:56 -07004151
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004152void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004153 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004154 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004155 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004156 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004157 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004158 if (devDesc != 0) {
4159 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4160 desc->mIoHandle, address.string());
4161 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004162 }
4163}
4164
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004165status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004166 audio_policy_dev_state_t state,
4167 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004168 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004169{
François Gaffie53615e22015-03-19 09:24:12 +01004170 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004171 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004172
4173 if (audio_device_is_digital(device)) {
4174 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004175 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004176 }
Eric Laurente552edb2014-03-10 17:42:56 -07004177
Eric Laurent3b73df72014-03-11 09:06:29 -07004178 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004179 // first list already open outputs that can be routed to this device
4180 for (size_t i = 0; i < mOutputs.size(); i++) {
4181 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004182 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004183 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004184 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4185 outputs.add(mOutputs.keyAt(i));
4186 } else {
4187 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004188 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004189 }
Eric Laurente552edb2014-03-10 17:42:56 -07004190 }
4191 }
4192 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004193 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004194 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004195 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4196 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004197 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004198 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004199 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004200 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004201 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4202 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004203 }
Eric Laurente552edb2014-03-10 17:42:56 -07004204 }
4205 }
4206 }
4207
Eric Laurent7b279bb2015-12-14 10:18:23 -08004208 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004209
Eric Laurente552edb2014-03-10 17:42:56 -07004210 if (profiles.isEmpty() && outputs.isEmpty()) {
4211 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4212 return BAD_VALUE;
4213 }
4214
4215 // open outputs for matching profiles if needed. Direct outputs are also opened to
4216 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4217 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004218 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004219
4220 // nothing to do if one output is already opened for this profile
4221 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004222 for (j = 0; j < outputs.size(); j++) {
4223 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004224 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004225 // matching profile: save the sample rates, format and channel masks supported
4226 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004227 if (audio_device_is_digital(device)) {
4228 devDesc->importAudioPort(profile);
4229 }
Eric Laurente552edb2014-03-10 17:42:56 -07004230 break;
4231 }
4232 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004233 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004234 continue;
4235 }
4236
Eric Laurent3974e3b2017-12-07 17:58:43 -08004237 if (!profile->canOpenNewIo()) {
4238 ALOGW("Max Output number %u already opened for this profile %s",
4239 profile->maxOpenCount, profile->getTagName().c_str());
4240 continue;
4241 }
4242
Eric Laurent83efe1c2017-07-09 16:51:08 -07004243 ALOGV("opening output for device %08x with params %s profile %p name %s",
4244 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004245 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004246 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004247 status_t status = desc->open(nullptr, device, address,
4248 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004249
Eric Laurentfe231122017-11-17 17:48:06 -08004250 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004251 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004252 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004253 char *param = audio_device_address_to_parameter(device, address);
4254 mpClientInterface->setParameters(output, String8(param));
4255 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004256 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004257 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004258 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004259 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004260 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004261 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004262 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004263 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004264 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004265 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4266 profile->pickAudioProfile(
4267 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004268 config.offload_info.sample_rate = config.sample_rate;
4269 config.offload_info.channel_mask = config.channel_mask;
4270 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004271
4272 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4273 AUDIO_OUTPUT_FLAG_NONE, &output);
4274 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004275 output = AUDIO_IO_HANDLE_NONE;
4276 }
Eric Laurentd4692962014-05-05 18:13:44 -07004277 }
4278
Eric Laurentcf2c0212014-07-25 16:20:43 -07004279 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004280 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004281 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004282 sp<AudioPolicyMix> policyMix;
4283 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004284 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4285 address.string());
4286 }
François Gaffie036e1e92015-03-19 10:16:24 +01004287 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004288 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004289
Eric Laurent87ffa392015-05-22 10:32:38 -07004290 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4291 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004292 // no duplicated output for direct outputs and
4293 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004294 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004295
Eric Laurentd4692962014-05-05 18:13:44 -07004296 //TODO: configure audio effect output stage here
4297
4298 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004299 sp<SwAudioOutputDescriptor> dupOutputDesc =
4300 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4301 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4302 &duplicatedOutput);
4303 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004304 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004305 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004306 } else {
4307 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004308 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004309 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004310 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004311 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004312 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004313 }
Eric Laurente552edb2014-03-10 17:42:56 -07004314 }
4315 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004316 } else {
4317 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004318 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004320 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004321 profiles.removeAt(profile_index);
4322 profile_index--;
4323 } else {
4324 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004325 // Load digital format info only for digital devices
4326 if (audio_device_is_digital(device)) {
4327 devDesc->importAudioPort(profile);
4328 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004329
François Gaffie53615e22015-03-19 09:24:12 +01004330 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004331 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4332 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004333 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004334 NULL/*patch handle*/, address.string());
4335 }
Eric Laurente552edb2014-03-10 17:42:56 -07004336 ALOGV("checkOutputsForDevice(): adding output %d", output);
4337 }
4338 }
4339
4340 if (profiles.isEmpty()) {
4341 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4342 return BAD_VALUE;
4343 }
Eric Laurentd4692962014-05-05 18:13:44 -07004344 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004345 // check if one opened output is not needed any more after disconnecting one device
4346 for (size_t i = 0; i < mOutputs.size(); i++) {
4347 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004348 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004349 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004350 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004351 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004352 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004353 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004354 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4355 mOutputs.keyAt(i));
4356 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004357 }
Eric Laurente552edb2014-03-10 17:42:56 -07004358 }
4359 }
Eric Laurentd4692962014-05-05 18:13:44 -07004360 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004361 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004362 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4363 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004364 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004365 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004366 "clearing direct output profile %zu on module %s",
4367 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004368 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004369 }
4370 }
4371 }
4372 }
4373 return NO_ERROR;
4374}
4375
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004376status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004377 audio_policy_dev_state_t state,
4378 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004379 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004380{
Paul McLean9080a4c2015-06-18 08:24:02 -07004381 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004382 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004383
4384 if (audio_device_is_digital(device)) {
4385 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004386 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004387 }
4388
Eric Laurentd4692962014-05-05 18:13:44 -07004389 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4390 // first list already open inputs that can be routed to this device
4391 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4392 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004393 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004394 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4395 inputs.add(mInputs.keyAt(input_index));
4396 }
4397 }
4398
4399 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004400 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004401 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004402 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004403 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004404 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004405 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004406
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004407 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004408 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004409 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004410 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004411 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4412 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004413 }
Eric Laurentd4692962014-05-05 18:13:44 -07004414 }
4415 }
4416 }
4417
4418 if (profiles.isEmpty() && inputs.isEmpty()) {
4419 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4420 return BAD_VALUE;
4421 }
4422
4423 // open inputs for matching profiles if needed. Direct inputs are also opened to
4424 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4425 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4426
Eric Laurent1c333e22014-05-20 10:48:17 -07004427 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004428
Eric Laurentd4692962014-05-05 18:13:44 -07004429 // nothing to do if one input is already opened for this profile
4430 size_t input_index;
4431 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4432 desc = mInputs.valueAt(input_index);
4433 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004434 if (audio_device_is_digital(device)) {
4435 devDesc->importAudioPort(profile);
4436 }
Eric Laurentd4692962014-05-05 18:13:44 -07004437 break;
4438 }
4439 }
4440 if (input_index != mInputs.size()) {
4441 continue;
4442 }
4443
Eric Laurent3974e3b2017-12-07 17:58:43 -08004444 if (!profile->canOpenNewIo()) {
4445 ALOGW("Max Input number %u already opened for this profile %s",
4446 profile->maxOpenCount, profile->getTagName().c_str());
4447 continue;
4448 }
4449
Eric Laurentfe231122017-11-17 17:48:06 -08004450 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004451 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004452 status_t status = desc->open(nullptr,
4453 device,
4454 address,
4455 AUDIO_SOURCE_MIC,
4456 AUDIO_INPUT_FLAG_NONE,
4457 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004458
Eric Laurentcf2c0212014-07-25 16:20:43 -07004459 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004460 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004461 char *param = audio_device_address_to_parameter(device, address);
4462 mpClientInterface->setParameters(input, String8(param));
4463 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004464 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004465 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004466 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004467 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004468 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004469 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004470 }
4471
4472 if (input != 0) {
4473 addInput(input, desc);
4474 }
4475 } // endif input != 0
4476
Eric Laurentcf2c0212014-07-25 16:20:43 -07004477 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004478 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004479 profiles.removeAt(profile_index);
4480 profile_index--;
4481 } else {
4482 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004483 if (audio_device_is_digital(device)) {
4484 devDesc->importAudioPort(profile);
4485 }
Eric Laurentd4692962014-05-05 18:13:44 -07004486 ALOGV("checkInputsForDevice(): adding input %d", input);
4487 }
4488 } // end scan profiles
4489
4490 if (profiles.isEmpty()) {
4491 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4492 return BAD_VALUE;
4493 }
4494 } else {
4495 // Disconnect
4496 // check if one opened input is not needed any more after disconnecting one device
4497 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4498 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004499 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004500 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4501 mInputs.keyAt(input_index));
4502 inputs.add(mInputs.keyAt(input_index));
4503 }
4504 }
4505 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004506 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004507 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004508 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004509 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004510 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004511 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004512 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4513 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004514 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004515 }
4516 }
4517 }
4518 } // end disconnect
4519
4520 return NO_ERROR;
4521}
4522
4523
Eric Laurente0720872014-03-11 09:30:41 -07004524void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004525{
4526 ALOGV("closeOutput(%d)", output);
4527
Eric Laurentc75307b2015-03-17 15:29:32 -07004528 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004529 if (outputDesc == NULL) {
4530 ALOGW("closeOutput() unknown output %d", output);
4531 return;
4532 }
François Gaffie036e1e92015-03-19 10:16:24 +01004533 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004534
Eric Laurente552edb2014-03-10 17:42:56 -07004535 // look for duplicated outputs connected to the output being removed.
4536 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004537 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004538 if (dupOutputDesc->isDuplicated() &&
4539 (dupOutputDesc->mOutput1 == outputDesc ||
4540 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004541 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004542 if (dupOutputDesc->mOutput1 == outputDesc) {
4543 outputDesc2 = dupOutputDesc->mOutput2;
4544 } else {
4545 outputDesc2 = dupOutputDesc->mOutput1;
4546 }
4547 // As all active tracks on duplicated output will be deleted,
4548 // and as they were also referenced on the other output, the reference
4549 // count for their stream type must be adjusted accordingly on
4550 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004551 const bool wasActive = outputDesc2->isActive();
4552 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4553 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004554 }
Eric Laurent733ce942017-12-07 12:18:25 -08004555 // stop() will be a no op if the output is still active but is needed in case all
4556 // active streams refcounts where cleared above
4557 if (wasActive) {
4558 outputDesc2->stop();
4559 }
Eric Laurente552edb2014-03-10 17:42:56 -07004560 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4561 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4562
4563 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004564 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004565 }
4566 }
4567
Eric Laurent05b90f82014-08-27 15:32:29 -07004568 nextAudioPortGeneration();
4569
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004570 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004571 if (index >= 0) {
4572 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004573 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004574 mAudioPatches.removeItemsAt(index);
4575 mpClientInterface->onAudioPatchListUpdate();
4576 }
4577
Eric Laurentfe231122017-11-17 17:48:06 -08004578 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004579
François Gaffie53615e22015-03-19 09:24:12 +01004580 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004581 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004582
4583 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4584 // no direct outputs are open.
Mikhail Naganov100f0122018-11-29 11:22:16 -08004585 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004586 bool directOutputOpen = false;
4587 for (size_t i = 0; i < mOutputs.size(); i++) {
4588 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4589 directOutputOpen = true;
4590 break;
4591 }
4592 }
4593 if (!directOutputOpen) {
4594 ALOGV("no direct outputs open, reset MSD patch");
4595 setMsdPatch();
4596 }
4597 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004598}
4599
4600void AudioPolicyManager::closeInput(audio_io_handle_t input)
4601{
4602 ALOGV("closeInput(%d)", input);
4603
4604 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4605 if (inputDesc == NULL) {
4606 ALOGW("closeInput() unknown input %d", input);
4607 return;
4608 }
4609
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004611
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004612 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004613 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004614 if (index >= 0) {
4615 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004616 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 mAudioPatches.removeItemsAt(index);
4618 mpClientInterface->onAudioPatchListUpdate();
4619 }
4620
Eric Laurentfe231122017-11-17 17:48:06 -08004621 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004622 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004623
4624 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4625 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4626 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4627 SoundTrigger::setCaptureState(false);
4628 }
Eric Laurente552edb2014-03-10 17:42:56 -07004629}
4630
Eric Laurentc75307b2015-03-17 15:29:32 -07004631SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4632 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004633 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004634{
4635 SortedVector<audio_io_handle_t> outputs;
4636
4637 ALOGVV("getOutputsForDevice() device %04x", device);
4638 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004639 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004640 i, openOutputs.valueAt(i)->isDuplicated(),
4641 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004642 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4643 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4644 outputs.add(openOutputs.keyAt(i));
4645 }
4646 }
4647 return outputs;
4648}
4649
Mikhail Naganov37977152018-07-11 15:54:44 -07004650void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4651{
4652 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4653 // output is suspended before any tracks are moved to it
4654 checkA2dpSuspend();
4655 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004656 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004657 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004658 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004659 setMsdPatch();
4660 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004661}
4662
Eric Laurente0720872014-03-11 09:30:41 -07004663void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004664{
4665 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4666 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4667 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4668 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4669
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004670 // also take into account external policy-related changes: add all outputs which are
4671 // associated with policies in the "before" and "after" output vectors
4672 ALOGVV("checkOutputForStrategy(): policy related outputs");
4673 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004674 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004675 if (desc != 0 && desc->mPolicyMix != NULL) {
4676 srcOutputs.add(desc->mIoHandle);
4677 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4678 }
4679 }
4680 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004681 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004682 if (desc != 0 && desc->mPolicyMix != NULL) {
4683 dstOutputs.add(desc->mIoHandle);
4684 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4685 }
4686 }
4687
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004688 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004689 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4690 // audio from invalidated tracks will be rendered when unmuting
4691 uint32_t maxLatency = 0;
4692 for (audio_io_handle_t srcOut : srcOutputs) {
4693 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4694 if (desc != 0 && maxLatency < desc->latency()) {
4695 maxLatency = desc->latency();
4696 }
4697 }
Eric Laurente552edb2014-03-10 17:42:56 -07004698 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4699 strategy, srcOutputs[0], dstOutputs[0]);
4700 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004701 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004702 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4703 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004704 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004705 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004706 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004707 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004708 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004709 if (source != 0){
4710 connectAudioSource(source);
4711 }
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713
4714 // Move effects associated to this strategy from previous output to new output
4715 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004716 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
4718 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004719 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004720 if (getStrategy((audio_stream_type_t)i) == strategy) {
4721 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004722 }
4723 }
4724 }
4725}
4726
Eric Laurente0720872014-03-11 09:30:41 -07004727void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004728{
François Gaffie2110e042015-03-24 08:41:51 +01004729 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004730 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004731 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004732 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004733 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004734 checkOutputForStrategy(STRATEGY_SONIFICATION);
4735 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004736 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004737 checkOutputForStrategy(STRATEGY_MEDIA);
4738 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004739 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004740}
4741
Eric Laurente0720872014-03-11 09:30:41 -07004742void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004743{
François Gaffie53615e22015-03-19 09:24:12 +01004744 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004745 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004747 return;
4748 }
4749
Eric Laurent3a4311c2014-03-17 12:00:47 -07004750 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004751 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4752 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4753 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004754
4755 // if suspended, restore A2DP output if:
4756 // ((SCO device is NOT connected) ||
4757 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4758 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004759 //
Eric Laurentf732e072016-08-03 19:30:28 -07004760 // if not suspended, suspend A2DP output if:
4761 // (SCO device is connected) &&
4762 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4763 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004764 //
4765 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004766 if (!isScoConnected ||
4767 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4768 AUDIO_POLICY_FORCE_BT_SCO) &&
4769 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4770 AUDIO_POLICY_FORCE_BT_SCO) &&
4771 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004772 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004773
4774 mpClientInterface->restoreOutput(a2dpOutput);
4775 mA2dpSuspended = false;
4776 }
4777 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004778 if (isScoConnected &&
4779 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4780 AUDIO_POLICY_FORCE_BT_SCO) ||
4781 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4782 AUDIO_POLICY_FORCE_BT_SCO) ||
4783 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004784 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004785
4786 mpClientInterface->suspendOutput(a2dpOutput);
4787 mA2dpSuspended = true;
4788 }
4789 }
4790}
4791
Eric Laurent97ac8712018-07-27 18:59:02 -07004792template <class IoDescriptor, class Filter>
4793sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4794 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4795{
4796 auto activeClients = desc->clientsList(true /*activeOnly*/);
4797 auto activeClientsWithRoute =
4798 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4799 active = activeClients.size() > 0;
4800 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4801 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4802 }
4803 return nullptr;
4804}
4805
4806template <class IoCollection, class Filter>
4807sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4808 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4809{
4810 sp<DeviceDescriptor> device;
4811 for (size_t i = 0; i < ioCollection.size(); i++) {
4812 auto desc = ioCollection.valueAt(i);
4813 bool active;
4814 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4815 if (active && curDevice == nullptr) {
4816 return nullptr;
4817 } else if (curDevice != nullptr) {
4818 device = curDevice;
4819 }
4820 }
4821 return device;
4822}
4823
Eric Laurentc75307b2015-03-17 15:29:32 -07004824audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4825 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004826{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004827 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004828 if (index >= 0) {
4829 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4830 if (patchDesc->mUid != mUidCached) {
4831 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004832 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004833 return outputDesc->device();
4834 }
4835 }
4836
Eric Laurent97ac8712018-07-27 18:59:02 -07004837 // Honor explicit routing requests only if no client using default routing is active on this
4838 // input: a specific app can not force routing for other apps by setting a preferred device.
4839 bool active; // unused
4840 sp<DeviceDescriptor> deviceDesc =
4841 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4842 if (deviceDesc != nullptr) {
4843 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004844 }
4845
Eric Laurente552edb2014-03-10 17:42:56 -07004846 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004847 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004848 // use device for strategy enforced audible
4849 // 2: we are in call or the strategy phone is active on the output:
4850 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004851 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004852 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004853 // 4: the strategy for enforced audible is active but not enforced on the output:
4854 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004855 // 5: the strategy accessibility is active on the output:
4856 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004857 // 6: the strategy "respectful" sonification is active on the output:
4858 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004859 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004860 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004861 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004862 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004863 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004864 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004865
4866 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4867 // with a refined rule considering mutually exclusive devices (using same backend)
4868 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004869 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004870 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004871 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004872 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4873 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004874 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004875 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004876 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004877 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004878 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4879 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004880 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4881 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004882 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004883 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004884 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004886 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004887 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004888 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004889 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004890 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004891 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004892 }
4893
Eric Laurent1c333e22014-05-20 10:48:17 -07004894 ALOGV("getNewOutputDevice() selected device %x", device);
4895 return device;
4896}
4897
Eric Laurentfb66dd92016-01-28 18:32:03 -08004898audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004899{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004900 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004901
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004902 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 if (index >= 0) {
4904 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4905 if (patchDesc->mUid != mUidCached) {
4906 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004907 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 return inputDesc->mDevice;
4909 }
4910 }
4911
Eric Laurent97ac8712018-07-27 18:59:02 -07004912 // Honor explicit routing requests only if no client using default routing is active on this
4913 // input: a specific app can not force routing for other apps by setting a preferred device.
4914 bool active;
4915 sp<DeviceDescriptor> deviceDesc =
4916 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4917 if (deviceDesc != nullptr) {
4918 return deviceDesc->type();
4919 }
4920
Eric Laurentdc95a252018-04-12 12:46:56 -07004921 // If we are not in call and no client is active on this input, this methods returns
4922 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4eb58f12018-12-07 16:41:02 -08004923 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004924 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4925 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4926 }
4927 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004928 device = getDeviceAndMixForInputSource(source);
4929 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004930
Eric Laurente552edb2014-03-10 17:42:56 -07004931 return device;
4932}
4933
Eric Laurent794fde22016-03-11 09:50:45 -08004934bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4935 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004936 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004937}
4938
Eric Laurente0720872014-03-11 09:30:41 -07004939uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004940 return (uint32_t)getStrategy(stream);
4941}
4942
Eric Laurente0720872014-03-11 09:30:41 -07004943audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004944 // By checking the range of stream before calling getStrategy, we avoid
4945 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4946 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004947 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004948 return AUDIO_DEVICE_NONE;
4949 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004950 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004951 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004952 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4953 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004954 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 }
Eric Laurent794fde22016-03-11 09:50:45 -08004956 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004957 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004958 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004959 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004960 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4961 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004962 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004963 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004964 }
4965 }
Eric Laurente552edb2014-03-10 17:42:56 -07004966 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004967
Eric Laurentb0688d62018-08-14 15:49:18 -07004968 // Favor devices selected on active streams if any to report correct device in case of
4969 // explicit device selection
4970 if (activeDevices != AUDIO_DEVICE_NONE) {
4971 devices = activeDevices;
4972 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004973 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4974 and doesn't really need to.*/
4975 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4976 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4977 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4978 }
Eric Laurente552edb2014-03-10 17:42:56 -07004979 return devices;
4980}
4981
François Gaffie2110e042015-03-24 08:41:51 +01004982routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4983{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004984 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004985 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004986}
4987
Eric Laurent97ac8712018-07-27 18:59:02 -07004988routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004989 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004990 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004991 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004992 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004993 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004994 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004995 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004996 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004997 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004998}
4999
Eric Laurente0720872014-03-11 09:30:41 -07005000void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005001 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005002 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005003 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5004 updateDevicesAndOutputs();
5005 break;
5006 default:
5007 break;
5008 }
5009}
5010
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005011uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005012
5013 // skip beacon mute management if a dedicated TTS output is available
5014 if (mTtsOutputAvailable) {
5015 return 0;
5016 }
5017
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005018 switch(event) {
5019 case STARTING_OUTPUT:
5020 mBeaconMuteRefCount++;
5021 break;
5022 case STOPPING_OUTPUT:
5023 if (mBeaconMuteRefCount > 0) {
5024 mBeaconMuteRefCount--;
5025 }
5026 break;
5027 case STARTING_BEACON:
5028 mBeaconPlayingRefCount++;
5029 break;
5030 case STOPPING_BEACON:
5031 if (mBeaconPlayingRefCount > 0) {
5032 mBeaconPlayingRefCount--;
5033 }
5034 break;
5035 }
5036
5037 if (mBeaconMuteRefCount > 0) {
5038 // any playback causes beacon to be muted
5039 return setBeaconMute(true);
5040 } else {
5041 // no other playback: unmute when beacon starts playing, mute when it stops
5042 return setBeaconMute(mBeaconPlayingRefCount == 0);
5043 }
5044}
5045
5046uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5047 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5048 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5049 // keep track of muted state to avoid repeating mute/unmute operations
5050 if (mBeaconMuted != mute) {
5051 // mute/unmute AUDIO_STREAM_TTS on all outputs
5052 ALOGV("\t muting %d", mute);
5053 uint32_t maxLatency = 0;
5054 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005056 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005057 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005058 0 /*delay*/, AUDIO_DEVICE_NONE);
5059 const uint32_t latency = desc->latency() * 2;
5060 if (latency > maxLatency) {
5061 maxLatency = latency;
5062 }
5063 }
5064 mBeaconMuted = mute;
5065 return maxLatency;
5066 }
5067 return 0;
5068}
5069
Eric Laurente0720872014-03-11 09:30:41 -07005070audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005071 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005072{
Eric Laurent97ac8712018-07-27 18:59:02 -07005073 // Honor explicit routing requests only if all active clients have a preferred route in which
5074 // case the last active client route is used
5075 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5076 if (deviceDesc != nullptr) {
5077 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07005078 }
5079
Eric Laurente552edb2014-03-10 17:42:56 -07005080 if (fromCache) {
5081 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5082 strategy, mDeviceForStrategy[strategy]);
5083 return mDeviceForStrategy[strategy];
5084 }
François Gaffie2110e042015-03-24 08:41:51 +01005085 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005086}
5087
Eric Laurente0720872014-03-11 09:30:41 -07005088void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005089{
5090 for (int i = 0; i < NUM_STRATEGIES; i++) {
5091 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5092 }
5093 mPreviousOutputs = mOutputs;
5094}
5095
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005096uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005097 audio_devices_t prevDevice,
5098 uint32_t delayMs)
5099{
5100 // mute/unmute strategies using an incompatible device combination
5101 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5102 // if unmuting, unmute only after the specified delay
5103 if (outputDesc->isDuplicated()) {
5104 return 0;
5105 }
5106
5107 uint32_t muteWaitMs = 0;
5108 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005109 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005110
5111 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5112 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005113 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005114 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5115 bool doMute = false;
5116
5117 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5118 doMute = true;
5119 outputDesc->mStrategyMutedByDevice[i] = true;
5120 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5121 doMute = true;
5122 outputDesc->mStrategyMutedByDevice[i] = false;
5123 }
Eric Laurent99401132014-05-07 19:48:15 -07005124 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005125 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005126 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005127 // skip output if it does not share any device with current output
5128 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5129 == AUDIO_DEVICE_NONE) {
5130 continue;
5131 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005132 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005133 mute ? "muting" : "unmuting", i, curDevice);
5134 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005135 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005136 if (mute) {
5137 // FIXME: should not need to double latency if volume could be applied
5138 // immediately by the audioflinger mixer. We must account for the delay
5139 // between now and the next time the audioflinger thread for this output
5140 // will process a buffer (which corresponds to one buffer size,
5141 // usually 1/2 or 1/4 of the latency).
5142 if (muteWaitMs < desc->latency() * 2) {
5143 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005144 }
5145 }
5146 }
5147 }
5148 }
5149 }
5150
Eric Laurent99401132014-05-07 19:48:15 -07005151 // temporary mute output if device selection changes to avoid volume bursts due to
5152 // different per device volumes
5153 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005154 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5155 // temporary mute duration is conservatively set to 4 times the reported latency
5156 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5157 if (muteWaitMs < tempMuteWaitMs) {
5158 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005159 }
Eric Laurentdc462862016-07-19 12:29:53 -07005160
Eric Laurent99401132014-05-07 19:48:15 -07005161 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005162 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005163 // make sure that we do not start the temporary mute period too early in case of
5164 // delayed device change
5165 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005166 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005167 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005168 }
5169 }
5170 }
5171
Eric Laurente552edb2014-03-10 17:42:56 -07005172 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5173 if (muteWaitMs > delayMs) {
5174 muteWaitMs -= delayMs;
5175 usleep(muteWaitMs * 1000);
5176 return muteWaitMs;
5177 }
5178 return 0;
5179}
5180
Eric Laurentc75307b2015-03-17 15:29:32 -07005181uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005182 audio_devices_t device,
5183 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005185 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005186 const char *address,
5187 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005188{
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005190 AudioParameter param;
5191 uint32_t muteWaitMs;
5192
5193 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005194 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5195 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5196 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5197 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005198 return muteWaitMs;
5199 }
5200 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5201 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005202 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005203 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005204 return 0;
5205 }
5206
5207 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005208 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005209
5210 audio_devices_t prevDevice = outputDesc->mDevice;
5211
Paul McLeanaa981192015-03-21 09:55:15 -07005212 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005213
5214 if (device != AUDIO_DEVICE_NONE) {
5215 outputDesc->mDevice = device;
5216 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005217
5218 // if the outputs are not materially active, there is no need to mute.
5219 if (requiresMuteCheck) {
5220 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5221 } else {
5222 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5223 muteWaitMs = 0;
5224 }
Eric Laurente552edb2014-03-10 17:42:56 -07005225
5226 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005227 // the requested device is AUDIO_DEVICE_NONE
5228 // OR the requested device is the same as current device
5229 // AND force is not specified
5230 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005231 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005232 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5233 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005234 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005235 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005236 return muteWaitMs;
5237 }
5238
5239 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005240
Eric Laurente552edb2014-03-10 17:42:56 -07005241 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005243 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005244 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005245 DeviceVector deviceList;
5246 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005247 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005248 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005249 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5250 device, String8(address));
5251 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005252 }
5253
Eric Laurent1c333e22014-05-20 10:48:17 -07005254 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005255 PatchBuilder patchBuilder;
5256 patchBuilder.addSource(outputDesc);
François Gaffieaca677c2018-05-03 10:47:50 +02005257 ALOG_ASSERT(deviceList.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5258 for (const auto &device : deviceList) {
5259 patchBuilder.addSink(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005261 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005262 }
5263 }
Eric Laurente552edb2014-03-10 17:42:56 -07005264
5265 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005266 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005267
5268 return muteWaitMs;
5269}
5270
Eric Laurentc75307b2015-03-17 15:29:32 -07005271status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 int delayMs,
5273 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005274{
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 ssize_t index;
5276 if (patchHandle) {
5277 index = mAudioPatches.indexOfKey(*patchHandle);
5278 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005279 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 }
5281 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 return INVALID_OPERATION;
5283 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5285 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005286 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005287 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 removeAudioPatch(patchDesc->mHandle);
5289 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005290 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005291 return status;
5292}
5293
5294status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5295 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 bool force,
5297 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005298{
5299 status_t status = NO_ERROR;
5300
Eric Laurent1f2f2232014-06-02 12:01:23 -07005301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005302 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5303 inputDesc->mDevice = device;
5304
Mikhail Naganov708e0382018-05-30 09:53:04 -07005305 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005306 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005307 PatchBuilder patchBuilder;
5308 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005309 // AUDIO_SOURCE_HOTWORD is for internal use only:
5310 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005311 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5312 auto result = usecase;
5313 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5314 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5315 }
5316 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005317 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005318 addSource(deviceList.itemAt(0));
5319 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005320 }
5321 }
5322 return status;
5323}
5324
Eric Laurent6a94d692014-05-20 11:18:06 -07005325status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5326 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005327{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005328 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005329 ssize_t index;
5330 if (patchHandle) {
5331 index = mAudioPatches.indexOfKey(*patchHandle);
5332 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005333 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 }
5335 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005336 return INVALID_OPERATION;
5337 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5339 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005340 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005341 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 removeAudioPatch(patchDesc->mHandle);
5343 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005344 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005345 return status;
5346}
5347
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005348sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005349 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005350 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005351 audio_format_t& format,
5352 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005353 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005354{
5355 // Choose an input profile based on the requested capture parameters: select the first available
5356 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005357 //
5358 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5359 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005360
Glenn Kasten730b9262018-03-29 15:01:26 -07005361 sp<IOProfile> firstInexact;
5362 uint32_t updatedSamplingRate = 0;
5363 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5364 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005365 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005366 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005367 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005368 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005369 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005370 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005371 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005372 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005373 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005374 &channelMask /*updatedChannelMask*/,
5375 // FIXME ugly cast
5376 (audio_output_flags_t) flags,
5377 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005378 return profile;
5379 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5381 samplingRate,
5382 &updatedSamplingRate,
5383 format,
5384 &updatedFormat,
5385 channelMask,
5386 &updatedChannelMask,
5387 // FIXME ugly cast
5388 (audio_output_flags_t) flags,
5389 false /*exactMatchRequiredForInputFlags*/)) {
5390 firstInexact = profile;
5391 }
5392
Eric Laurente552edb2014-03-10 17:42:56 -07005393 }
5394 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005395 if (firstInexact != nullptr) {
5396 samplingRate = updatedSamplingRate;
5397 format = updatedFormat;
5398 channelMask = updatedChannelMask;
5399 return firstInexact;
5400 }
Eric Laurente552edb2014-03-10 17:42:56 -07005401 return NULL;
5402}
5403
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005404
5405audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005406 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005407{
Eric Laurent97ac8712018-07-27 18:59:02 -07005408 // Honor explicit routing requests only if all active clients have a preferred route in which
5409 // case the last active client route is used
5410 sp<DeviceDescriptor> deviceDesc =
5411 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5412 if (deviceDesc != nullptr) {
5413 return deviceDesc->type();
5414 }
5415
5416
François Gaffie036e1e92015-03-19 10:16:24 +01005417 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5418 audio_devices_t selectedDeviceFromMix =
5419 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005420
François Gaffie036e1e92015-03-19 10:16:24 +01005421 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5422 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005423 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005424 return getDeviceForInputSource(inputSource);
5425}
5426
5427audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5428{
Eric Laurent97ac8712018-07-27 18:59:02 -07005429 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005430}
5431
Eric Laurente0720872014-03-11 09:30:41 -07005432float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005433 int index,
5434 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005435{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005436 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005437
5438 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5439 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5440 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5441 // the ringtone volume
5442 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5443 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5444 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5445 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5446 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5447 }
5448
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005449 // in-call: always cap volume by voice volume + some low headroom
5450 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005451 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005452 switch (stream) {
5453 case AUDIO_STREAM_SYSTEM:
5454 case AUDIO_STREAM_RING:
5455 case AUDIO_STREAM_MUSIC:
5456 case AUDIO_STREAM_ALARM:
5457 case AUDIO_STREAM_NOTIFICATION:
5458 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5459 case AUDIO_STREAM_DTMF:
5460 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005461 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005462 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005463 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005464 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005465 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005466 if (volumeDB > maxVoiceVolDb) {
5467 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5468 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5469 volumeDB = maxVoiceVolDb;
5470 }
5471 } break;
5472 default:
5473 break;
5474 }
5475 }
5476
Eric Laurente552edb2014-03-10 17:42:56 -07005477 // if a headset is connected, apply the following rules to ring tones and notifications
5478 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005479 // - always attenuate notifications volume by 6dB
5480 // - attenuate ring tones volume by 6dB unless music is not playing and
5481 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005482 // - if music is playing, always limit the volume to current music volume,
5483 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005484 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005485 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5486 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5487 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005488 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005489 AUDIO_DEVICE_OUT_USB_HEADSET |
5490 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005491 ((stream_strategy == STRATEGY_SONIFICATION)
5492 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005493 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005494 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005495 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005496 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005497 // when the phone is ringing we must consider that music could have been paused just before
5498 // by the music application and behave as if music was active if the last music track was
5499 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005500 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005501 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005502 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005503 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005504 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005505 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5506 musicDevice),
5507 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005508 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5509 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005510 if (volumeDB > minVolDB) {
5511 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005512 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005513 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005514 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5515 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5516 // on A2DP, also ensure notification volume is not too low compared to media when
5517 // intended to be played
5518 if ((volumeDB > -96.0f) &&
5519 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5520 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5521 stream, device,
5522 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5523 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5524 }
5525 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005526 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5527 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005528 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005529 }
5530 }
5531
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005532 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005533}
5534
Eric Laurent3839bc02018-07-10 18:33:34 -07005535int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5536 audio_stream_type_t srcStream,
5537 audio_stream_type_t dstStream)
5538{
5539 if (srcStream == dstStream) {
5540 return srcIndex;
5541 }
5542 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5543 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5544 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5545 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5546
5547 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5548}
5549
Eric Laurente0720872014-03-11 09:30:41 -07005550status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005551 int index,
5552 const sp<AudioOutputDescriptor>& outputDesc,
5553 audio_devices_t device,
5554 int delayMs,
5555 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005556{
Eric Laurente552edb2014-03-10 17:42:56 -07005557 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005558 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005559 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005560 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005561 return NO_ERROR;
5562 }
François Gaffie2110e042015-03-24 08:41:51 +01005563 audio_policy_forced_cfg_t forceUseForComm =
5564 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005566 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5567 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005568 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005569 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005570 return INVALID_OPERATION;
5571 }
5572
Eric Laurentc75307b2015-03-17 15:29:32 -07005573 if (device == AUDIO_DEVICE_NONE) {
5574 device = outputDesc->device();
5575 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005576
Eric Laurentffbc80f2015-03-18 18:30:19 -07005577 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005578 if (outputDesc->isFixedVolume(device) ||
5579 // Force VoIP volume to max for bluetooth SCO
5580 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5581 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005582 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005583 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005584
Eric Laurentffbc80f2015-03-18 18:30:19 -07005585 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005586
Eric Laurent3b73df72014-03-11 09:06:29 -07005587 if (stream == AUDIO_STREAM_VOICE_CALL ||
5588 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005589 float voiceVolume;
5590 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005592 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005593 } else {
5594 voiceVolume = 1.0;
5595 }
5596
Eric Laurent18fba842016-03-31 14:41:26 -07005597 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005598 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5599 mLastVoiceVolume = voiceVolume;
5600 }
5601 }
5602
5603 return NO_ERROR;
5604}
5605
Eric Laurentc75307b2015-03-17 15:29:32 -07005606void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5607 audio_devices_t device,
5608 int delayMs,
5609 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005610{
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005612
Eric Laurent794fde22016-03-11 09:50:45 -08005613 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005614 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005615 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005617 device,
5618 delayMs,
5619 force);
5620 }
5621}
5622
Eric Laurente0720872014-03-11 09:30:41 -07005623void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005624 bool on,
5625 const sp<AudioOutputDescriptor>& outputDesc,
5626 int delayMs,
5627 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005628{
Eric Laurent72249d52015-06-08 11:12:15 -07005629 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5630 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005631 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005632 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005634 }
5635 }
5636}
5637
Eric Laurente0720872014-03-11 09:30:41 -07005638void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005639 bool on,
5640 const sp<AudioOutputDescriptor>& outputDesc,
5641 int delayMs,
5642 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005643{
Eric Laurente552edb2014-03-10 17:42:56 -07005644 if (device == AUDIO_DEVICE_NONE) {
5645 device = outputDesc->device();
5646 }
5647
Eric Laurentc75307b2015-03-17 15:29:32 -07005648 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5649 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005650
5651 if (on) {
5652 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005653 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005654 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005655 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005656 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005657 }
5658 }
5659 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5660 outputDesc->mMuteCount[stream]++;
5661 } else {
5662 if (outputDesc->mMuteCount[stream] == 0) {
5663 ALOGV("setStreamMute() unmuting non muted stream!");
5664 return;
5665 }
5666 if (--outputDesc->mMuteCount[stream] == 0) {
5667 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005668 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005669 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005670 device,
5671 delayMs);
5672 }
5673 }
5674}
5675
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005676audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5677{
5678 // flags to stream type mapping
5679 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5680 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5681 }
5682 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5683 return AUDIO_STREAM_BLUETOOTH_SCO;
5684 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005685 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5686 return AUDIO_STREAM_TTS;
5687 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005688
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005689 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005690}
Eric Laurente83b55d2014-11-14 10:06:21 -08005691
François Gaffie53615e22015-03-19 09:24:12 +01005692bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5693{
Eric Laurente83b55d2014-11-14 10:06:21 -08005694 // has flags that map to a strategy?
5695 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5696 return true;
5697 }
5698
5699 // has known usage?
5700 switch (paa->usage) {
5701 case AUDIO_USAGE_UNKNOWN:
5702 case AUDIO_USAGE_MEDIA:
5703 case AUDIO_USAGE_VOICE_COMMUNICATION:
5704 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5705 case AUDIO_USAGE_ALARM:
5706 case AUDIO_USAGE_NOTIFICATION:
5707 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5708 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5709 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5710 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5711 case AUDIO_USAGE_NOTIFICATION_EVENT:
5712 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5713 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5714 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5715 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005716 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005717 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005718 break;
5719 default:
5720 return false;
5721 }
5722 return true;
5723}
5724
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005725bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005726 routing_strategy strategy, uint32_t inPastMs,
5727 nsecs_t sysTime) const
5728{
5729 if ((sysTime == 0) && (inPastMs != 0)) {
5730 sysTime = systemTime();
5731 }
Eric Laurent794fde22016-03-11 09:50:45 -08005732 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005733 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005734 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005735 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5736 return true;
5737 }
5738 }
5739 return false;
5740}
5741
Eric Laurent484e9272018-06-07 17:29:23 -07005742bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5743 routing_strategy strategy, uint32_t inPastMs,
5744 nsecs_t sysTime) const
5745{
5746 for (size_t i = 0; i < mOutputs.size(); i++) {
5747 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5748 if (outputDesc->sharesHwModuleWith(desc)
5749 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5750 return true;
5751 }
5752 }
5753 return false;
5754}
5755
François Gaffie2110e042015-03-24 08:41:51 +01005756audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5757{
5758 return mEngine->getForceUse(usage);
5759}
5760
5761bool AudioPolicyManager::isInCall()
5762{
5763 return isStateInCall(mEngine->getPhoneState());
5764}
5765
5766bool AudioPolicyManager::isStateInCall(int state)
5767{
5768 return is_state_in_call(state);
5769}
5770
Eric Laurentd60560a2015-04-10 11:31:20 -07005771void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5772{
5773 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005774 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5775 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5776 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5777 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005778 }
5779 }
5780
5781 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5782 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5783 bool release = false;
5784 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5785 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5786 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5787 source->ext.device.type == deviceDesc->type()) {
5788 release = true;
5789 }
5790 }
5791 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5792 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5793 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5794 sink->ext.device.type == deviceDesc->type()) {
5795 release = true;
5796 }
5797 }
5798 if (release) {
5799 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5800 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5801 }
5802 }
5803}
5804
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005805void AudioPolicyManager::modifySurroundFormats(
5806 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005807 std::unordered_set<audio_format_t> enforcedSurround(
5808 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005809 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5810 for (const auto& pair : mConfig.getSurroundFormats()) {
5811 allSurround.insert(pair.first);
5812 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5813 }
Phil Burk09bc4612016-02-24 15:58:15 -08005814
5815 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5816 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005817 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005818 // This is the resulting set of formats depending on the surround mode:
5819 // 'all surround' = allSurround
5820 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5821 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5822 // 'manual surround' = mManualSurroundFormats
5823 // AUTO: formats v 'enforced surround'
5824 // ALWAYS: formats v 'all surround' v 'enforced surround'
5825 // NEVER: formats ^ 'non-surround'
5826 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005827
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005828 std::unordered_set<audio_format_t> formatSet;
5829 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5830 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005831 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005832 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005833 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005834 formatSet.insert(*formatIter);
5835 }
5836 }
5837 } else {
5838 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5839 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005840 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005841
jiabin81772902018-04-02 17:52:27 -07005842 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005843 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005844 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5845 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5846 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005847 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005848 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5849 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5850 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005851 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005852 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005853 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005854 for (const auto& format : formatSet) {
5855 formatsPtr->push(format);
5856 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005857}
5858
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005859void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005860 ChannelsVector &channelMasks = *channelMasksPtr;
5861 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5862 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5863
5864 // If NEVER, then remove support for channelMasks > stereo.
5865 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5866 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5867 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5868 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5869 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5870 channelMasks.removeAt(maskIndex);
5871 } else {
5872 maskIndex++;
5873 }
5874 }
jiabin81772902018-04-02 17:52:27 -07005875 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5876 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5877 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005878 bool supports5dot1 = false;
5879 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005880 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005881 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5882 supports5dot1 = true;
5883 break;
5884 }
5885 }
5886 // If not then add 5.1 support.
5887 if (!supports5dot1) {
5888 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005890 }
Phil Burk09bc4612016-02-24 15:58:15 -08005891 }
5892}
5893
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005894void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005895 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005896 AudioProfileVector &profiles)
5897{
5898 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005899 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005900
François Gaffie112b0af2015-11-19 16:13:25 +01005901 // Format MUST be checked first to update the list of AudioProfile
5902 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005903 reply = mpClientInterface->getParameters(
5904 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005905 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005906 AudioParameter repliedParameters(reply);
5907 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005908 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005909 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5910 return;
5911 }
Phil Burk09bc4612016-02-24 15:58:15 -08005912 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005913 if (device == AUDIO_DEVICE_OUT_HDMI
5914 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005915 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005916 }
Phil Burk09bc4612016-02-24 15:58:15 -08005917 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005918 }
François Gaffie112b0af2015-11-19 16:13:25 +01005919
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005920 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005921 ChannelsVector channelMasks;
5922 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005923 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005924 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005925
5926 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005927 reply = mpClientInterface->getParameters(
5928 ioHandle,
5929 requestedParameters.toString() + ";" +
5930 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005931 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005932 AudioParameter repliedParameters(reply);
5933 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005934 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005935 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005936 }
5937 }
5938 if (profiles.hasDynamicChannelsFor(format)) {
5939 reply = mpClientInterface->getParameters(ioHandle,
5940 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005941 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005942 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005943 AudioParameter repliedParameters(reply);
5944 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005945 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005946 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005947 if (device == AUDIO_DEVICE_OUT_HDMI
5948 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005949 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005950 }
François Gaffie112b0af2015-11-19 16:13:25 +01005951 }
5952 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005953 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005954 }
5955}
Eric Laurentd60560a2015-04-10 11:31:20 -07005956
Mikhail Naganovdc769682018-05-04 15:34:08 -07005957status_t AudioPolicyManager::installPatch(const char *caller,
5958 audio_patch_handle_t *patchHandle,
5959 AudioIODescriptorInterface *ioDescriptor,
5960 const struct audio_patch *patch,
5961 int delayMs)
5962{
5963 ssize_t index = mAudioPatches.indexOfKey(
5964 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5965 *patchHandle : ioDescriptor->getPatchHandle());
5966 sp<AudioPatch> patchDesc;
5967 status_t status = installPatch(
5968 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5969 if (status == NO_ERROR) {
5970 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5971 }
5972 return status;
5973}
5974
5975status_t AudioPolicyManager::installPatch(const char *caller,
5976 ssize_t index,
5977 audio_patch_handle_t *patchHandle,
5978 const struct audio_patch *patch,
5979 int delayMs,
5980 uid_t uid,
5981 sp<AudioPatch> *patchDescPtr)
5982{
5983 sp<AudioPatch> patchDesc;
5984 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5985 if (index >= 0) {
5986 patchDesc = mAudioPatches.valueAt(index);
5987 afPatchHandle = patchDesc->mAfPatchHandle;
5988 }
5989
5990 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5991 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5992 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5993 if (status == NO_ERROR) {
5994 if (index < 0) {
5995 patchDesc = new AudioPatch(patch, uid);
5996 addAudioPatch(patchDesc->mHandle, patchDesc);
5997 } else {
5998 patchDesc->mPatch = *patch;
5999 }
6000 patchDesc->mAfPatchHandle = afPatchHandle;
6001 if (patchHandle) {
6002 *patchHandle = patchDesc->mHandle;
6003 }
6004 nextAudioPortGeneration();
6005 mpClientInterface->onAudioPatchListUpdate();
6006 }
6007 if (patchDescPtr) *patchDescPtr = patchDesc;
6008 return status;
6009}
6010
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006011} // namespace android