blob: c8dd362c48f2eb82e7b9ed401102649b2fac5e03 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie44481e72016-04-20 07:49:57 +020091void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
92 audio_policy_dev_state_t state,
93 const String8 &device_address)
94{
95 AudioParameter param(device_address);
96 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070097 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020098 param.addInt(key, device);
99 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
100}
101
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800103 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800104 const char *device_address,
105 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800106{
Paul McLeane743a472015-01-28 11:07:31 -0800107 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800108 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700109
110 // connect/disconnect only 1 device at a time
111 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
112
François Gaffie53615e22015-03-19 09:24:12 +0100113 sp<DeviceDescriptor> devDesc =
114 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800115
Eric Laurente552edb2014-03-10 17:42:56 -0700116 // handle output devices
117 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700118 SortedVector <audio_io_handle_t> outputs;
119
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // save a copy of the opened output descriptors before any output is opened or closed
123 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
124 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 switch (state)
126 {
127 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800128 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700129 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700130 ALOGW("setDeviceConnectionState() device already connected: %x", device);
131 return INVALID_OPERATION;
132 }
133 ALOGV("setDeviceConnectionState() connecting device %x", device);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 index = mAvailableOutputDevices.add(devDesc);
137 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100138 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700139 if (module == 0) {
140 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
141 device);
142 mAvailableOutputDevices.remove(devDesc);
143 return INVALID_OPERATION;
144 }
Paul McLeane743a472015-01-28 11:07:31 -0800145 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 } else {
147 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 }
149
François Gaffie44481e72016-04-20 07:49:57 +0200150 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
151 // parameters on newly connected devices (instead of opening the outputs...)
152 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
153
Eric Laurenta1d525f2015-01-29 13:36:45 -0800154 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700155 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200156
157 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
158 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700159 return INVALID_OPERATION;
160 }
François Gaffie2110e042015-03-24 08:41:51 +0100161 // Propagate device availability to Engine
162 mEngine->setDeviceConnectionState(devDesc, state);
163
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700164 // outputs should never be empty here
165 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
166 "checkOutputsForDevice() returned no outputs but status OK");
167 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
168 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169
Eric Laurent3ae5f312015-02-03 17:12:08 -0800170 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700171 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700172 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700173 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700174 ALOGW("setDeviceConnectionState() device not connected: %x", device);
175 return INVALID_OPERATION;
176 }
177
Paul McLean5c477aa2014-08-20 16:47:57 -0700178 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
179
Paul McLeane743a472015-01-28 11:07:31 -0800180 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200181 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700182
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700185
Eric Laurenta1d525f2015-01-29 13:36:45 -0800186 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100187
188 // Propagate device availability to Engine
189 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700190 } break;
191
192 default:
193 ALOGE("setDeviceConnectionState() invalid state: %x", state);
194 return BAD_VALUE;
195 }
196
Mikhail Naganov37977152018-07-11 15:54:44 -0700197 checkForDeviceAndOutputChanges([&]() {
198 // outputs must be closed after checkOutputForAllStrategies() is executed
199 if (!outputs.isEmpty()) {
200 for (audio_io_handle_t output : outputs) {
201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
202 // close unused outputs after device disconnection or direct outputs that have been
203 // opened by checkOutputsForDevice() to query dynamic parameters
204 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
205 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
206 (desc->mDirectOpenCount == 0))) {
207 closeOutput(output);
208 }
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
211 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700213 return false;
214 });
Eric Laurente552edb2014-03-10 17:42:56 -0700215
Eric Laurent87ffa392015-05-22 10:32:38 -0700216 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700217 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
218 updateCallRouting(newDevice);
219 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100220 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
223 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
224 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 // do not force device change on duplicated output because if device is 0, it will
226 // also force a device 0 for the two outputs it is duplicated to which may override
227 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100228 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
229 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100230 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700231 // always force when disconnecting (a non-duplicated device)
232 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700233 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700234 }
Eric Laurente552edb2014-03-10 17:42:56 -0700235 }
236
Eric Laurentd60560a2015-04-10 11:31:20 -0700237 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
238 cleanUpForDevice(devDesc);
239 }
240
Eric Laurent72aa32f2014-05-30 18:51:48 -0700241 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700242 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700243 } // end if is output device
244
Eric Laurente552edb2014-03-10 17:42:56 -0700245 // handle input devices
246 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700247 SortedVector <audio_io_handle_t> inputs;
248
Eric Laurent3a4311c2014-03-17 12:00:47 -0700249 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700250 switch (state)
251 {
252 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700253 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700254 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700255 ALOGW("setDeviceConnectionState() device already connected: %d", device);
256 return INVALID_OPERATION;
257 }
François Gaffie53615e22015-03-19 09:24:12 +0100258 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700259 if (module == NULL) {
260 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
261 device);
262 return INVALID_OPERATION;
263 }
François Gaffie44481e72016-04-20 07:49:57 +0200264
265 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
266 // parameters on newly connected devices (instead of opening the inputs...)
267 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
268
Paul McLean9080a4c2015-06-18 08:24:02 -0700269 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200270 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
271 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700272 return INVALID_OPERATION;
273 }
274
Eric Laurent3a4311c2014-03-17 12:00:47 -0700275 index = mAvailableInputDevices.add(devDesc);
276 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800277 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 } else {
279 return NO_MEMORY;
280 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800281
François Gaffie2110e042015-03-24 08:41:51 +0100282 // Propagate device availability to Engine
283 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700284 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700285
286 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700287 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700288 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700289 ALOGW("setDeviceConnectionState() device not connected: %d", device);
290 return INVALID_OPERATION;
291 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700292
293 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
294
295 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200296 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700297
Paul McLean9080a4c2015-06-18 08:24:02 -0700298 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700300
François Gaffie2110e042015-03-24 08:41:51 +0100301 // Propagate device availability to Engine
302 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700303 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700304
305 default:
306 ALOGE("setDeviceConnectionState() invalid state: %x", state);
307 return BAD_VALUE;
308 }
309
Eric Laurentd4692962014-05-05 18:13:44 -0700310 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700311 // As the input device list can impact the output device selection, update
312 // getDeviceForStrategy() cache
313 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700314
Eric Laurent87ffa392015-05-22 10:32:38 -0700315 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700316 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
317 updateCallRouting(newDevice);
318 }
319
Eric Laurentd60560a2015-04-10 11:31:20 -0700320 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
321 cleanUpForDevice(devDesc);
322 }
323
Eric Laurentb52c1522014-05-20 11:27:36 -0700324 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700325 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700326 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700327
328 ALOGW("setDeviceConnectionState() invalid device: %x", device);
329 return BAD_VALUE;
330}
331
Eric Laurente0720872014-03-11 09:30:41 -0700332audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100333 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700334{
Eric Laurent634b7142016-04-20 13:48:02 -0700335 sp<DeviceDescriptor> devDesc =
336 mHwModules.getDeviceDescriptor(device, device_address, "",
337 (strlen(device_address) != 0)/*matchAddress*/);
338
339 if (devDesc == 0) {
340 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
341 device, device_address);
342 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
343 }
François Gaffie53615e22015-03-19 09:24:12 +0100344
Eric Laurent3a4311c2014-03-17 12:00:47 -0700345 DeviceVector *deviceVector;
346
Eric Laurente552edb2014-03-10 17:42:56 -0700347 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700348 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700349 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700350 deviceVector = &mAvailableInputDevices;
351 } else {
352 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700354 }
Eric Laurent634b7142016-04-20 13:48:02 -0700355
356 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
357 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800358}
359
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800360status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
361 const char *device_address,
362 const char *device_name)
363{
364 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700365 String8 reply;
366 AudioParameter param;
367 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800368
369 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
370 device, device_address, device_name);
371
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800372 // connect/disconnect only 1 device at a time
373 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
374
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800375 // Check if the device is currently connected
376 sp<DeviceDescriptor> devDesc =
377 mHwModules.getDeviceDescriptor(device, device_address, device_name);
378 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
379 if (index < 0) {
380 // Nothing to do: device is not connected
381 return NO_ERROR;
382 }
383
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700384 // For offloaded A2DP, Hw modules may have the capability to
385 // configure codecs. Check if any of the loaded hw modules
386 // supports this.
387 // If supported, send a set parameter to configure A2DP codecs
388 // and return. No need to toggle device state.
389 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
390 reply = mpClientInterface->getParameters(
391 AUDIO_IO_HANDLE_NONE,
392 String8(AudioParameter::keyReconfigA2dpSupported));
393 AudioParameter repliedParameters(reply);
394 repliedParameters.getInt(
395 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
396 if (isReconfigA2dpSupported) {
397 const String8 key(AudioParameter::keyReconfigA2dp);
398 param.add(key, String8("true"));
399 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
400 return NO_ERROR;
401 }
402 }
403
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800404 // Toggle the device state: UNAVAILABLE -> AVAILABLE
405 // This will force reading again the device configuration
406 status = setDeviceConnectionState(device,
407 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
408 device_address, device_name);
409 if (status != NO_ERROR) {
410 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
411 status);
412 return status;
413 }
414
415 status = setDeviceConnectionState(device,
416 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
417 device_address, device_name);
418 if (status != NO_ERROR) {
419 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
420 status);
421 return status;
422 }
423
424 return NO_ERROR;
425}
426
Eric Laurentdc462862016-07-19 12:29:53 -0700427uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700428{
429 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700430 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700431
Andy Hunga76c7de2016-12-13 19:14:31 -0800432 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700433 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700434 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800435 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
437
438 // release existing RX patch if any
439 if (mCallRxPatch != 0) {
440 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
441 mCallRxPatch.clear();
442 }
443 // release TX patch if any
444 if (mCallTxPatch != 0) {
445 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
446 mCallTxPatch.clear();
447 }
448
449 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
450 // via setOutputDevice() on primary output.
451 // Otherwise, create two audio patches for TX and RX path.
452 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700453 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454 // If the TX device is also on the primary HW module, setOutputDevice() will take care
455 // of it due to legacy implementation. If not, create a patch.
456 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
457 == AUDIO_DEVICE_NONE) {
458 createTxPatch = true;
459 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700460 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800461 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 createTxPatch = true;
463 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700464 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800465 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
466 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700467
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800468 return muteWaitMs;
469}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700470
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
472 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700473 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700474
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800475 sp<DeviceDescriptor> txSourceDeviceDesc;
476 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700477 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
478 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700480 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
481 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482 }
483
484 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
485 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
486 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
487 // request to reuse existing output stream if one is already opened to reach the target device
488 if (output != AUDIO_IO_HANDLE_NONE) {
489 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
490 ALOG_ASSERT(!outputDesc->isDuplicated(),
491 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700492 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800493 }
494
495 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700496 // terminate active capture if on the same HW module as the call TX source device
497 // FIXME: would be better to refine to only inputs whose profile connects to the
498 // call TX device but this information is not in the audio patch and logic here must be
499 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800500 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800501 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700502 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700503 }
504 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700505 }
Eric Laurentdc462862016-07-19 12:29:53 -0700506
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800507 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700508 status_t status = mpClientInterface->createAudioPatch(
509 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800510 ALOGW_IF(status != NO_ERROR,
511 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
512 sp<AudioPatch> audioPatch;
513 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700514 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800515 audioPatch->mAfPatchHandle = afPatchHandle;
516 audioPatch->mUid = mUidCached;
517 }
518 return audioPatch;
519}
520
Mikhail Naganovdc769682018-05-04 15:34:08 -0700521sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100522 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700523 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800524 ALOG_ASSERT(!deviceList.isEmpty(),
525 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700527}
528
Eric Laurente0720872014-03-11 09:30:41 -0700529void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700530{
531 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100532 // store previous phone state for management of sonification strategy below
533 int oldState = mEngine->getPhoneState();
534
535 if (mEngine->setPhoneState(state) != NO_ERROR) {
536 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700537 return;
538 }
François Gaffie2110e042015-03-24 08:41:51 +0100539 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700540 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700541 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700542 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800543 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
545
François Gaffie2110e042015-03-24 08:41:51 +0100546 /**
547 * Switching to or from incall state or switching between telephony and VoIP lead to force
548 * routing command.
549 */
550 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
551 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700552
553 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700554 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700555
Eric Laurente552edb2014-03-10 17:42:56 -0700556 int delayMs = 0;
557 if (isStateInCall(state)) {
558 nsecs_t sysTime = systemTime();
559 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700561 // mute media and sonification strategies and delay device switch by the largest
562 // latency of any output where either strategy is active.
563 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100564 if ((isStrategyActive(desc, STRATEGY_MEDIA,
565 SONIFICATION_HEADSET_MUSIC_DELAY,
566 sysTime) ||
567 isStrategyActive(desc, STRATEGY_SONIFICATION,
568 SONIFICATION_HEADSET_MUSIC_DELAY,
569 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700570 (delayMs < (int)desc->latency()*2)) {
571 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700572 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 setStrategyMute(STRATEGY_MEDIA, true, desc);
574 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700575 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
577 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700578 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
579 }
580 }
581
Eric Laurent87ffa392015-05-22 10:32:38 -0700582 if (hasPrimaryOutput()) {
583 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
584 // the device returned is not necessarily reachable via this output
585 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
586 // force routing command to audio hardware when ending call
587 // even if no device change is needed
588 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
589 rxDevice = mPrimaryOutput->device();
590 }
Eric Laurente552edb2014-03-10 17:42:56 -0700591
Eric Laurent87ffa392015-05-22 10:32:38 -0700592 if (state == AUDIO_MODE_IN_CALL) {
593 updateCallRouting(rxDevice, delayMs);
594 } else if (oldState == AUDIO_MODE_IN_CALL) {
595 if (mCallRxPatch != 0) {
596 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
597 mCallRxPatch.clear();
598 }
599 if (mCallTxPatch != 0) {
600 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
601 mCallTxPatch.clear();
602 }
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
604 } else {
605 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700607 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700608
609 // reevaluate routing on all outputs in case tracks have been started during the call
610 for (size_t i = 0; i < mOutputs.size(); i++) {
611 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
612 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
613 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800614 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700615 }
616 }
617
Eric Laurente552edb2014-03-10 17:42:56 -0700618 if (isStateInCall(state)) {
619 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700620 // force reevaluating accessibility routing when call starts
621 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
623
624 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700625 if (state == AUDIO_MODE_RINGTONE &&
626 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700627 mLimitRingtoneVolume = true;
628 } else {
629 mLimitRingtoneVolume = false;
630 }
631}
632
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700633audio_mode_t AudioPolicyManager::getPhoneState() {
634 return mEngine->getPhoneState();
635}
636
Eric Laurente0720872014-03-11 09:30:41 -0700637void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700638 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700639{
François Gaffie2110e042015-03-24 08:41:51 +0100640 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700641 if (config == mEngine->getForceUse(usage)) {
642 return;
643 }
Eric Laurente552edb2014-03-10 17:42:56 -0700644
François Gaffie2110e042015-03-24 08:41:51 +0100645 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
646 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
647 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700648 }
François Gaffie2110e042015-03-24 08:41:51 +0100649 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
651 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700652
653 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700654 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800655
Eric Laurentdc462862016-07-19 12:29:53 -0700656 //FIXME: workaround for truncated touch sounds
657 // to be removed when the problem is handled by system UI
658 uint32_t delayMs = 0;
659 uint32_t waitMs = 0;
660 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
661 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
662 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700663 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700665 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666 }
Eric Laurente552edb2014-03-10 17:42:56 -0700667 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700668 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
669 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
670 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700671 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
672 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurente552edb2014-03-10 17:42:56 -0700674 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700675 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700676 }
677 }
678
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800679 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800680 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700681 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800682 if (activeDesc->mProfile->getSupportedDevices().types() &
683 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
684 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689}
690
Eric Laurente0720872014-03-11 09:30:41 -0700691void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700692{
693 ALOGV("setSystemProperty() property %s, value %s", property, value);
694}
695
696// Find a direct output profile compatible with the parameters passed, even if the input flags do
697// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800698sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700699 audio_devices_t device,
700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags)
704{
Eric Laurent861a6282015-05-18 15:40:16 -0700705 // only retain flags that will drive the direct output profile selection
706 // if explicitly requested
707 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700708 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
709 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700710 flags =
711 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
712
713 sp<IOProfile> profile;
714
Mikhail Naganovd4120142017-12-06 15:49:22 -0800715 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800716 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700717 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700718 samplingRate, NULL /*updatedSamplingRate*/,
719 format, NULL /*updatedFormat*/,
720 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700721 flags)) {
722 continue;
723 }
724 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100725 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700726 continue;
727 }
728 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100729 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 continue;
731 }
732 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100733 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700734 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700735 }
Eric Laurente552edb2014-03-10 17:42:56 -0700736 }
737 }
Eric Laurent861a6282015-05-18 15:40:16 -0700738 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700739}
740
Eric Laurentf4e63452017-11-06 19:31:46 +0000741audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700742{
Eric Laurent3b73df72014-03-11 09:06:29 -0700743 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700744 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800745
746 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
747 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
748 // format, flags, etc. This may result in some discrepancy for functions that utilize
749 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
750 // and AudioSystem::getOutputSamplingRate().
751
Eric Laurentf4e63452017-11-06 19:31:46 +0000752 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
753 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700754
Eric Laurentf4e63452017-11-06 19:31:46 +0000755 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
756 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700757}
758
Eric Laurente83b55d2014-11-14 10:06:21 -0800759status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
760 audio_io_handle_t *output,
761 audio_session_t session,
762 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700763 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800764 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200765 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700766 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800767 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768{
Eric Laurente83b55d2014-11-14 10:06:21 -0800769 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700770 DeviceVector outputDevices;
771 routing_strategy strategy;
772 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700773 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100774 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700775
Eric Laurent8f42ea12018-08-08 09:08:25 -0700776 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
777 if (*portId != AUDIO_PORT_HANDLE_NONE) {
778 return INVALID_OPERATION;
779 }
780
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 if (attr != NULL) {
782 if (!isValidAttributes(attr)) {
783 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
784 attr->usage, attr->content_type, attr->flags,
785 attr->tags);
786 return BAD_VALUE;
787 }
788 attributes = *attr;
789 } else {
790 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
791 ALOGE("getOutputForAttr(): invalid stream type");
792 return BAD_VALUE;
793 }
794 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700795 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700797 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700798 " session %d selectedDeviceId %d",
799 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
800 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700801
Eric Laurent97ac8712018-07-27 18:59:02 -0700802 *stream = streamTypefromAttributesInt(&attributes);
803
804 strategy = getStrategyForAttr(&attributes);
805
Scott Randolph7b1fd232018-06-18 15:33:03 -0700806 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700807 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
808 sp<DeviceDescriptor> deviceDesc =
809 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
810 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700811 } else {
812 // If no explict route, is there a matching dynamic policy that applies?
813 sp<SwAudioOutputDescriptor> desc;
814 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
815 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
816 if (!audio_has_proportional_frames(config->format)) {
817 return BAD_VALUE;
818 }
819 *stream = streamTypefromAttributesInt(&attributes);
820 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700821 AudioMix *mix = desc->mPolicyMix;
822 sp<DeviceDescriptor> deviceDesc =
823 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
824 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700825 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700826 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700827 }
828
829 // Virtual sources must always be dynamicaly or explicitly routed
830 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
831 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
832 return BAD_VALUE;
833 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700834 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700835 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200838 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839 }
840
Nadav Barb2f18162018-07-18 13:01:53 +0300841 // Set incall music only if device was explicitly set, and fallback to the device which is
842 // chosen by the engine if not.
843 // FIXME: provide a more generic approach which is not device specific and move this back
844 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200845 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300846 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200847 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300848 audio_is_linear_pcm(config->format) &&
849 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700850 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300851 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
852 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700853 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300854 device = mEngine->getDeviceForStrategy(strategy);
855 }
856 }
857
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800858 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
859 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200860 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700861
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100862 *output = AUDIO_IO_HANDLE_NONE;
863 if (msdDevice != AUDIO_DEVICE_NONE) {
864 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
865 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
866 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
867 __func__, msdDevice, device);
868 device = msdDevice;
869 } else {
870 *output = AUDIO_IO_HANDLE_NONE;
871 }
872 }
873 if (*output == AUDIO_IO_HANDLE_NONE) {
874 *output = getOutputForDevice(device, session, *stream, config, flags);
875 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800876 if (*output == AUDIO_IO_HANDLE_NONE) {
877 return INVALID_OPERATION;
878 }
Paul McLeanaa981192015-03-21 09:55:15 -0700879
Eric Laurent8fc147b2018-07-22 19:13:55 -0700880 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700881 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
882 : AUDIO_PORT_HANDLE_NONE;
883
Eric Laurent8fc147b2018-07-22 19:13:55 -0700884exit:
885 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
886 .format = config->format,
887 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700888 *portId = AudioPort::getNextUniqueId();
889
Eric Laurent8fc147b2018-07-22 19:13:55 -0700890 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700891 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
892 requestedDeviceId, *stream,
893 getStrategyForAttr(&attributes),
894 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700895 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700896 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700897
898 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
899 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700900
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700902}
903
904audio_io_handle_t AudioPolicyManager::getOutputForDevice(
905 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800906 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700907 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800908 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200909 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700910{
Andy Hungc88b0642018-04-27 15:42:35 -0700911 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700912 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700913
Eric Laurente552edb2014-03-10 17:42:56 -0700914 // open a direct output if required by specified parameters
915 //force direct flag if offload flag is set: offloading implies a direct output stream
916 // and all common behaviors are driven by checking only the direct flag
917 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200918 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
919 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
Nadav Bar766fb022018-01-07 12:18:03 +0200921 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
922 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700923 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800924 // only allow deep buffering for music stream type
925 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200926 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700927 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200928 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700929 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
930 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200931 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800932 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700933 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200934 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700935 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200936 audio_is_linear_pcm(config->format) &&
937 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200938 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700939 AUDIO_OUTPUT_FLAG_DIRECT);
940 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700941 }
Eric Laurente552edb2014-03-10 17:42:56 -0700942
Nadav Bar766fb022018-01-07 12:18:03 +0200943
Eric Laurentb732cf52014-09-24 19:08:21 -0700944 sp<IOProfile> profile;
945
946 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700947 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200948 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800949 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
950 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700951 goto non_direct_output;
952 }
953
Andy Hung2ddee192015-12-18 17:34:44 -0800954 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
955 // This prevents creating an offloaded track and tearing it down immediately after start
956 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700957 // FIXME: We should check the audio session here but we do not have it in this context.
958 // This may prevent offloading in rare situations where effects are left active by apps
959 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700960
Nadav Bar766fb022018-01-07 12:18:03 +0200961 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800962 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700963 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800964 config->sample_rate,
965 config->format,
966 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200967 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700968 }
969
Eric Laurent1c333e22014-05-20 10:48:17 -0700970 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700971 // exclusive outputs for MMAP and Offload are enforced by different session ids.
972 for (size_t i = 0; i < mOutputs.size(); i++) {
973 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
974 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
975 // reuse direct output if currently open by the same client
976 // and configured with same parameters
977 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700978 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700979 (config->channel_mask == desc->mChannelMask) &&
980 (session == desc->mDirectClientSession)) {
981 desc->mDirectOpenCount++;
982 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
983 mOutputs.keyAt(i), session);
984 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700985 }
986 }
987 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800988
989 if (!profile->canOpenNewIo()) {
990 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700991 }
Eric Laurent861a6282015-05-18 15:40:16 -0700992
Eric Laurent3974e3b2017-12-07 17:58:43 -0800993 sp<SwAudioOutputDescriptor> outputDesc =
994 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800995
Mikhail Naganov708e0382018-05-30 09:53:04 -0700996 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800997 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
998 : String8("");
999
Dean Wheatley3023b382018-08-09 07:42:40 +10001000 // MSD patch may be using the only output stream that can service this request. Release
1001 // MSD patch to prioritize this request over any active output on MSD.
1002 AudioPatchCollection msdPatches = getMsdPatches();
1003 for (size_t i = 0; i < msdPatches.size(); i++) {
1004 const auto& patch = msdPatches[i];
1005 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1006 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1007 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1008 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1009 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1010 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1011 releaseAudioPatch(patch->mHandle, mUidCached);
1012 break;
1013 }
1014 }
1015 }
1016
Nadav Bar766fb022018-01-07 12:18:03 +02001017 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001018
1019 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001020 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001021 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001022 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001023 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1024 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1025 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1026 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1027 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001028 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001029 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001031 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001032 if (audio_is_linear_pcm(config->format) &&
1033 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001034 goto non_direct_output;
1035 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001036 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001037 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001039 outputDesc->mDirectClientSession = session;
1040
Eric Laurente552edb2014-03-10 17:42:56 -07001041 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001043 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001044 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001045 return output;
1046 }
1047
Eric Laurentb732cf52014-09-24 19:08:21 -07001048non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001049
1050 // A request for HW A/V sync cannot fallback to a mixed output because time
1051 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001052 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001053 return AUDIO_IO_HANDLE_NONE;
1054 }
1055
Eric Laurente552edb2014-03-10 17:42:56 -07001056 // ignoring channel mask due to downmix capability in mixer
1057
1058 // open a non direct output
1059
1060 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001061 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001062 // get which output is suitable for the specified stream. The actual
1063 // routing change will happen when startOutput() will be called
1064 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1065
Eric Laurent8838a382014-09-08 16:44:28 -07001066 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001067 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1068 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001069 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001070 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001071 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001072 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Eric Laurente552edb2014-03-10 17:42:56 -07001074 return output;
1075}
1076
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001077sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001078 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001079 if (msdModule != 0) {
1080 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1081 msdModule->getHandle());
1082 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1083 }
1084 return 0;
1085}
1086
1087audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001088 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001089 if (msdModule != 0) {
1090 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1091 }
1092 return AUDIO_DEVICE_NONE;
1093}
1094
1095const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1096 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001097 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1098 if (msdModule != 0) {
1099 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1100 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1101 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1102 const struct audio_port_config *source = &patch->mPatch.sources[j];
1103 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1104 source->ext.device.hw_module == msdModule->getHandle()) {
1105 msdPatches.addAudioPatch(patch->mHandle, patch);
1106 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001107 }
1108 }
1109 }
1110 return msdPatches;
1111}
1112
1113status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1114 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1115{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001116 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001117 if (msdModule == nullptr) {
1118 ALOGE("%s() unable to get MSD module", __func__);
1119 return NO_INIT;
1120 }
1121 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1122 if (deviceModule == nullptr) {
1123 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1124 return NO_INIT;
1125 }
1126 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1127 if (inputProfiles.isEmpty()) {
1128 ALOGE("%s() no input profiles for MSD module", __func__);
1129 return NO_INIT;
1130 }
1131 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1132 if (outputProfiles.isEmpty()) {
1133 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1134 return NO_INIT;
1135 }
1136 AudioProfileVector msdProfiles;
1137 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1138 for (const auto &inProfile : inputProfiles) {
1139 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1140 msdProfiles.appendVector(inProfile->getAudioProfiles());
1141 }
1142 }
1143 AudioProfileVector deviceProfiles;
1144 for (const auto &outProfile : outputProfiles) {
1145 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1146 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1147 }
1148 }
1149 struct audio_config_base bestSinkConfig;
1150 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1151 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1152 &bestSinkConfig);
1153 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001154 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1155 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001156 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 }
1158 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1159 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1160 sinkConfig->format = bestSinkConfig.format;
1161 // For encoded streams force direct flag to prevent downstream mixing.
1162 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1163 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1164 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1165 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1166 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1167 sourceConfig->format = bestSinkConfig.format;
1168 // Copy input stream directly without any processing (e.g. resampling).
1169 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1170 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1171 if (hwAvSync) {
1172 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1173 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1174 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1175 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1176 }
1177 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1178 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1179 sinkConfig->config_mask |= config_mask;
1180 sourceConfig->config_mask |= config_mask;
1181 return NO_ERROR;
1182}
1183
1184PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1185{
1186 PatchBuilder patchBuilder;
1187 patchBuilder.addSource(getMsdAudioInDevice()).
1188 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1189 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1190 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1191 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1192 // For now, we just forcefully try with HwAvSync first.
1193 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1194 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1195 getBestMsdAudioProfileFor(
1196 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1197 if (res == NO_ERROR) {
1198 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1199 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1200 }
1201 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1202 " supporting PCM format conversion.", __func__);
1203 return patchBuilder;
1204}
1205
1206status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1207 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1208 if (outputDevice == AUDIO_DEVICE_NONE) {
1209 // Use media strategy for unspecified output device. This should only
1210 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1211 // therefore invalidate explicit routing requests.
1212 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1213 }
1214 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1215 const struct audio_patch* patch = patchBuilder.patch();
1216 const AudioPatchCollection msdPatches = getMsdPatches();
1217 if (!msdPatches.isEmpty()) {
1218 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1219 "The current MSD prototype only supports one output patch");
1220 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1221 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1222 return NO_ERROR;
1223 }
1224 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1225 }
1226 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1227 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1228 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1229 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1230 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1231 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1232 return status;
1233}
1234
Eric Laurente0720872014-03-11 09:30:41 -07001235audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001236 audio_output_flags_t flags,
1237 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001238{
1239 // select one output among several that provide a path to a particular device or set of
1240 // devices (the list was previously build by getOutputsForDevice()).
1241 // The priority is as follows:
1242 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001243 // 2: the output with the bit depth the closest to the requested one
1244 // 3: the primary output
1245 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001246
1247 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001248 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001249 }
1250 if (outputs.size() == 1) {
1251 return outputs[0];
1252 }
1253
1254 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001255 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1257 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001258 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1259 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001260
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001261 for (audio_io_handle_t output : outputs) {
1262 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001263 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001264 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1265 continue;
1266 }
Eric Laurent8838a382014-09-08 16:44:28 -07001267 // if a valid format is specified, skip output if not compatible
1268 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001269 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001270 continue;
1271 }
Eric Laurente6930022016-02-11 10:20:40 -08001272 if (AudioPort::isBetterFormatMatch(
1273 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001274 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001275 bestFormat = outputDesc->mFormat;
1276 }
Eric Laurent8838a382014-09-08 16:44:28 -07001277 }
1278
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001279 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001280 if (commonFlags >= maxCommonFlags) {
1281 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001282 if (format != AUDIO_FORMAT_INVALID
1283 && AudioPort::isBetterFormatMatch(
1284 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001285 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001286 bestFormatForFlags = outputDesc->mFormat;
1287 }
1288 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001289 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001290 maxCommonFlags = commonFlags;
1291 bestFormatForFlags = outputDesc->mFormat;
1292 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001293 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001295 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001296 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
1298 }
1299 }
1300
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001301 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001302 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001303 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001304 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001305 return outputForFormat;
1306 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001307 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001308 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310
1311 return outputs[0];
1312}
1313
Eric Laurent8fc147b2018-07-22 19:13:55 -07001314status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001315{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 ALOGV("%s portId %d", __FUNCTION__, portId);
1317
1318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1319 if (outputDesc == 0) {
1320 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001321 return BAD_VALUE;
1322 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001323 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001324
Eric Laurent8fc147b2018-07-22 19:13:55 -07001325 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001326 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001327
Eric Laurent733ce942017-12-07 12:18:25 -08001328 status_t status = outputDesc->start();
1329 if (status != NO_ERROR) {
1330 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001331 }
1332
Eric Laurent97ac8712018-07-27 18:59:02 -07001333 uint32_t delayMs;
1334 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001335
1336 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001337 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001338 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 if (delayMs != 0) {
1341 usleep(delayMs * 1000);
1342 }
1343
1344 return status;
1345}
1346
Eric Laurent97ac8712018-07-27 18:59:02 -07001347status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1348 const sp<TrackClientDescriptor>& client,
1349 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001350{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001351 // cannot start playback of STREAM_TTS if any other output is being used
1352 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001353
1354 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001355 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001356 if (stream == AUDIO_STREAM_TTS) {
1357 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001358 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001359 return INVALID_OPERATION;
1360 } else {
1361 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1362 }
1363 } else {
1364 // some playback other than beacon starts
1365 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1366 }
1367
Eric Laurent77305a62016-07-25 16:39:22 -07001368 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001369 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001370 bool force = !outputDesc->isActive() &&
1371 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001372
Eric Laurent97ac8712018-07-27 18:59:02 -07001373 audio_devices_t device = AUDIO_DEVICE_NONE;
1374 AudioMix *policyMix = NULL;
1375 const char *address = NULL;
1376 if (outputDesc->mPolicyMix != NULL) {
1377 policyMix = outputDesc->mPolicyMix;
1378 address = policyMix->mDeviceAddress.string();
1379 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1380 device = policyMix->mDeviceType;
1381 } else {
1382 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1383 }
1384 }
1385
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001386 // requiresMuteCheck is false when we can bypass mute strategy.
1387 // It covers a common case when there is no materially active audio
1388 // and muting would result in unnecessary delay and dropped audio.
1389 const uint32_t outputLatencyMs = outputDesc->latency();
1390 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1391
Eric Laurente552edb2014-03-10 17:42:56 -07001392 // increment usage count for this stream on the requested output:
1393 // NOTE that the usage count is the same for duplicated output and hardware output which is
1394 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001395 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001396
1397 if (client->hasPreferredDevice(true)) {
1398 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1399 if (device != outputDesc->device()) {
1400 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1401 }
1402 }
Eric Laurente552edb2014-03-10 17:42:56 -07001403
Eric Laurent36829f92017-04-07 19:04:42 -07001404 if (stream == AUDIO_STREAM_MUSIC) {
1405 selectOutputForMusicEffects();
1406 }
1407
Eric Laurent592dd7b2018-08-05 18:58:48 -07001408 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 if (device == AUDIO_DEVICE_NONE) {
1411 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001412 }
Eric Laurent36829f92017-04-07 19:04:42 -07001413
Eric Laurente552edb2014-03-10 17:42:56 -07001414 routing_strategy strategy = getStrategy(stream);
1415 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001416 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1417 (beaconMuteLatency > 0);
1418 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001419 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001420 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001422 // An output has a shared device if
1423 // - managed by the same hw module
1424 // - supports the currently selected device
1425 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1426 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1427
Eric Laurent77305a62016-07-25 16:39:22 -07001428 // force a device change if any other output is:
1429 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001430 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001431 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001432 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001433 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001434 // change the device currently selected by the other output.
1435 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001437 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001438 force = true;
1439 }
1440 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001441 // a notification so that audio focus effect can propagate, or that a mute/unmute
1442 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001443 const uint32_t latencyMs = desc->latency();
1444 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1445
1446 if (shouldWait && isActive && (waitMs < latencyMs)) {
1447 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001448 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001449
1450 // Require mute check if another output is on a shared device
1451 // and currently active to have proper drain and avoid pops.
1452 // Note restoring AudioTracks onto this output needs to invoke
1453 // a volume ramp if there is no mute.
1454 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001455 }
1456 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001457
1458 const uint32_t muteWaitMs =
1459 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001460
Eric Laurente552edb2014-03-10 17:42:56 -07001461 // apply volume rules for current stream and device if necessary
1462 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001463 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001464 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001465 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001466
1467 // update the outputs if starting an output with a stream that can affect notification
1468 // routing
1469 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001470
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001471 // force reevaluating accessibility routing when ringtone or alarm starts
1472 if (strategy == STRATEGY_SONIFICATION) {
1473 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1474 }
Eric Laurentdc462862016-07-19 12:29:53 -07001475
1476 if (waitMs > muteWaitMs) {
1477 *delayMs = waitMs - muteWaitMs;
1478 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001479
1480 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1481 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1482 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1483 // change occurs after the MixerThread starts and causes a stream volume
1484 // glitch.
1485 //
1486 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
Eric Laurentdc462862016-07-19 12:29:53 -07001488
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001489 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1490 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1491 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1492 }
1493
Eric Laurent97ac8712018-07-27 18:59:02 -07001494 // Automatically enable the remote submix input when output is started on a re routing mix
1495 // of type MIX_TYPE_RECORDERS
1496 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1497 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1498 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1499 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1500 address,
1501 "remote-submix");
1502 }
1503
Eric Laurente552edb2014-03-10 17:42:56 -07001504 return NO_ERROR;
1505}
1506
Eric Laurent8fc147b2018-07-22 19:13:55 -07001507status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001508{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 ALOGV("%s portId %d", __FUNCTION__, portId);
1510
1511 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1512 if (outputDesc == 0) {
1513 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 return BAD_VALUE;
1515 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001516 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent97ac8712018-07-27 18:59:02 -07001518 ALOGV("stopOutput() output %d, stream %d, session %d",
1519 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001520
Eric Laurent97ac8712018-07-27 18:59:02 -07001521 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001522
Eric Laurent733ce942017-12-07 12:18:25 -08001523 if (status == NO_ERROR ) {
1524 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001525 }
1526 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001527}
1528
Eric Laurent97ac8712018-07-27 18:59:02 -07001529status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1530 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001531{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001532 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001533 audio_stream_type_t stream = client->stream();
1534
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001535 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1536
Eric Laurent592dd7b2018-08-05 18:58:48 -07001537 if (outputDesc->streamActiveCount(stream) > 0) {
1538 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001539 // Automatically disable the remote submix input when output is stopped on a
1540 // re routing mix of type MIX_TYPE_RECORDERS
1541 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1542 outputDesc->mPolicyMix != NULL &&
1543 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1544 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1545 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1546 outputDesc->mPolicyMix->mDeviceAddress,
1547 "remote-submix");
1548 }
1549 }
1550 bool forceDeviceUpdate = false;
1551 if (client->hasPreferredDevice(true)) {
1552 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1553 forceDeviceUpdate = true;
1554 }
1555
Eric Laurente552edb2014-03-10 17:42:56 -07001556 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001557 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001560 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001561 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001562 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001563 // delay the device switch by twice the latency because stopOutput() is executed when
1564 // the track stop() command is received and at that time the audio track buffer can
1565 // still contain data that needs to be drained. The latency only covers the audio HAL
1566 // and kernel buffers. Also the latency does not always include additional delay in the
1567 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001568 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
1570 // force restoring the device selection on other active outputs if it differs from the
1571 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001572 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001573 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001574 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001575 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001576 desc->isActive() &&
1577 outputDesc->sharesHwModuleWith(desc) &&
1578 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001579 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1580 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001581
Eric Laurentc75307b2015-03-17 15:29:32 -07001582 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001583 newDevice2,
1584 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001585 delayMs);
1586 // re-apply device specific volume if not done by setOutputDevice()
1587 if (!force) {
1588 applyStreamVolumes(desc, newDevice2, delayMs);
1589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590 }
1591 }
1592 // update the outputs if stopping one with a stream that can affect notification routing
1593 handleNotificationRoutingForStream(stream);
1594 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001595
1596 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1597 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1598 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1599 }
1600
Eric Laurent36829f92017-04-07 19:04:42 -07001601 if (stream == AUDIO_STREAM_MUSIC) {
1602 selectOutputForMusicEffects();
1603 }
Eric Laurente552edb2014-03-10 17:42:56 -07001604 return NO_ERROR;
1605 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001606 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001607 return INVALID_OPERATION;
1608 }
1609}
1610
Eric Laurent8fc147b2018-07-22 19:13:55 -07001611void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001612{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001613 ALOGV("%s portId %d", __FUNCTION__, portId);
1614
1615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1616 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001617 // If an output descriptor is closed due to a device routing change,
1618 // then there are race conditions with releaseOutput from tracks
1619 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1620 // destroyed shortly thereafter.
1621 //
1622 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001623 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001624 return;
1625 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001626
1627 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001628
Eric Laurent8fc147b2018-07-22 19:13:55 -07001629 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1630 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001631 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001632 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001633 return;
1634 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001635 if (--outputDesc->mDirectOpenCount == 0) {
1636 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001637 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001638 }
1639 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001640 // stopOutput() needs to be successfully called before releaseOutput()
1641 // otherwise there may be inaccurate stream reference counts.
1642 // This is checked in outputDesc->removeClient below.
1643 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001644}
1645
Eric Laurentcaf7f482014-11-25 17:50:47 -08001646status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1647 audio_io_handle_t *input,
1648 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001649 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001650 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001651 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001652 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001653 input_type_t *inputType,
1654 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001655{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001656 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001657 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001658 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001659
Eric Laurentad2e7b92017-09-14 20:06:42 -07001660 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001661 // handle legacy remote submix case where the address was not always specified
1662 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001663 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001664 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001665 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001666 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001667 sp<AudioInputDescriptor> inputDesc;
1668 sp<RecordClientDescriptor> clientDesc;
1669 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001670 bool isSoundTrigger;
1671 audio_devices_t device;
1672
1673 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1674 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1675 return INVALID_OPERATION;
1676 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001677
Eric Laurentfe231122017-11-17 17:48:06 -08001678 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1679 inputSource = AUDIO_SOURCE_MIC;
1680 }
1681
Paul McLean466dc8e2015-04-17 13:15:36 -06001682 // Explicit routing?
1683 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001684 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001685 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001686 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001687
Eric Laurentad2e7b92017-09-14 20:06:42 -07001688 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1689 // possible
1690 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1691 *input != AUDIO_IO_HANDLE_NONE) {
1692 ssize_t index = mInputs.indexOfKey(*input);
1693 if (index < 0) {
1694 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1695 status = BAD_VALUE;
1696 goto error;
1697 }
1698 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001699 RecordClientVector clients = inputDesc->getClientsForSession(session);
1700 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001701 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1702 status = BAD_VALUE;
1703 goto error;
1704 }
1705 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1706 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001707 // corresponds to a new client and is only permitted from the same UID.
1708 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001709 if (clients.size() > 1) {
1710 for (const auto& client : clients) {
1711 // The client map is ordered by key values (portId) and portIds are allocated
1712 // incrementaly. So the first client in this list is the one opened by audio flinger
1713 // when the mmap stream is created and should be ignored as it does not correspond
1714 // to an actual client
1715 if (client == *clients.cbegin()) {
1716 continue;
1717 }
1718 if (uid != client->uid() && !client->isSilenced()) {
1719 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1720 uid, client->portId(), client->uid());
1721 status = INVALID_OPERATION;
1722 goto error;
1723 }
Eric Laurent331679c2018-04-16 17:03:16 -07001724 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001726 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001727 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001728
Eric Laurent8f42ea12018-08-08 09:08:25 -07001729 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001730 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001731 }
1732
1733 *input = AUDIO_IO_HANDLE_NONE;
1734 *inputType = API_INPUT_INVALID;
1735
Eric Laurentad2e7b92017-09-14 20:06:42 -07001736 halInputSource = inputSource;
1737
Eric Laurentc447ded2015-01-06 08:47:05 -08001738 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001739 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001740 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1741 if (status != NO_ERROR) {
1742 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001743 }
1744 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001745 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1746 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001747 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001748 if (deviceDesc != 0) {
1749 device = deviceDesc->type();
1750 } else {
1751 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1752 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001753 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001754 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001755 status = BAD_VALUE;
1756 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001757 }
Eric Laurentc722f302014-12-10 11:21:49 -08001758 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001759 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001760 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1761 // there is an external policy, but this input is attached to a mix of recorders,
1762 // meaning it receives audio injected into the framework, so the recorder doesn't
1763 // know about it and is therefore considered "legacy"
1764 *inputType = API_INPUT_LEGACY;
1765 } else {
1766 // recording a mix of players defined by an external policy, we're rerouting for
1767 // an external policy
1768 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1769 }
Eric Laurentc722f302014-12-10 11:21:49 -08001770 } else if (audio_is_remote_submix_device(device)) {
1771 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001772 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001773 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1774 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001775 } else {
1776 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001777 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001778
Eric Laurent599c7582015-12-07 18:05:55 -08001779 }
1780
Eric Laurent8f42ea12018-08-08 09:08:25 -07001781 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001782 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001783 policyMix);
1784 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001785 status = INVALID_OPERATION;
1786 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001787 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001788
Eric Laurent8f42ea12018-08-08 09:08:25 -07001789exit:
1790
Mikhail Naganov708e0382018-05-30 09:53:04 -07001791 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001792 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001793 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001794
Eric Laurent8f42ea12018-08-08 09:08:25 -07001795 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1796 mSoundTriggerSessions.indexOfKey(session) > 0;
1797 *portId = AudioPort::getNextUniqueId();
1798
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001800 *attr, *config, requestedDeviceId,
1801 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001802 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001803 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001804
1805 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1806 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001807
Eric Laurent599c7582015-12-07 18:05:55 -08001808 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001809
1810error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001811 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001812}
1813
1814
1815audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1816 String8 address,
1817 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001818 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001819 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001820 audio_input_flags_t flags,
1821 AudioMix *policyMix)
1822{
1823 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1824 audio_source_t halInputSource = inputSource;
1825 bool isSoundTrigger = false;
1826
1827 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1828 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1829 if (index >= 0) {
1830 input = mSoundTriggerSessions.valueFor(session);
1831 isSoundTrigger = true;
1832 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1833 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1834 } else {
1835 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001836 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001837 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001838 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001839 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001840 }
1841
Andy Hungf129b032015-04-07 13:45:50 -07001842 // find a compatible input profile (not necessarily identical in parameters)
1843 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001844 // sampling rate and flags may be updated by getInputProfile
1845 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1846 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001847 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001848 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001849 audio_input_flags_t profileFlags = flags;
1850 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001851 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001852 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001853 profileSamplingRate, profileFormat, profileChannelMask,
1854 profileFlags);
1855 if (profile != 0) {
1856 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001857 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1858 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001859 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1860 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1861 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001862 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001863 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1864 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001865 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001868 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001869 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001870 if (samplingRate == 0) {
1871 samplingRate = profileSamplingRate;
1872 }
Eric Laurente552edb2014-03-10 17:42:56 -07001873
Eric Laurent322b4d22015-04-03 15:57:54 -07001874 if (profile->getModuleHandle() == 0) {
1875 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001876 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001877 }
1878
Eric Laurent3974e3b2017-12-07 17:58:43 -08001879 if (!profile->canOpenNewIo()) {
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001880 for (size_t i = 0; i < mInputs.size(); ) {
1881 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1882 if (desc->mProfile != profile) {
1883 continue;
1884 }
1885 // if sound trigger, reuse input if used by other sound trigger on same session
1886 // else
1887 // reuse input if active client app is not in IDLE state
1888 //
1889 RecordClientVector clients = desc->clientsList();
1890 bool doClose = false;
1891 for (const auto& client : clients) {
1892 if (isSoundTrigger != client->isSoundTrigger()) {
1893 continue;
1894 }
1895 if (client->isSoundTrigger()) {
1896 if (session == client->session()) {
1897 return desc->mIoHandle;
1898 }
1899 continue;
1900 }
1901 if (client->active() && client->appState() != APP_STATE_IDLE) {
1902 return desc->mIoHandle;
1903 }
1904 doClose = true;
1905 }
1906 if (doClose) {
1907 closeInput(desc->mIoHandle);
1908 } else {
1909 i++;
1910 }
1911 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001912 }
1913
Eric Laurentfe231122017-11-17 17:48:06 -08001914 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001915
Eric Laurentfe231122017-11-17 17:48:06 -08001916 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1917 lConfig.sample_rate = profileSamplingRate;
1918 lConfig.channel_mask = profileChannelMask;
1919 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001920
Eric Laurent53b810e2017-12-10 17:25:10 -08001921 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001922 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001923 // the inputs vector must be of size >= 1, but we don't want to crash here
1924 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1925 }
1926
Eric Laurentfe231122017-11-17 17:48:06 -08001927 status_t status = inputDesc->open(&lConfig, device, address,
1928 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001929
1930 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001931 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001932 (profileSamplingRate != lConfig.sample_rate) ||
1933 !audio_formats_match(profileFormat, lConfig.format) ||
1934 (profileChannelMask != lConfig.channel_mask)) {
1935 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001936 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001937 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001938 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001939 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001940 }
Eric Laurent599c7582015-12-07 18:05:55 -08001941 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001942 }
1943
Eric Laurentc722f302014-12-10 11:21:49 -08001944 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001945
Eric Laurent599c7582015-12-07 18:05:55 -08001946 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001947 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001948
Eric Laurent599c7582015-12-07 18:05:55 -08001949 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001950}
1951
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001952status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08001953{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001954 ALOGV("%s portId %d", __FUNCTION__, portId);
1955
1956 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1957 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001958 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959 return BAD_VALUE;
1960 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001962 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001963 if (client->active()) {
1964 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1965 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001966 }
1967
Eric Laurent8f42ea12018-08-08 09:08:25 -07001968 audio_session_t session = client->session();
1969
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001970 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001971
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001972 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001973
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001974 status_t status = inputDesc->start();
1975 if (status != NO_ERROR) {
1976 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07001977 }
Eric Laurente552edb2014-03-10 17:42:56 -07001978
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001979 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08001980 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07001981 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08001982
Eric Laurent8f42ea12018-08-08 09:08:25 -07001983 // indicate active capture to sound trigger service if starting capture from a mic on
1984 // primary HW module
1985 audio_devices_t device = getNewInputDevice(inputDesc);
1986 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001987
Eric Laurent8f42ea12018-08-08 09:08:25 -07001988 if (inputDesc->activeCount() == 1) {
1989 // if input maps to a dynamic policy with an activity listener, notify of state change
1990 if ((inputDesc->mPolicyMix != NULL)
1991 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1992 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1993 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08001994 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001995
Eric Laurent8f42ea12018-08-08 09:08:25 -07001996 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1997 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1998 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
1999 SoundTrigger::setCaptureState(true);
2000 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002001
Eric Laurent8f42ea12018-08-08 09:08:25 -07002002 // automatically enable the remote submix output when input is started if not
2003 // used by a policy mix of type MIX_TYPE_RECORDERS
2004 // For remote submix (a virtual device), we open only one input per capture request.
2005 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2006 String8 address = String8("");
2007 if (inputDesc->mPolicyMix == NULL) {
2008 address = String8("0");
2009 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2010 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002011 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002012 if (address != "") {
2013 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2014 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2015 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002016 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002017 }
Eric Laurente552edb2014-03-10 17:42:56 -07002018 }
2019
Eric Laurent8f42ea12018-08-08 09:08:25 -07002020 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurente552edb2014-03-10 17:42:56 -07002022 return NO_ERROR;
2023}
2024
Eric Laurent8fc147b2018-07-22 19:13:55 -07002025status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002026{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002027 ALOGV("%s portId %d", __FUNCTION__, portId);
2028
2029 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2030 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002031 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002032 return BAD_VALUE;
2033 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002034 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002035 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036 if (!client->active()) {
2037 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002038 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002039 }
2040
Eric Laurent8f42ea12018-08-08 09:08:25 -07002041 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002042
Eric Laurent8f42ea12018-08-08 09:08:25 -07002043 inputDesc->stop();
2044 if (inputDesc->isActive()) {
2045 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2046 } else {
2047 // if input maps to a dynamic policy with an activity listener, notify of state change
2048 if ((inputDesc->mPolicyMix != NULL)
2049 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2050 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2051 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002052 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002053
2054 // automatically disable the remote submix output when input is stopped if not
2055 // used by a policy mix of type MIX_TYPE_RECORDERS
2056 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2057 String8 address = String8("");
2058 if (inputDesc->mPolicyMix == NULL) {
2059 address = String8("0");
2060 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2061 address = inputDesc->mPolicyMix->mDeviceAddress;
2062 }
2063 if (address != "") {
2064 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2065 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2066 address, "remote-submix");
2067 }
2068 }
2069
2070 audio_devices_t device = inputDesc->mDevice;
2071 resetInputDevice(input);
2072
2073 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2074 // primary HW module
2075 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2076 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2077 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2078 SoundTrigger::setCaptureState(false);
2079 }
2080 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002081 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002082 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002083}
2084
Eric Laurent8fc147b2018-07-22 19:13:55 -07002085void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002086{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002087 ALOGV("%s portId %d", __FUNCTION__, portId);
2088
2089 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2090 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002091 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002092 return;
2093 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002094 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 audio_io_handle_t input = inputDesc->mIoHandle;
2096
Eric Laurent8f42ea12018-08-08 09:08:25 -07002097 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002098
Andy Hung39efb7a2018-09-26 15:39:28 -07002099 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002100
Andy Hung39efb7a2018-09-26 15:39:28 -07002101 if (inputDesc->getClientCount() > 0) {
2102 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002103 return;
2104 }
2105
Eric Laurent05b90f82014-08-27 15:32:29 -07002106 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002107 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002108 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002109}
2110
Eric Laurent8f42ea12018-08-08 09:08:25 -07002111void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002112{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002113 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002114
2115 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002116 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002117 }
2118}
2119
Eric Laurent8f42ea12018-08-08 09:08:25 -07002120void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2121{
2122 stopInput(portId);
2123 releaseInput(portId);
2124}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125
Eric Laurentd4692962014-05-05 18:13:44 -07002126void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002127 bool patchRemoved = false;
2128
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002129 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002130 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002131 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002132 if (patch_index >= 0) {
2133 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002134 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002135 mAudioPatches.removeItemsAt(patch_index);
2136 patchRemoved = true;
2137 }
Eric Laurentfe231122017-11-17 17:48:06 -08002138 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002139 }
2140 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002141 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002142 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002143
2144 if (patchRemoved) {
2145 mpClientInterface->onAudioPatchListUpdate();
2146 }
Eric Laurentd4692962014-05-05 18:13:44 -07002147}
2148
Eric Laurente0720872014-03-11 09:30:41 -07002149void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002150 int indexMin,
2151 int indexMax)
2152{
2153 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002154 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002155
2156 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002157 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2158 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002159 continue;
2160 }
2161 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002162 }
Eric Laurente552edb2014-03-10 17:42:56 -07002163}
2164
Eric Laurente0720872014-03-11 09:30:41 -07002165status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002166 int index,
2167 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002168{
2169
Nadav Bar7c605f62017-12-25 00:01:52 +02002170 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2171 // app that has MODIFY_PHONE_STATE permission.
2172 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2173 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002174 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002175 return BAD_VALUE;
2176 }
2177 if (!audio_is_output_device(device)) {
2178 return BAD_VALUE;
2179 }
2180
2181 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002182 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002183
Eric Laurent1fd372e2016-04-06 14:23:53 -07002184 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002185 stream, device, index);
2186
Eric Laurent28d09f02016-03-08 10:43:05 -08002187 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002188 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2189 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002190 continue;
2191 }
2192 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2193 }
Eric Laurente552edb2014-03-10 17:42:56 -07002194
Eric Laurent1fd372e2016-04-06 14:23:53 -07002195 // update volume on all outputs and streams matching the following:
2196 // - The requested stream (or a stream matching for volume control) is active on the output
2197 // - The device (or devices) selected by the strategy corresponding to this stream includes
2198 // the requested device
2199 // - For non default requested device, currently selected device on the output is either the
2200 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002201 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2202 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002203 status_t status = NO_ERROR;
2204 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002205 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2206 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002207 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002208 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002209 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002210 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002211 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002212 continue;
2213 }
Eric Laurent794fde22016-03-11 09:50:45 -08002214 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002215 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2216 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002217 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2218 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002219 continue;
2220 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002221 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002222 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002223 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002224 applyVolume = (curDevice & curStreamDevice) != 0;
2225 } else {
2226 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002227 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002228 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002229 // rescale index before applying to curStream as ranges may be different for
2230 // stream and curStream
2231 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002232 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002233 //FIXME: workaround for truncated touch sounds
2234 // delayed volume change for system stream to be removed when the problem is
2235 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002236 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002237 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002238 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002239 if (volStatus != NO_ERROR) {
2240 status = volStatus;
2241 }
2242 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002243 }
Eric Laurente552edb2014-03-10 17:42:56 -07002244 }
2245 return status;
2246}
2247
Eric Laurente0720872014-03-11 09:30:41 -07002248status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002249 int *index,
2250 audio_devices_t device)
2251{
2252 if (index == NULL) {
2253 return BAD_VALUE;
2254 }
2255 if (!audio_is_output_device(device)) {
2256 return BAD_VALUE;
2257 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002258 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002259 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002260 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002261 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2262 }
François Gaffiedfd74092015-03-19 12:10:59 +01002263 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002264
François Gaffied1ab2bd2015-12-02 18:20:06 +01002265 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002266 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2267 return NO_ERROR;
2268}
2269
Eric Laurent36829f92017-04-07 19:04:42 -07002270audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002271{
2272 // select one output among several suitable for global effects.
2273 // The priority is as follows:
2274 // 1: An offloaded output. If the effect ends up not being offloadable,
2275 // AudioFlinger will invalidate the track and the offloaded output
2276 // will be closed causing the effect to be moved to a PCM output.
2277 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002278 // 3: The primary output
2279 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002280
Eric Laurent3b73df72014-03-11 09:06:29 -07002281 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002282 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002283 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002284
Eric Laurent36829f92017-04-07 19:04:42 -07002285 if (outputs.size() == 0) {
2286 return AUDIO_IO_HANDLE_NONE;
2287 }
Eric Laurente552edb2014-03-10 17:42:56 -07002288
Eric Laurent36829f92017-04-07 19:04:42 -07002289 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2290 bool activeOnly = true;
2291
2292 while (output == AUDIO_IO_HANDLE_NONE) {
2293 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2294 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2295 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2296
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002297 for (audio_io_handle_t output : outputs) {
2298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002299 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2300 continue;
2301 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002302 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2303 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002304 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002305 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002306 }
2307 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002308 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002309 }
2310 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002311 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002312 }
2313 }
2314 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2315 output = outputOffloaded;
2316 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2317 output = outputDeepBuffer;
2318 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2319 output = outputPrimary;
2320 } else {
2321 output = outputs[0];
2322 }
2323 activeOnly = false;
2324 }
2325
2326 if (output != mMusicEffectOutput) {
2327 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2328 mMusicEffectOutput = output;
2329 }
2330
2331 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 return output;
2333}
2334
Eric Laurent36829f92017-04-07 19:04:42 -07002335audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2336{
2337 return selectOutputForMusicEffects();
2338}
2339
Eric Laurente0720872014-03-11 09:30:41 -07002340status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002341 audio_io_handle_t io,
2342 uint32_t strategy,
2343 int session,
2344 int id)
2345{
2346 ssize_t index = mOutputs.indexOfKey(io);
2347 if (index < 0) {
2348 index = mInputs.indexOfKey(io);
2349 if (index < 0) {
2350 ALOGW("registerEffect() unknown io %d", io);
2351 return INVALID_OPERATION;
2352 }
2353 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002354 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002355}
2356
Eric Laurentc75307b2015-03-17 15:29:32 -07002357bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2358{
Eric Laurent28d09f02016-03-08 10:43:05 -08002359 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002360 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2361 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002362 continue;
2363 }
2364 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2365 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002366 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002367}
2368
2369bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2370{
2371 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2372}
2373
Eric Laurente0720872014-03-11 09:30:41 -07002374bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002375{
2376 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002377 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002378 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002379 return true;
2380 }
2381 }
2382 return false;
2383}
2384
Eric Laurent275e8e92014-11-30 15:14:47 -08002385// Register a list of custom mixes with their attributes and format.
2386// When a mix is registered, corresponding input and output profiles are
2387// added to the remote submix hw module. The profile contains only the
2388// parameters (sampling rate, format...) specified by the mix.
2389// The corresponding input remote submix device is also connected.
2390//
2391// When a remote submix device is connected, the address is checked to select the
2392// appropriate profile and the corresponding input or output stream is opened.
2393//
2394// When capture starts, getInputForAttr() will:
2395// - 1 look for a mix matching the address passed in attribtutes tags if any
2396// - 2 if none found, getDeviceForInputSource() will:
2397// - 2.1 look for a mix matching the attributes source
2398// - 2.2 if none found, default to device selection by policy rules
2399// At this time, the corresponding output remote submix device is also connected
2400// and active playback use cases can be transferred to this mix if needed when reconnecting
2401// after AudioTracks are invalidated
2402//
2403// When playback starts, getOutputForAttr() will:
2404// - 1 look for a mix matching the address passed in attribtutes tags if any
2405// - 2 if none found, look for a mix matching the attributes usage
2406// - 3 if none found, default to device and output selection by policy rules.
2407
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002408status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002409{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002410 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2411 status_t res = NO_ERROR;
2412
2413 sp<HwModule> rSubmixModule;
2414 // examine each mix's route type
2415 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002417 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002418 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002419 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002420 break;
2421 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002422 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002423 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002424 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002425 rSubmixModule = mHwModules.getModuleFromName(
2426 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2427 if (rSubmixModule == 0) {
2428 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2429 i);
2430 res = INVALID_OPERATION;
2431 break;
2432 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002433 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002434
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 String8 address = mix.mDeviceAddress;
2436 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2437 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2438 } else {
2439 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2440 }
François Gaffie036e1e92015-03-19 10:16:24 +01002441
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002443 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002444 res = INVALID_OPERATION;
2445 break;
2446 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 audio_config_t outputConfig = mix.mFormat;
2448 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002449 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2450 // stereo and let audio flinger do the channel conversion if needed.
2451 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2452 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2453 rSubmixModule->addOutputProfile(address, &outputConfig,
2454 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2455 rSubmixModule->addInputProfile(address, &inputConfig,
2456 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002457
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002459 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2460 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2461 address.string(), "remote-submix");
2462 } else {
2463 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2464 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2465 address.string(), "remote-submix");
2466 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002467 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2468 String8 address = mix.mDeviceAddress;
2469 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002470 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2471 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002473 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2475 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2476 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2477 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2478 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2479 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002480 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2481 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002482 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002483 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002484 } else {
2485 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 }
2487 break;
2488 }
2489 }
2490
2491 if (res != NO_ERROR) {
2492 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002493 i, device, address.string());
2494 res = INVALID_OPERATION;
2495 break;
2496 } else if (!foundOutput) {
2497 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2498 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 res = INVALID_OPERATION;
2500 break;
2501 }
Eric Laurentc722f302014-12-10 11:21:49 -08002502 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002503 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002504 if (res != NO_ERROR) {
2505 unregisterPolicyMixes(mixes);
2506 }
2507 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002508}
2509
2510status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2511{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002512 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002513 status_t res = NO_ERROR;
2514 sp<HwModule> rSubmixModule;
2515 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002516 for (const auto& mix : mixes) {
2517 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002518
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002520 rSubmixModule = mHwModules.getModuleFromName(
2521 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2522 if (rSubmixModule == 0) {
2523 res = INVALID_OPERATION;
2524 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 }
2526 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002527
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002528 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002529
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2531 res = INVALID_OPERATION;
2532 continue;
2533 }
2534
2535 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2536 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2537 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2538 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2539 address.string(), "remote-submix");
2540 }
2541 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2542 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2543 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2544 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2545 address.string(), "remote-submix");
2546 }
2547 rSubmixModule->removeOutputProfile(address);
2548 rSubmixModule->removeInputProfile(address);
2549
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002550 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2551 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 res = INVALID_OPERATION;
2553 continue;
2554 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002555 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002556 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002558}
2559
Andy Hungc29d82b2018-10-05 12:23:17 -07002560void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002561{
Andy Hungc29d82b2018-10-05 12:23:17 -07002562 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2563 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002564 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002565 std::string stateLiteral;
2566 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002567 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002568 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2569 "communications", "media", "record", "dock", "system",
2570 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2571 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2572 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002573 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002574 forceUses[i], mEngine->getForceUse(i));
2575 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002576 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2577 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2578 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2579 mAvailableOutputDevices.dump(dst, String8("Available output"));
2580 mAvailableInputDevices.dump(dst, String8("Available input"));
2581 mHwModulesAll.dump(dst);
2582 mOutputs.dump(dst);
2583 mInputs.dump(dst);
2584 mVolumeCurves->dump(dst);
2585 mEffects.dump(dst);
2586 mAudioPatches.dump(dst);
2587 mPolicyMixes.dump(dst);
2588 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002589 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002590 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002591 size_t i = 0;
2592 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002593 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002594 std::string sfmt;
2595 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002596 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002597 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002598 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002599 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002600}
2601
2602status_t AudioPolicyManager::dump(int fd)
2603{
2604 String8 result;
2605 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002606 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002607 return NO_ERROR;
2608}
2609
2610// This function checks for the parameters which can be offloaded.
2611// This can be enhanced depending on the capability of the DSP and policy
2612// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002613bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002614{
2615 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002616 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002617 offloadInfo.sample_rate, offloadInfo.channel_mask,
2618 offloadInfo.format,
2619 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2620 offloadInfo.has_video);
2621
Andy Hung2ddee192015-12-18 17:34:44 -08002622 if (mMasterMono) {
2623 return false; // no offloading if mono is set.
2624 }
2625
Eric Laurente552edb2014-03-10 17:42:56 -07002626 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002627 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2628 ALOGV("offload disabled by audio.offload.disable");
2629 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002630 }
2631
2632 // Check if stream type is music, then only allow offload as of now.
2633 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2634 {
2635 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2636 return false;
2637 }
2638
2639 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002640 const bool allowOffloadWithVideo =
2641 property_get_bool("audio.offload.video", false /* default_value */);
2642 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002643 ALOGV("isOffloadSupported: has_video == true, returning false");
2644 return false;
2645 }
2646
2647 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002648 const int min_duration_secs = property_get_int32(
2649 "audio.offload.min.duration.secs", -1 /* default_value */);
2650 if (min_duration_secs >= 0) {
2651 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2652 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2653 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 return false;
2655 }
2656 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2657 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2658 return false;
2659 }
2660
2661 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2662 // creating an offloaded track and tearing it down immediately after start when audioflinger
2663 // detects there is an active non offloadable effect.
2664 // FIXME: We should check the audio session here but we do not have it in this context.
2665 // This may prevent offloading in rare situations where effects are left active by apps
2666 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002667 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002668 return false;
2669 }
2670
2671 // See if there is a profile to support this.
2672 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002673 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002674 offloadInfo.sample_rate,
2675 offloadInfo.format,
2676 offloadInfo.channel_mask,
2677 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002678 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2679 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002680}
2681
Eric Laurent6a94d692014-05-20 11:18:06 -07002682status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2683 audio_port_type_t type,
2684 unsigned int *num_ports,
2685 struct audio_port *ports,
2686 unsigned int *generation)
2687{
2688 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2689 generation == NULL) {
2690 return BAD_VALUE;
2691 }
2692 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2693 if (ports == NULL) {
2694 *num_ports = 0;
2695 }
2696
2697 size_t portsWritten = 0;
2698 size_t portsMax = *num_ports;
2699 *num_ports = 0;
2700 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002701 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2702 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002703 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002704 for (const auto& dev : mAvailableOutputDevices) {
2705 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002706 continue;
2707 }
2708 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002709 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002710 }
2711 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002712 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002713 }
2714 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002715 for (const auto& dev : mAvailableInputDevices) {
2716 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002717 continue;
2718 }
2719 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002720 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002721 }
2722 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002723 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002724 }
2725 }
2726 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2727 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2728 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2729 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2730 }
2731 *num_ports += mInputs.size();
2732 }
2733 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002734 size_t numOutputs = 0;
2735 for (size_t i = 0; i < mOutputs.size(); i++) {
2736 if (!mOutputs[i]->isDuplicated()) {
2737 numOutputs++;
2738 if (portsWritten < portsMax) {
2739 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2740 }
2741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002742 }
Eric Laurent84c70242014-06-23 08:46:27 -07002743 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002744 }
2745 }
2746 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002747 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 return NO_ERROR;
2749}
2750
Eric Laurent99fcae42018-05-17 16:59:18 -07002751status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002752{
Eric Laurent99fcae42018-05-17 16:59:18 -07002753 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2754 return BAD_VALUE;
2755 }
2756 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2757 if (dev != 0) {
2758 dev->toAudioPort(port);
2759 return NO_ERROR;
2760 }
2761 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2762 if (dev != 0) {
2763 dev->toAudioPort(port);
2764 return NO_ERROR;
2765 }
2766 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2767 if (out != 0) {
2768 out->toAudioPort(port);
2769 return NO_ERROR;
2770 }
2771 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2772 if (in != 0) {
2773 in->toAudioPort(port);
2774 return NO_ERROR;
2775 }
2776 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002777}
2778
Eric Laurent6a94d692014-05-20 11:18:06 -07002779status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2780 audio_patch_handle_t *handle,
2781 uid_t uid)
2782{
2783 ALOGV("createAudioPatch()");
2784
2785 if (handle == NULL || patch == NULL) {
2786 return BAD_VALUE;
2787 }
2788 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2789
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002790 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002791 return BAD_VALUE;
2792 }
2793 // only one source per audio patch supported for now
2794 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002795 return INVALID_OPERATION;
2796 }
Eric Laurent874c42872014-08-08 15:13:39 -07002797
2798 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002799 return INVALID_OPERATION;
2800 }
Eric Laurent874c42872014-08-08 15:13:39 -07002801 for (size_t i = 0; i < patch->num_sinks; i++) {
2802 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2803 return INVALID_OPERATION;
2804 }
2805 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002806
2807 sp<AudioPatch> patchDesc;
2808 ssize_t index = mAudioPatches.indexOfKey(*handle);
2809
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2811 patch->sources[0].role,
2812 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002813#if LOG_NDEBUG == 0
2814 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002815 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002816 patch->sinks[i].role,
2817 patch->sinks[i].type);
2818 }
2819#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002820
2821 if (index >= 0) {
2822 patchDesc = mAudioPatches.valueAt(index);
2823 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2824 mUidCached, patchDesc->mUid, uid);
2825 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2826 return INVALID_OPERATION;
2827 }
2828 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002829 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002830 }
2831
2832 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002833 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 if (outputDesc == NULL) {
2835 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2836 return BAD_VALUE;
2837 }
Eric Laurent84c70242014-06-23 08:46:27 -07002838 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2839 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002840 if (patchDesc != 0) {
2841 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2842 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2843 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2844 return BAD_VALUE;
2845 }
2846 }
Eric Laurent874c42872014-08-08 15:13:39 -07002847 DeviceVector devices;
2848 for (size_t i = 0; i < patch->num_sinks; i++) {
2849 // Only support mix to devices connection
2850 // TODO add support for mix to mix connection
2851 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2852 ALOGV("createAudioPatch() source mix but sink is not a device");
2853 return INVALID_OPERATION;
2854 }
2855 sp<DeviceDescriptor> devDesc =
2856 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2857 if (devDesc == 0) {
2858 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2859 return BAD_VALUE;
2860 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002861
François Gaffie53615e22015-03-19 09:24:12 +01002862 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002863 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002864 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002865 NULL, // updatedSamplingRate
2866 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002867 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002868 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002869 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002870 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002871 ALOGV("createAudioPatch() profile not supported for device %08x",
2872 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002873 return INVALID_OPERATION;
2874 }
2875 devices.add(devDesc);
2876 }
2877 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 return INVALID_OPERATION;
2879 }
Eric Laurent874c42872014-08-08 15:13:39 -07002880
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 // TODO: reconfigure output format and channels here
2882 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002883 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002884 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002885 index = mAudioPatches.indexOfKey(*handle);
2886 if (index >= 0) {
2887 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2888 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2889 }
2890 patchDesc = mAudioPatches.valueAt(index);
2891 patchDesc->mUid = uid;
2892 ALOGV("createAudioPatch() success");
2893 } else {
2894 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2895 return INVALID_OPERATION;
2896 }
2897 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2898 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2899 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002900 // only one sink supported when connecting an input device to a mix
2901 if (patch->num_sinks > 1) {
2902 return INVALID_OPERATION;
2903 }
François Gaffie53615e22015-03-19 09:24:12 +01002904 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002905 if (inputDesc == NULL) {
2906 return BAD_VALUE;
2907 }
2908 if (patchDesc != 0) {
2909 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2910 return BAD_VALUE;
2911 }
2912 }
2913 sp<DeviceDescriptor> devDesc =
2914 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2915 if (devDesc == 0) {
2916 return BAD_VALUE;
2917 }
2918
François Gaffie53615e22015-03-19 09:24:12 +01002919 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002920 devDesc->mAddress,
2921 patch->sinks[0].sample_rate,
2922 NULL, /*updatedSampleRate*/
2923 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002924 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002925 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002926 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002927 // FIXME for the parameter type,
2928 // and the NONE
2929 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002930 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002931 return INVALID_OPERATION;
2932 }
2933 // TODO: reconfigure output format and channels here
2934 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002935 devDesc->type(), inputDesc->mIoHandle);
2936 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002937 index = mAudioPatches.indexOfKey(*handle);
2938 if (index >= 0) {
2939 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2940 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2941 }
2942 patchDesc = mAudioPatches.valueAt(index);
2943 patchDesc->mUid = uid;
2944 ALOGV("createAudioPatch() success");
2945 } else {
2946 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2947 return INVALID_OPERATION;
2948 }
2949 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2950 // device to device connection
2951 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002952 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002953 return BAD_VALUE;
2954 }
2955 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002956 sp<DeviceDescriptor> srcDeviceDesc =
2957 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002958 if (srcDeviceDesc == 0) {
2959 return BAD_VALUE;
2960 }
Eric Laurent874c42872014-08-08 15:13:39 -07002961
Eric Laurent6a94d692014-05-20 11:18:06 -07002962 //update source and sink with our own data as the data passed in the patch may
2963 // be incomplete.
2964 struct audio_patch newPatch = *patch;
2965 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002966
Eric Laurent874c42872014-08-08 15:13:39 -07002967 for (size_t i = 0; i < patch->num_sinks; i++) {
2968 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2969 ALOGV("createAudioPatch() source device but one sink is not a device");
2970 return INVALID_OPERATION;
2971 }
2972
2973 sp<DeviceDescriptor> sinkDeviceDesc =
2974 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2975 if (sinkDeviceDesc == 0) {
2976 return BAD_VALUE;
2977 }
2978 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2979
Eric Laurent3bcf8592015-04-03 12:13:24 -07002980 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002981 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07002982 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002983 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002984 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002985 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002986 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002987 return INVALID_OPERATION;
2988 }
Eric Laurent874c42872014-08-08 15:13:39 -07002989 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002990 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002991 // if the sink device is reachable via an opened output stream, request to go via
2992 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002993 audio_io_handle_t output = selectOutput(outputs,
2994 AUDIO_OUTPUT_FLAG_NONE,
2995 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002996 if (output != AUDIO_IO_HANDLE_NONE) {
2997 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2998 if (outputDesc->isDuplicated()) {
2999 return INVALID_OPERATION;
3000 }
3001 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003002 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003003 newPatch.num_sources = 2;
3004 }
Eric Laurent83b88082014-06-20 18:31:16 -07003005 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 }
3007 // TODO: check from routing capabilities in config file and other conflicting patches
3008
Mikhail Naganovdc769682018-05-04 15:34:08 -07003009 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3010 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3012 status);
3013 return INVALID_OPERATION;
3014 }
3015 } else {
3016 return BAD_VALUE;
3017 }
3018 } else {
3019 return BAD_VALUE;
3020 }
3021 return NO_ERROR;
3022}
3023
3024status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3025 uid_t uid)
3026{
3027 ALOGV("releaseAudioPatch() patch %d", handle);
3028
3029 ssize_t index = mAudioPatches.indexOfKey(handle);
3030
3031 if (index < 0) {
3032 return BAD_VALUE;
3033 }
3034 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3035 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3036 mUidCached, patchDesc->mUid, uid);
3037 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3038 return INVALID_OPERATION;
3039 }
3040
3041 struct audio_patch *patch = &patchDesc->mPatch;
3042 patchDesc->mUid = mUidCached;
3043 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003044 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 if (outputDesc == NULL) {
3046 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3047 return BAD_VALUE;
3048 }
3049
Eric Laurentc75307b2015-03-17 15:29:32 -07003050 setOutputDevice(outputDesc,
3051 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003052 true,
3053 0,
3054 NULL);
3055 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3056 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003057 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003058 if (inputDesc == NULL) {
3059 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3060 return BAD_VALUE;
3061 }
3062 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003063 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003064 true,
3065 NULL);
3066 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003067 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3068 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3069 status, patchDesc->mAfPatchHandle);
3070 removeAudioPatch(patchDesc->mHandle);
3071 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003072 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 } else {
3074 return BAD_VALUE;
3075 }
3076 } else {
3077 return BAD_VALUE;
3078 }
3079 return NO_ERROR;
3080}
3081
3082status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3083 struct audio_patch *patches,
3084 unsigned int *generation)
3085{
François Gaffie53615e22015-03-19 09:24:12 +01003086 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003087 return BAD_VALUE;
3088 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003089 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003090 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003091}
3092
Eric Laurente1715a42014-05-20 11:30:42 -07003093status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003094{
Eric Laurente1715a42014-05-20 11:30:42 -07003095 ALOGV("setAudioPortConfig()");
3096
3097 if (config == NULL) {
3098 return BAD_VALUE;
3099 }
3100 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3101 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003102 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3103 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003104 }
3105
Eric Laurenta121f902014-06-03 13:32:54 -07003106 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003107 if (config->type == AUDIO_PORT_TYPE_MIX) {
3108 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003110 if (outputDesc == NULL) {
3111 return BAD_VALUE;
3112 }
Eric Laurent84c70242014-06-23 08:46:27 -07003113 ALOG_ASSERT(!outputDesc->isDuplicated(),
3114 "setAudioPortConfig() called on duplicated output %d",
3115 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003116 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003117 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003118 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003119 if (inputDesc == NULL) {
3120 return BAD_VALUE;
3121 }
Eric Laurenta121f902014-06-03 13:32:54 -07003122 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003123 } else {
3124 return BAD_VALUE;
3125 }
3126 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3127 sp<DeviceDescriptor> deviceDesc;
3128 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3129 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3130 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3131 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3132 } else {
3133 return BAD_VALUE;
3134 }
3135 if (deviceDesc == NULL) {
3136 return BAD_VALUE;
3137 }
Eric Laurenta121f902014-06-03 13:32:54 -07003138 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003139 } else {
3140 return BAD_VALUE;
3141 }
3142
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003143 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003144 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3145 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003146 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003147 audioPortConfig->toAudioPortConfig(&newConfig, config);
3148 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003149 }
Eric Laurenta121f902014-06-03 13:32:54 -07003150 if (status != NO_ERROR) {
3151 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003152 }
Eric Laurente1715a42014-05-20 11:30:42 -07003153
3154 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003155}
3156
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003157void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3158{
Eric Laurentd60560a2015-04-10 11:31:20 -07003159 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003160 clearAudioPatches(uid);
3161 clearSessionRoutes(uid);
3162}
3163
Eric Laurent6a94d692014-05-20 11:18:06 -07003164void AudioPolicyManager::clearAudioPatches(uid_t uid)
3165{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003166 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3168 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003169 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 }
3171 }
3172}
3173
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003174void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3175 audio_io_handle_t ouptutToSkip)
3176{
3177 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3178 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3179 for (size_t j = 0; j < mOutputs.size(); j++) {
3180 if (mOutputs.keyAt(j) == ouptutToSkip) {
3181 continue;
3182 }
3183 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3184 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3185 continue;
3186 }
3187 // If the default device for this strategy is on another output mix,
3188 // invalidate all tracks in this strategy to force re connection.
3189 // Otherwise select new device on the output mix.
3190 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003191 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003192 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3193 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3194 }
3195 }
3196 } else {
3197 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3198 setOutputDevice(outputDesc, newDevice, false);
3199 }
3200 }
3201}
3202
3203void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3204{
3205 // remove output routes associated with this uid
3206 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003207 for (size_t i = 0; i < mOutputs.size(); i++) {
3208 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003209 for (const auto& client : outputDesc->getClientIterable()) {
3210 if (client->hasPreferredDevice() && client->uid() == uid) {
3211 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3212 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003213 }
3214 }
3215 }
3216 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003217 for (const auto& strategy : affectedStrategies) {
3218 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003219 }
3220
3221 // remove input routes associated with this uid
3222 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003223 for (size_t i = 0; i < mInputs.size(); i++) {
3224 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003225 for (const auto& client : inputDesc->getClientIterable()) {
3226 if (client->hasPreferredDevice() && client->uid() == uid) {
3227 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3228 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003229 }
3230 }
3231 }
3232 // reroute inputs if necessary
3233 SortedVector<audio_io_handle_t> inputsToClose;
3234 for (size_t i = 0; i < mInputs.size(); i++) {
3235 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003236 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003237 inputsToClose.add(inputDesc->mIoHandle);
3238 }
3239 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003240 for (const auto& input : inputsToClose) {
3241 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003242 }
3243}
3244
Eric Laurentd60560a2015-04-10 11:31:20 -07003245void AudioPolicyManager::clearAudioSources(uid_t uid)
3246{
3247 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003248 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3249 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003250 stopAudioSource(mAudioSources.keyAt(i));
3251 }
3252 }
3253}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003254
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003255status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3256 audio_io_handle_t *ioHandle,
3257 audio_devices_t *device)
3258{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003259 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3260 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003261 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003262
François Gaffiedf372692015-03-19 10:43:27 +01003263 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003264}
3265
Eric Laurentd60560a2015-04-10 11:31:20 -07003266status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003267 const audio_attributes_t *attributes,
3268 audio_port_handle_t *portId,
3269 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003270{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003271 ALOGV("%s", __FUNCTION__);
3272 *portId = AUDIO_PORT_HANDLE_NONE;
3273
3274 if (source == NULL || attributes == NULL || portId == NULL) {
3275 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3276 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003277 return BAD_VALUE;
3278 }
3279
Eric Laurentd60560a2015-04-10 11:31:20 -07003280 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3281 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003282 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3283 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003284 return INVALID_OPERATION;
3285 }
3286
3287 sp<DeviceDescriptor> srcDeviceDesc =
3288 mAvailableInputDevices.getDevice(source->ext.device.type,
3289 String8(source->ext.device.address));
3290 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003291 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003292 return BAD_VALUE;
3293 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003294
3295 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003296
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003297 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003298 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003299
3300 sp<SourceClientDescriptor> sourceDesc =
3301 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003302 streamTypefromAttributesInt(attributes),
3303 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003304
3305 status_t status = connectAudioSource(sourceDesc);
3306 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003307 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003308 }
3309 return status;
3310}
3311
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003312status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003313{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003314 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003315
3316 // make sure we only have one patch per source.
3317 disconnectAudioSource(sourceDesc);
3318
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003319 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003320 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003321 audio_stream_type_t stream = sourceDesc->stream();
3322 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003323
3324 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3325 sp<DeviceDescriptor> sinkDeviceDesc =
3326 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3327
3328 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003329
3330 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3331 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003332 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003333 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3334 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3335 // create patch between src device and output device
3336 // create Hwoutput and add to mHwOutputs
3337 } else {
3338 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3339 audio_io_handle_t output =
3340 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3341 if (output == AUDIO_IO_HANDLE_NONE) {
3342 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3343 return INVALID_OPERATION;
3344 }
3345 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3346 if (outputDesc->isDuplicated()) {
3347 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3348 return INVALID_OPERATION;
3349 }
Eric Laurent733ce942017-12-07 12:18:25 -08003350 status_t status = outputDesc->start();
3351 if (status != NO_ERROR) {
3352 return status;
3353 }
3354
Eric Laurentd60560a2015-04-10 11:31:20 -07003355 // create a special patch with no sink and two sources:
3356 // - the second source indicates to PatchPanel through which output mix this patch should
3357 // be connected as well as the stream type for volume control
3358 // - the sink is defined by whatever output device is currently selected for the output
3359 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003360 PatchBuilder patchBuilder;
3361 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3362 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003363 &afPatchHandle,
3364 0);
3365 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3366 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003367 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003368 if (status != NO_ERROR) {
3369 ALOGW("%s patch panel could not connect device patch, error %d",
3370 __FUNCTION__, status);
3371 return INVALID_OPERATION;
3372 }
3373 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003374 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003375
3376 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003377 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003378 return status;
3379 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003380 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003381 if (delayMs != 0) {
3382 usleep(delayMs * 1000);
3383 }
3384 }
3385
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003386 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3387 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003388
3389 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003390}
3391
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003392status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003393{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003394 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3395 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003396 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003397 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003398 return BAD_VALUE;
3399 }
3400 status_t status = disconnectAudioSource(sourceDesc);
3401
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003402 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003403 return status;
3404}
3405
Andy Hung2ddee192015-12-18 17:34:44 -08003406status_t AudioPolicyManager::setMasterMono(bool mono)
3407{
3408 if (mMasterMono == mono) {
3409 return NO_ERROR;
3410 }
3411 mMasterMono = mono;
3412 // if enabling mono we close all offloaded devices, which will invalidate the
3413 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3414 // for recreating the new AudioTrack as non-offloaded PCM.
3415 //
3416 // If disabling mono, we leave all tracks as is: we don't know which clients
3417 // and tracks are able to be recreated as offloaded. The next "song" should
3418 // play back offloaded.
3419 if (mMasterMono) {
3420 Vector<audio_io_handle_t> offloaded;
3421 for (size_t i = 0; i < mOutputs.size(); ++i) {
3422 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3423 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3424 offloaded.push(desc->mIoHandle);
3425 }
3426 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003427 for (const auto& handle : offloaded) {
3428 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003429 }
3430 }
3431 // update master mono for all remaining outputs
3432 for (size_t i = 0; i < mOutputs.size(); ++i) {
3433 updateMono(mOutputs.keyAt(i));
3434 }
3435 return NO_ERROR;
3436}
3437
3438status_t AudioPolicyManager::getMasterMono(bool *mono)
3439{
3440 *mono = mMasterMono;
3441 return NO_ERROR;
3442}
3443
Eric Laurentac9cef52017-06-09 15:46:26 -07003444float AudioPolicyManager::getStreamVolumeDB(
3445 audio_stream_type_t stream, int index, audio_devices_t device)
3446{
3447 return computeVolume(stream, index, device);
3448}
3449
jiabin81772902018-04-02 17:52:27 -07003450status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3451 audio_format_t *surroundFormats,
3452 bool *surroundFormatsEnabled,
3453 bool reported)
3454{
3455 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3456 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3457 return BAD_VALUE;
3458 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003459 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3460 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003461
3462 // Only return value if there is HDMI output.
3463 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3464 return INVALID_OPERATION;
3465 }
3466
3467 size_t formatsWritten = 0;
3468 size_t formatsMax = *numSurroundFormats;
3469 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003470 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003471 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003472 // Return formats from HDMI profiles, that have already been resolved by
3473 // checkOutputsForDevice().
3474 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3475 AUDIO_DEVICE_OUT_HDMI);
3476 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3477 FormatVector supportedFormats =
3478 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3479 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003480 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003481 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003482 } else {
3483 for (const auto& pair : mConfig.getSurroundFormats()) {
3484 if (pair.second.count(supportedFormats[j]) != 0) {
3485 formats.insert(pair.first);
3486 break;
3487 }
3488 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003489 }
3490 }
jiabin81772902018-04-02 17:52:27 -07003491 }
3492 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003493 for (const auto& pair : mConfig.getSurroundFormats()) {
3494 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003495 }
3496 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003497 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003498 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003499 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003500 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003501 if (mConfig.getSurroundFormats().count(format) == 0) {
3502 // Check sub-formats
3503 for (const auto& pair : mConfig.getSurroundFormats()) {
3504 for (const auto& subformat : pair.second) {
3505 formatEnabled = mSurroundFormats.count(subformat) != 0;
3506 if (formatEnabled) break;
3507 }
3508 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003509 }
3510 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003511 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003512 }
3513 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3514 }
3515 (*numSurroundFormats)++;
3516 }
3517 return NO_ERROR;
3518}
3519
3520status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3521{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003522 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003523 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003524 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3525 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003526 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003527 return BAD_VALUE;
3528 }
3529
3530 // Should only be called when MANUAL.
3531 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3532 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3533 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003534 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003535 return INVALID_OPERATION;
3536 }
3537
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003538 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003539 return NO_ERROR;
3540 }
3541
3542 // The operation is valid only when there is HDMI output available.
3543 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003544 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003545 return INVALID_OPERATION;
3546 }
3547
Mikhail Naganov2563f232018-09-27 14:48:01 -07003548 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003549 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003550 mSurroundFormats.insert(audioFormat);
3551 for (const auto& subFormat : formatIter->second) {
3552 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003553 }
3554 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003555 mSurroundFormats.erase(audioFormat);
3556 for (const auto& subFormat : formatIter->second) {
3557 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003558 }
3559 }
3560
3561 sp<SwAudioOutputDescriptor> outputDesc;
3562 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003563 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003564 AUDIO_DEVICE_OUT_HDMI);
3565 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3566 // Simulate reconnection to update enabled surround sound formats.
3567 String8 address = hdmiOutputDevices[i]->mAddress;
3568 String8 name = hdmiOutputDevices[i]->getName();
3569 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3570 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3571 address.c_str(),
3572 name.c_str());
3573 if (status != NO_ERROR) {
3574 continue;
3575 }
3576 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3578 address.c_str(),
3579 name.c_str());
3580 profileUpdated |= (status == NO_ERROR);
3581 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003582 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003583 AUDIO_DEVICE_IN_HDMI);
3584 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3585 // Simulate reconnection to update enabled surround sound formats.
3586 String8 address = hdmiInputDevices[i]->mAddress;
3587 String8 name = hdmiInputDevices[i]->getName();
3588 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3589 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3590 address.c_str(),
3591 name.c_str());
3592 if (status != NO_ERROR) {
3593 continue;
3594 }
3595 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3597 address.c_str(),
3598 name.c_str());
3599 profileUpdated |= (status == NO_ERROR);
3600 }
3601
jiabin81772902018-04-02 17:52:27 -07003602 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003603 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003604 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003605 }
3606
3607 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3608}
3609
Eric Laurentf32108e2018-10-04 17:22:04 -07003610void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003611{
Eric Laurentf32108e2018-10-04 17:22:04 -07003612 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentf32108e2018-10-04 17:22:04 -07003613
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003614 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003615
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003616 for (size_t i = 0; i < activeInputs.size(); i++) {
3617 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003618 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3619 for (const auto& client : clients) {
3620 if (uid == client->uid()) {
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003621 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003622 }
3623 }
3624 }
3625}
3626
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003627status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003628{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003629 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003630
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003631 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003632 if (patchDesc == 0) {
3633 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003634 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003635 return BAD_VALUE;
3636 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003637 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003638
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003639 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003640 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003641 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003642 if (status == NO_ERROR) {
3643 swOutputDesc->stop();
3644 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003645 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3646 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003647 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003648 if (hwOutputDesc != 0) {
3649 // release patch between src device and output device
3650 // close Hwoutput and remove from mHwOutputs
3651 } else {
3652 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3653 }
3654 }
3655 return NO_ERROR;
3656}
3657
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003658sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003659 audio_io_handle_t output, routing_strategy strategy)
3660{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003661 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003662 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003663 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3664 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003665 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003666 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003667 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3668 source = sourceDesc;
3669 break;
3670 }
3671 }
3672 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003673}
3674
Eric Laurente552edb2014-03-10 17:42:56 -07003675// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003676// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003677// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003678uint32_t AudioPolicyManager::nextAudioPortGeneration()
3679{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003680 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003681}
3682
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003683// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3684static const char *kConfigLocationList[] =
3685 {"/odm/etc", "/vendor/etc", "/system/etc"};
3686static const int kConfigLocationListSize =
3687 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3688
3689static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3690 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003691 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003692 status_t ret;
3693
Petri Gyntherf497f292018-04-17 18:46:10 -07003694 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3695 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3696 // A2DP offload supported but disabled: try to use special XML file
3697 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3698 }
3699 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3700
3701 for (const char* fileName : fileNames) {
3702 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003703 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3704 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003705 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003706 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003707 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003708 return ret;
3709 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003710 }
3711 }
3712 return ret;
3713}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003714
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003715AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3716 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003717 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003718 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003719 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003720 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003721 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003722 mVolumeCurves(new VolumeCurvesCollection()),
3723 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003724 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003725 mAudioPortGeneration(1),
3726 mBeaconMuteRefCount(0),
3727 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003728 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003729 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003730 mMasterMono(false),
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003731 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003732{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003733}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003734
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003735AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3736 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3737{
3738 loadConfig();
3739 initialize();
3740}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003741
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003742// This check is to catch any legacy platform updating to Q without having
3743// switched to XML since its deprecation on O.
3744// TODO: after Q release, remove this check and flag as XML is now the only
3745// option and all legacy platform should have transitioned to XML.
3746#ifndef USE_XML_AUDIO_POLICY_CONF
3747#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003748#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003749
3750void AudioPolicyManager::loadConfig() {
3751 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003752 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003753 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003754 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003755}
3756
3757status_t AudioPolicyManager::initialize() {
3758 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003759
3760 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003761 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3762 if (!engineInstance) {
3763 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003764 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003765 }
3766 // Retrieve the Policy Manager Interface
3767 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3768 if (mEngine == NULL) {
3769 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003770 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003771 }
3772 mEngine->setObserver(this);
3773 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003774 if (status != NO_ERROR) {
3775 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3776 return status;
3777 }
François Gaffie2110e042015-03-24 08:41:51 +01003778
Eric Laurent3a4311c2014-03-17 12:00:47 -07003779 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003780 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003781 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3782 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003783 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003784 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003785 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3786 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003787 continue;
3788 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003789 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003790 // open all output streams needed to access attached devices
3791 // except for direct output streams that are only opened when they are actually
3792 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003793 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003794 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003795 if (!outProfile->canOpenNewIo()) {
3796 ALOGE("Invalid Output profile max open count %u for profile %s",
3797 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3798 continue;
3799 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003800 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003801 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003802 continue;
3803 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003804 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003805 mTtsOutputAvailable = true;
3806 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003807
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003808 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003809 continue;
3810 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003811 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003812 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3813 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003814 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003815 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003816 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003817 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003818 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003819 if ((profileType & outputDeviceTypes) == 0) {
3820 continue;
3821 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003822 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3823 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003824 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003825 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3826 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003827 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3828 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003829 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003830 status_t status = outputDesc->open(nullptr, profileType, address,
3831 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003832
3833 if (status != NO_ERROR) {
3834 ALOGW("Cannot open output stream for device %08x on hw module %s",
3835 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003836 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003837 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003838 for (const auto& dev : supportedDevices) {
3839 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003840 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003841 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003842 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003843 }
3844 }
3845 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003846 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003847 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003848 }
3849 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003850 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003851 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003852 true,
3853 0,
3854 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003855 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003856 }
Eric Laurente552edb2014-03-10 17:42:56 -07003857 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003858 // open input streams needed to access attached devices to validate
3859 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003860 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003861 if (!inProfile->canOpenNewIo()) {
3862 ALOGE("Invalid Input profile max open count %u for profile %s",
3863 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3864 continue;
3865 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003866 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003867 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003868 continue;
3869 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003870 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003871 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003872 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3873
Eric Laurentd78f1532014-09-16 16:38:20 -07003874 if ((profileType & inputDeviceTypes) == 0) {
3875 continue;
3876 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003877 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003878 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003879
Mikhail Naganov708e0382018-05-30 09:53:04 -07003880 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003881 // the inputs vector must be of size >= 1, but we don't want to crash here
3882 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3883 : String8("");
3884 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3885 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3886
Eric Laurentd78f1532014-09-16 16:38:20 -07003887 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003888 status_t status = inputDesc->open(nullptr,
3889 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003890 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003891 AUDIO_SOURCE_MIC,
3892 AUDIO_INPUT_FLAG_NONE,
3893 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003894
3895 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003896 for (const auto& dev : inProfile->getSupportedDevices()) {
3897 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003898 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003899 if (index >= 0) {
3900 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3901 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003902 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003903 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003904 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003905 }
3906 }
Eric Laurentfe231122017-11-17 17:48:06 -08003907 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003908 } else {
3909 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003910 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003911 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003912 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003913 }
3914 }
3915 // make sure all attached devices have been allocated a unique ID
3916 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003917 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003918 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003919 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3920 continue;
3921 }
François Gaffie2110e042015-03-24 08:41:51 +01003922 // The device is now validated and can be appended to the available devices of the engine
3923 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3924 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925 i++;
3926 }
3927 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003928 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003929 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3931 continue;
3932 }
François Gaffie2110e042015-03-24 08:41:51 +01003933 // The device is now validated and can be appended to the available devices of the engine
3934 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3935 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 i++;
3937 }
3938 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003939 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003940 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003941 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003942 }
jiabin9ff780e2018-03-19 18:19:52 -07003943 // If microphones address is empty, set it according to device type
3944 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
3945 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
3946 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
3947 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
3948 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
3949 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
3950 }
3951 }
3952 }
Eric Laurente552edb2014-03-10 17:42:56 -07003953
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003954 if (mPrimaryOutput == 0) {
3955 ALOGE("Failed to open primary output");
3956 status = NO_INIT;
3957 }
Eric Laurente552edb2014-03-10 17:42:56 -07003958
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09003959 // Silence ALOGV statements
3960 property_set("log.tag." LOG_TAG, "D");
3961
Eric Laurente552edb2014-03-10 17:42:56 -07003962 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003963 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003964}
3965
Eric Laurente0720872014-03-11 09:30:41 -07003966AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003967{
Eric Laurente552edb2014-03-10 17:42:56 -07003968 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003969 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003970 }
3971 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003972 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003973 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003974 mAvailableOutputDevices.clear();
3975 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003976 mOutputs.clear();
3977 mInputs.clear();
3978 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003979 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07003980 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003981}
3982
Eric Laurente0720872014-03-11 09:30:41 -07003983status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003984{
Eric Laurent87ffa392015-05-22 10:32:38 -07003985 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003986}
3987
Eric Laurente552edb2014-03-10 17:42:56 -07003988// ---
3989
Eric Laurent98e38192018-02-15 18:31:53 -08003990void AudioPolicyManager::addOutput(audio_io_handle_t output,
3991 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003992{
Eric Laurent1c333e22014-05-20 10:48:17 -07003993 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08003994 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08003995 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003996 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003998}
3999
François Gaffie53615e22015-03-19 09:24:12 +01004000void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4001{
4002 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004003 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004004}
4005
Eric Laurent98e38192018-02-15 18:31:53 -08004006void AudioPolicyManager::addInput(audio_io_handle_t input,
4007 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004008{
Eric Laurent1c333e22014-05-20 10:48:17 -07004009 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004010 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004011}
Eric Laurente552edb2014-03-10 17:42:56 -07004012
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004013void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004014 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004015 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004016 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004017 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004019 if (devDesc != 0) {
4020 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4021 desc->mIoHandle, address.string());
4022 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004023 }
4024}
4025
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004026status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004027 audio_policy_dev_state_t state,
4028 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004029 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004030{
François Gaffie53615e22015-03-19 09:24:12 +01004031 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004032 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004033
4034 if (audio_device_is_digital(device)) {
4035 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004036 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004037 }
Eric Laurente552edb2014-03-10 17:42:56 -07004038
Eric Laurent3b73df72014-03-11 09:06:29 -07004039 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004040 // first list already open outputs that can be routed to this device
4041 for (size_t i = 0; i < mOutputs.size(); i++) {
4042 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004043 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004044 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004045 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4046 outputs.add(mOutputs.keyAt(i));
4047 } else {
4048 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004049 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004050 }
Eric Laurente552edb2014-03-10 17:42:56 -07004051 }
4052 }
4053 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004054 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004055 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004056 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4057 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004058 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004059 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004060 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004061 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004062 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4063 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004064 }
Eric Laurente552edb2014-03-10 17:42:56 -07004065 }
4066 }
4067 }
4068
Eric Laurent7b279bb2015-12-14 10:18:23 -08004069 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004070
Eric Laurente552edb2014-03-10 17:42:56 -07004071 if (profiles.isEmpty() && outputs.isEmpty()) {
4072 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4073 return BAD_VALUE;
4074 }
4075
4076 // open outputs for matching profiles if needed. Direct outputs are also opened to
4077 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4078 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004079 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004080
4081 // nothing to do if one output is already opened for this profile
4082 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004083 for (j = 0; j < outputs.size(); j++) {
4084 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004085 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004086 // matching profile: save the sample rates, format and channel masks supported
4087 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004088 if (audio_device_is_digital(device)) {
4089 devDesc->importAudioPort(profile);
4090 }
Eric Laurente552edb2014-03-10 17:42:56 -07004091 break;
4092 }
4093 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004094 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004095 continue;
4096 }
4097
Eric Laurent3974e3b2017-12-07 17:58:43 -08004098 if (!profile->canOpenNewIo()) {
4099 ALOGW("Max Output number %u already opened for this profile %s",
4100 profile->maxOpenCount, profile->getTagName().c_str());
4101 continue;
4102 }
4103
Eric Laurent83efe1c2017-07-09 16:51:08 -07004104 ALOGV("opening output for device %08x with params %s profile %p name %s",
4105 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004106 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004107 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004108 status_t status = desc->open(nullptr, device, address,
4109 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004110
Eric Laurentfe231122017-11-17 17:48:06 -08004111 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004112 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004114 char *param = audio_device_address_to_parameter(device, address);
4115 mpClientInterface->setParameters(output, String8(param));
4116 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004117 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004118 updateAudioProfiles(devDesc, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004119 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004120 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004121 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004122 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004123 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004124 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004125 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004126 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4127 profile->pickAudioProfile(
4128 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004129 config.offload_info.sample_rate = config.sample_rate;
4130 config.offload_info.channel_mask = config.channel_mask;
4131 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004132
4133 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4134 AUDIO_OUTPUT_FLAG_NONE, &output);
4135 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004136 output = AUDIO_IO_HANDLE_NONE;
4137 }
Eric Laurentd4692962014-05-05 18:13:44 -07004138 }
4139
Eric Laurentcf2c0212014-07-25 16:20:43 -07004140 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004141 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004142 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004143 sp<AudioPolicyMix> policyMix;
4144 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004145 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4146 address.string());
4147 }
François Gaffie036e1e92015-03-19 10:16:24 +01004148 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004149 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004150
Eric Laurent87ffa392015-05-22 10:32:38 -07004151 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4152 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004153 // no duplicated output for direct outputs and
4154 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004155 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004156
Eric Laurentd4692962014-05-05 18:13:44 -07004157 //TODO: configure audio effect output stage here
4158
4159 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004160 sp<SwAudioOutputDescriptor> dupOutputDesc =
4161 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4162 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4163 &duplicatedOutput);
4164 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004165 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004166 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004167 } else {
4168 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004169 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004170 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004171 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004173 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004174 }
Eric Laurente552edb2014-03-10 17:42:56 -07004175 }
4176 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004177 } else {
4178 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004179 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004180 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004181 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004182 profiles.removeAt(profile_index);
4183 profile_index--;
4184 } else {
4185 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004186 // Load digital format info only for digital devices
4187 if (audio_device_is_digital(device)) {
4188 devDesc->importAudioPort(profile);
4189 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004190
François Gaffie53615e22015-03-19 09:24:12 +01004191 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004192 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4193 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004194 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004195 NULL/*patch handle*/, address.string());
4196 }
Eric Laurente552edb2014-03-10 17:42:56 -07004197 ALOGV("checkOutputsForDevice(): adding output %d", output);
4198 }
4199 }
4200
4201 if (profiles.isEmpty()) {
4202 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4203 return BAD_VALUE;
4204 }
Eric Laurentd4692962014-05-05 18:13:44 -07004205 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004206 // check if one opened output is not needed any more after disconnecting one device
4207 for (size_t i = 0; i < mOutputs.size(); i++) {
4208 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004209 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004210 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004211 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004212 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004213 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004214 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004215 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4216 mOutputs.keyAt(i));
4217 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004218 }
Eric Laurente552edb2014-03-10 17:42:56 -07004219 }
4220 }
Eric Laurentd4692962014-05-05 18:13:44 -07004221 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004222 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004223 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4224 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004225 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004226 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004227 "clearing direct output profile %zu on module %s",
4228 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004229 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004230 }
4231 }
4232 }
4233 }
4234 return NO_ERROR;
4235}
4236
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004237status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004238 audio_policy_dev_state_t state,
4239 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004240 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004241{
Paul McLean9080a4c2015-06-18 08:24:02 -07004242 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004243 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004244
4245 if (audio_device_is_digital(device)) {
4246 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004247 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004248 }
4249
Eric Laurentd4692962014-05-05 18:13:44 -07004250 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4251 // first list already open inputs that can be routed to this device
4252 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4253 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004254 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004255 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4256 inputs.add(mInputs.keyAt(input_index));
4257 }
4258 }
4259
4260 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004261 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004262 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004263 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004264 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004265 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004266 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004267
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004268 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004269 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004270 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004271 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004272 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4273 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004274 }
Eric Laurentd4692962014-05-05 18:13:44 -07004275 }
4276 }
4277 }
4278
4279 if (profiles.isEmpty() && inputs.isEmpty()) {
4280 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4281 return BAD_VALUE;
4282 }
4283
4284 // open inputs for matching profiles if needed. Direct inputs are also opened to
4285 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4286 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4287
Eric Laurent1c333e22014-05-20 10:48:17 -07004288 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004289
Eric Laurentd4692962014-05-05 18:13:44 -07004290 // nothing to do if one input is already opened for this profile
4291 size_t input_index;
4292 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4293 desc = mInputs.valueAt(input_index);
4294 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004295 if (audio_device_is_digital(device)) {
4296 devDesc->importAudioPort(profile);
4297 }
Eric Laurentd4692962014-05-05 18:13:44 -07004298 break;
4299 }
4300 }
4301 if (input_index != mInputs.size()) {
4302 continue;
4303 }
4304
Eric Laurent3974e3b2017-12-07 17:58:43 -08004305 if (!profile->canOpenNewIo()) {
4306 ALOGW("Max Input number %u already opened for this profile %s",
4307 profile->maxOpenCount, profile->getTagName().c_str());
4308 continue;
4309 }
4310
Eric Laurentfe231122017-11-17 17:48:06 -08004311 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004312 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004313 status_t status = desc->open(nullptr,
4314 device,
4315 address,
4316 AUDIO_SOURCE_MIC,
4317 AUDIO_INPUT_FLAG_NONE,
4318 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004319
Eric Laurentcf2c0212014-07-25 16:20:43 -07004320 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004321 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004322 char *param = audio_device_address_to_parameter(device, address);
4323 mpClientInterface->setParameters(input, String8(param));
4324 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004325 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08004326 updateAudioProfiles(devDesc, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004327 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004328 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004329 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004330 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004331 }
4332
4333 if (input != 0) {
4334 addInput(input, desc);
4335 }
4336 } // endif input != 0
4337
Eric Laurentcf2c0212014-07-25 16:20:43 -07004338 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004339 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004340 profiles.removeAt(profile_index);
4341 profile_index--;
4342 } else {
4343 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004344 if (audio_device_is_digital(device)) {
4345 devDesc->importAudioPort(profile);
4346 }
Eric Laurentd4692962014-05-05 18:13:44 -07004347 ALOGV("checkInputsForDevice(): adding input %d", input);
4348 }
4349 } // end scan profiles
4350
4351 if (profiles.isEmpty()) {
4352 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4353 return BAD_VALUE;
4354 }
4355 } else {
4356 // Disconnect
4357 // check if one opened input is not needed any more after disconnecting one device
4358 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4359 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004360 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004361 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4362 mInputs.keyAt(input_index));
4363 inputs.add(mInputs.keyAt(input_index));
4364 }
4365 }
4366 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004367 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004368 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004369 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004370 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004371 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004372 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004373 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4374 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004375 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004376 }
4377 }
4378 }
4379 } // end disconnect
4380
4381 return NO_ERROR;
4382}
4383
4384
Eric Laurente0720872014-03-11 09:30:41 -07004385void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004386{
4387 ALOGV("closeOutput(%d)", output);
4388
Eric Laurentc75307b2015-03-17 15:29:32 -07004389 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004390 if (outputDesc == NULL) {
4391 ALOGW("closeOutput() unknown output %d", output);
4392 return;
4393 }
François Gaffie036e1e92015-03-19 10:16:24 +01004394 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004395
Eric Laurente552edb2014-03-10 17:42:56 -07004396 // look for duplicated outputs connected to the output being removed.
4397 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004398 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004399 if (dupOutputDesc->isDuplicated() &&
4400 (dupOutputDesc->mOutput1 == outputDesc ||
4401 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004402 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004403 if (dupOutputDesc->mOutput1 == outputDesc) {
4404 outputDesc2 = dupOutputDesc->mOutput2;
4405 } else {
4406 outputDesc2 = dupOutputDesc->mOutput1;
4407 }
4408 // As all active tracks on duplicated output will be deleted,
4409 // and as they were also referenced on the other output, the reference
4410 // count for their stream type must be adjusted accordingly on
4411 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004412 const bool wasActive = outputDesc2->isActive();
4413 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4414 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004415 }
Eric Laurent733ce942017-12-07 12:18:25 -08004416 // stop() will be a no op if the output is still active but is needed in case all
4417 // active streams refcounts where cleared above
4418 if (wasActive) {
4419 outputDesc2->stop();
4420 }
Eric Laurente552edb2014-03-10 17:42:56 -07004421 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4422 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4423
4424 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004425 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004426 }
4427 }
4428
Eric Laurent05b90f82014-08-27 15:32:29 -07004429 nextAudioPortGeneration();
4430
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004431 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004432 if (index >= 0) {
4433 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004434 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004435 mAudioPatches.removeItemsAt(index);
4436 mpClientInterface->onAudioPatchListUpdate();
4437 }
4438
Eric Laurentfe231122017-11-17 17:48:06 -08004439 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004440
François Gaffie53615e22015-03-19 09:24:12 +01004441 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004442 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004443
4444 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4445 // no direct outputs are open.
4446 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4447 bool directOutputOpen = false;
4448 for (size_t i = 0; i < mOutputs.size(); i++) {
4449 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4450 directOutputOpen = true;
4451 break;
4452 }
4453 }
4454 if (!directOutputOpen) {
4455 ALOGV("no direct outputs open, reset MSD patch");
4456 setMsdPatch();
4457 }
4458 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004459}
4460
4461void AudioPolicyManager::closeInput(audio_io_handle_t input)
4462{
4463 ALOGV("closeInput(%d)", input);
4464
4465 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4466 if (inputDesc == NULL) {
4467 ALOGW("closeInput() unknown input %d", input);
4468 return;
4469 }
4470
Eric Laurent6a94d692014-05-20 11:18:06 -07004471 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004472
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004473 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004474 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004475 if (index >= 0) {
4476 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004477 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004478 mAudioPatches.removeItemsAt(index);
4479 mpClientInterface->onAudioPatchListUpdate();
4480 }
4481
Eric Laurentfe231122017-11-17 17:48:06 -08004482 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004483 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004484
4485 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4486 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4487 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4488 SoundTrigger::setCaptureState(false);
4489 }
Eric Laurente552edb2014-03-10 17:42:56 -07004490}
4491
Eric Laurentc75307b2015-03-17 15:29:32 -07004492SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4493 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004494 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004495{
4496 SortedVector<audio_io_handle_t> outputs;
4497
4498 ALOGVV("getOutputsForDevice() device %04x", device);
4499 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004500 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004501 i, openOutputs.valueAt(i)->isDuplicated(),
4502 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004503 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4504 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4505 outputs.add(openOutputs.keyAt(i));
4506 }
4507 }
4508 return outputs;
4509}
4510
Mikhail Naganov37977152018-07-11 15:54:44 -07004511void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4512{
4513 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4514 // output is suspended before any tracks are moved to it
4515 checkA2dpSuspend();
4516 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004517 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004518 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004519 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004520 setMsdPatch();
4521 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004522}
4523
Eric Laurente0720872014-03-11 09:30:41 -07004524void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004525{
4526 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4527 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4528 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4529 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4530
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004531 // also take into account external policy-related changes: add all outputs which are
4532 // associated with policies in the "before" and "after" output vectors
4533 ALOGVV("checkOutputForStrategy(): policy related outputs");
4534 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004536 if (desc != 0 && desc->mPolicyMix != NULL) {
4537 srcOutputs.add(desc->mIoHandle);
4538 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4539 }
4540 }
4541 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004542 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004543 if (desc != 0 && desc->mPolicyMix != NULL) {
4544 dstOutputs.add(desc->mIoHandle);
4545 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4546 }
4547 }
4548
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004549 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004550 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4551 // audio from invalidated tracks will be rendered when unmuting
4552 uint32_t maxLatency = 0;
4553 for (audio_io_handle_t srcOut : srcOutputs) {
4554 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4555 if (desc != 0 && maxLatency < desc->latency()) {
4556 maxLatency = desc->latency();
4557 }
4558 }
Eric Laurente552edb2014-03-10 17:42:56 -07004559 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4560 strategy, srcOutputs[0], dstOutputs[0]);
4561 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004562 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004563 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4564 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004565 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004566 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004567 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004568 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004569 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004570 if (source != 0){
4571 connectAudioSource(source);
4572 }
Eric Laurente552edb2014-03-10 17:42:56 -07004573 }
4574
4575 // Move effects associated to this strategy from previous output to new output
4576 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004577 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004578 }
4579 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004580 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004581 if (getStrategy((audio_stream_type_t)i) == strategy) {
4582 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004583 }
4584 }
4585 }
4586}
4587
Eric Laurente0720872014-03-11 09:30:41 -07004588void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004589{
François Gaffie2110e042015-03-24 08:41:51 +01004590 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004591 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004592 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004593 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004594 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 checkOutputForStrategy(STRATEGY_SONIFICATION);
4596 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004597 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004598 checkOutputForStrategy(STRATEGY_MEDIA);
4599 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004600 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004601}
4602
Eric Laurente0720872014-03-11 09:30:41 -07004603void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004604{
François Gaffie53615e22015-03-19 09:24:12 +01004605 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004606 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004607 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004608 return;
4609 }
4610
Eric Laurent3a4311c2014-03-17 12:00:47 -07004611 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004612 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4613 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4614 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004615
4616 // if suspended, restore A2DP output if:
4617 // ((SCO device is NOT connected) ||
4618 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4619 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004620 //
Eric Laurentf732e072016-08-03 19:30:28 -07004621 // if not suspended, suspend A2DP output if:
4622 // (SCO device is connected) &&
4623 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4624 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004625 //
4626 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004627 if (!isScoConnected ||
4628 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4629 AUDIO_POLICY_FORCE_BT_SCO) &&
4630 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4631 AUDIO_POLICY_FORCE_BT_SCO) &&
4632 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004633 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004634
4635 mpClientInterface->restoreOutput(a2dpOutput);
4636 mA2dpSuspended = false;
4637 }
4638 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004639 if (isScoConnected &&
4640 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4641 AUDIO_POLICY_FORCE_BT_SCO) ||
4642 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4643 AUDIO_POLICY_FORCE_BT_SCO) ||
4644 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004645 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004646
4647 mpClientInterface->suspendOutput(a2dpOutput);
4648 mA2dpSuspended = true;
4649 }
4650 }
4651}
4652
Eric Laurent97ac8712018-07-27 18:59:02 -07004653template <class IoDescriptor, class Filter>
4654sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4655 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4656{
4657 auto activeClients = desc->clientsList(true /*activeOnly*/);
4658 auto activeClientsWithRoute =
4659 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4660 active = activeClients.size() > 0;
4661 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4662 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4663 }
4664 return nullptr;
4665}
4666
4667template <class IoCollection, class Filter>
4668sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4669 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4670{
4671 sp<DeviceDescriptor> device;
4672 for (size_t i = 0; i < ioCollection.size(); i++) {
4673 auto desc = ioCollection.valueAt(i);
4674 bool active;
4675 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4676 if (active && curDevice == nullptr) {
4677 return nullptr;
4678 } else if (curDevice != nullptr) {
4679 device = curDevice;
4680 }
4681 }
4682 return device;
4683}
4684
Eric Laurentc75307b2015-03-17 15:29:32 -07004685audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4686 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004687{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004688 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 if (index >= 0) {
4690 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4691 if (patchDesc->mUid != mUidCached) {
4692 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004693 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 return outputDesc->device();
4695 }
4696 }
4697
Eric Laurent97ac8712018-07-27 18:59:02 -07004698 // Honor explicit routing requests only if no client using default routing is active on this
4699 // input: a specific app can not force routing for other apps by setting a preferred device.
4700 bool active; // unused
4701 sp<DeviceDescriptor> deviceDesc =
4702 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4703 if (deviceDesc != nullptr) {
4704 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004705 }
4706
Eric Laurente552edb2014-03-10 17:42:56 -07004707 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004708 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004709 // use device for strategy enforced audible
4710 // 2: we are in call or the strategy phone is active on the output:
4711 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004712 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004713 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004714 // 4: the strategy for enforced audible is active but not enforced on the output:
4715 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004716 // 5: the strategy accessibility is active on the output:
4717 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004718 // 6: the strategy "respectful" sonification is active on the output:
4719 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004720 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004721 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004722 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004723 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004724 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004725 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004726
4727 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4728 // with a refined rule considering mutually exclusive devices (using same backend)
4729 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004730 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004731 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004732 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004733 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4734 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004735 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004736 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004737 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004738 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004739 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4740 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004741 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4742 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004743 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004744 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004745 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004746 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004747 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004748 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004749 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004750 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004751 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004752 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004753 }
4754
Eric Laurent1c333e22014-05-20 10:48:17 -07004755 ALOGV("getNewOutputDevice() selected device %x", device);
4756 return device;
4757}
4758
Eric Laurentfb66dd92016-01-28 18:32:03 -08004759audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004760{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004761 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004762
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004763 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 if (index >= 0) {
4765 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4766 if (patchDesc->mUid != mUidCached) {
4767 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004768 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 return inputDesc->mDevice;
4770 }
4771 }
4772
Eric Laurent97ac8712018-07-27 18:59:02 -07004773 // Honor explicit routing requests only if no client using default routing is active on this
4774 // input: a specific app can not force routing for other apps by setting a preferred device.
4775 bool active;
4776 sp<DeviceDescriptor> deviceDesc =
4777 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4778 if (deviceDesc != nullptr) {
4779 return deviceDesc->type();
4780 }
4781
Eric Laurentdc95a252018-04-12 12:46:56 -07004782 // If we are not in call and no client is active on this input, this methods returns
4783 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08004784 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004785 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4786 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4787 }
4788 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004789 device = getDeviceAndMixForInputSource(source);
4790 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004791
Eric Laurente552edb2014-03-10 17:42:56 -07004792 return device;
4793}
4794
Eric Laurent794fde22016-03-11 09:50:45 -08004795bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4796 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004797 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004801 return (uint32_t)getStrategy(stream);
4802}
4803
Eric Laurente0720872014-03-11 09:30:41 -07004804audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004805 // By checking the range of stream before calling getStrategy, we avoid
4806 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4807 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004808 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 return AUDIO_DEVICE_NONE;
4810 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004811 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004812 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004813 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4814 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004815 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 }
Eric Laurent794fde22016-03-11 09:50:45 -08004817 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004818 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004819 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004820 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004821 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4822 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004823 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004824 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 }
4826 }
Eric Laurente552edb2014-03-10 17:42:56 -07004827 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004828
Eric Laurentb0688d62018-08-14 15:49:18 -07004829 // Favor devices selected on active streams if any to report correct device in case of
4830 // explicit device selection
4831 if (activeDevices != AUDIO_DEVICE_NONE) {
4832 devices = activeDevices;
4833 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004834 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4835 and doesn't really need to.*/
4836 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4837 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4838 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4839 }
Eric Laurente552edb2014-03-10 17:42:56 -07004840 return devices;
4841}
4842
François Gaffie2110e042015-03-24 08:41:51 +01004843routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4844{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004845 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004846 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004847}
4848
Eric Laurent97ac8712018-07-27 18:59:02 -07004849routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004850 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004851 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004852 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004853 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004854 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004855 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004856 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004857 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004858 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004859}
4860
Eric Laurente0720872014-03-11 09:30:41 -07004861void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004862 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004863 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004864 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4865 updateDevicesAndOutputs();
4866 break;
4867 default:
4868 break;
4869 }
4870}
4871
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004872uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004873
4874 // skip beacon mute management if a dedicated TTS output is available
4875 if (mTtsOutputAvailable) {
4876 return 0;
4877 }
4878
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004879 switch(event) {
4880 case STARTING_OUTPUT:
4881 mBeaconMuteRefCount++;
4882 break;
4883 case STOPPING_OUTPUT:
4884 if (mBeaconMuteRefCount > 0) {
4885 mBeaconMuteRefCount--;
4886 }
4887 break;
4888 case STARTING_BEACON:
4889 mBeaconPlayingRefCount++;
4890 break;
4891 case STOPPING_BEACON:
4892 if (mBeaconPlayingRefCount > 0) {
4893 mBeaconPlayingRefCount--;
4894 }
4895 break;
4896 }
4897
4898 if (mBeaconMuteRefCount > 0) {
4899 // any playback causes beacon to be muted
4900 return setBeaconMute(true);
4901 } else {
4902 // no other playback: unmute when beacon starts playing, mute when it stops
4903 return setBeaconMute(mBeaconPlayingRefCount == 0);
4904 }
4905}
4906
4907uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4908 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4909 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4910 // keep track of muted state to avoid repeating mute/unmute operations
4911 if (mBeaconMuted != mute) {
4912 // mute/unmute AUDIO_STREAM_TTS on all outputs
4913 ALOGV("\t muting %d", mute);
4914 uint32_t maxLatency = 0;
4915 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004916 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004917 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004918 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004919 0 /*delay*/, AUDIO_DEVICE_NONE);
4920 const uint32_t latency = desc->latency() * 2;
4921 if (latency > maxLatency) {
4922 maxLatency = latency;
4923 }
4924 }
4925 mBeaconMuted = mute;
4926 return maxLatency;
4927 }
4928 return 0;
4929}
4930
Eric Laurente0720872014-03-11 09:30:41 -07004931audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004932 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004933{
Eric Laurent97ac8712018-07-27 18:59:02 -07004934 // Honor explicit routing requests only if all active clients have a preferred route in which
4935 // case the last active client route is used
4936 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
4937 if (deviceDesc != nullptr) {
4938 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07004939 }
4940
Eric Laurente552edb2014-03-10 17:42:56 -07004941 if (fromCache) {
4942 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4943 strategy, mDeviceForStrategy[strategy]);
4944 return mDeviceForStrategy[strategy];
4945 }
François Gaffie2110e042015-03-24 08:41:51 +01004946 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004947}
4948
Eric Laurente0720872014-03-11 09:30:41 -07004949void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004950{
4951 for (int i = 0; i < NUM_STRATEGIES; i++) {
4952 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4953 }
4954 mPreviousOutputs = mOutputs;
4955}
4956
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004957uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004958 audio_devices_t prevDevice,
4959 uint32_t delayMs)
4960{
4961 // mute/unmute strategies using an incompatible device combination
4962 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4963 // if unmuting, unmute only after the specified delay
4964 if (outputDesc->isDuplicated()) {
4965 return 0;
4966 }
4967
4968 uint32_t muteWaitMs = 0;
4969 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004970 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004971
4972 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4973 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004974 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004975 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4976 bool doMute = false;
4977
4978 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4979 doMute = true;
4980 outputDesc->mStrategyMutedByDevice[i] = true;
4981 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4982 doMute = true;
4983 outputDesc->mStrategyMutedByDevice[i] = false;
4984 }
Eric Laurent99401132014-05-07 19:48:15 -07004985 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004986 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004987 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004988 // skip output if it does not share any device with current output
4989 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4990 == AUDIO_DEVICE_NONE) {
4991 continue;
4992 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004993 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004994 mute ? "muting" : "unmuting", i, curDevice);
4995 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004996 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004997 if (mute) {
4998 // FIXME: should not need to double latency if volume could be applied
4999 // immediately by the audioflinger mixer. We must account for the delay
5000 // between now and the next time the audioflinger thread for this output
5001 // will process a buffer (which corresponds to one buffer size,
5002 // usually 1/2 or 1/4 of the latency).
5003 if (muteWaitMs < desc->latency() * 2) {
5004 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005005 }
5006 }
5007 }
5008 }
5009 }
5010 }
5011
Eric Laurent99401132014-05-07 19:48:15 -07005012 // temporary mute output if device selection changes to avoid volume bursts due to
5013 // different per device volumes
5014 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005015 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5016 // temporary mute duration is conservatively set to 4 times the reported latency
5017 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5018 if (muteWaitMs < tempMuteWaitMs) {
5019 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005020 }
Eric Laurentdc462862016-07-19 12:29:53 -07005021
Eric Laurent99401132014-05-07 19:48:15 -07005022 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005023 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005024 // make sure that we do not start the temporary mute period too early in case of
5025 // delayed device change
5026 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005027 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005028 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005029 }
5030 }
5031 }
5032
Eric Laurente552edb2014-03-10 17:42:56 -07005033 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5034 if (muteWaitMs > delayMs) {
5035 muteWaitMs -= delayMs;
5036 usleep(muteWaitMs * 1000);
5037 return muteWaitMs;
5038 }
5039 return 0;
5040}
5041
Eric Laurentc75307b2015-03-17 15:29:32 -07005042uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005043 audio_devices_t device,
5044 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005046 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005047 const char *address,
5048 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005049{
Eric Laurentc75307b2015-03-17 15:29:32 -07005050 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005051 AudioParameter param;
5052 uint32_t muteWaitMs;
5053
5054 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005055 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5056 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5057 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5058 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005059 return muteWaitMs;
5060 }
5061 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5062 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005064 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005065 return 0;
5066 }
5067
5068 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005069 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005070
5071 audio_devices_t prevDevice = outputDesc->mDevice;
5072
Paul McLeanaa981192015-03-21 09:55:15 -07005073 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005074
5075 if (device != AUDIO_DEVICE_NONE) {
5076 outputDesc->mDevice = device;
5077 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005078
5079 // if the outputs are not materially active, there is no need to mute.
5080 if (requiresMuteCheck) {
5081 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5082 } else {
5083 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5084 muteWaitMs = 0;
5085 }
Eric Laurente552edb2014-03-10 17:42:56 -07005086
5087 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005088 // the requested device is AUDIO_DEVICE_NONE
5089 // OR the requested device is the same as current device
5090 // AND force is not specified
5091 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005092 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005093 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5094 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005095 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005096 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005097 return muteWaitMs;
5098 }
5099
5100 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005101
Eric Laurente552edb2014-03-10 17:42:56 -07005102 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005103 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005104 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005105 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005106 DeviceVector deviceList;
5107 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005108 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005109 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005110 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5111 device, String8(address));
5112 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005113 }
5114
Eric Laurent1c333e22014-05-20 10:48:17 -07005115 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005116 PatchBuilder patchBuilder;
5117 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005118 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005119 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005120 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005121 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005122 }
5123 }
Eric Laurente552edb2014-03-10 17:42:56 -07005124
5125 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005126 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005127
5128 return muteWaitMs;
5129}
5130
Eric Laurentc75307b2015-03-17 15:29:32 -07005131status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 int delayMs,
5133 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005134{
Eric Laurent6a94d692014-05-20 11:18:06 -07005135 ssize_t index;
5136 if (patchHandle) {
5137 index = mAudioPatches.indexOfKey(*patchHandle);
5138 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005139 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005140 }
5141 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005142 return INVALID_OPERATION;
5143 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005144 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5145 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005146 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005147 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 removeAudioPatch(patchDesc->mHandle);
5149 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005150 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005151 return status;
5152}
5153
5154status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5155 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005156 bool force,
5157 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005158{
5159 status_t status = NO_ERROR;
5160
Eric Laurent1f2f2232014-06-02 12:01:23 -07005161 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005162 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5163 inputDesc->mDevice = device;
5164
Mikhail Naganov708e0382018-05-30 09:53:04 -07005165 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005166 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005167 PatchBuilder patchBuilder;
5168 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005169 // AUDIO_SOURCE_HOTWORD is for internal use only:
5170 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005171 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5172 auto result = usecase;
5173 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5174 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5175 }
5176 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005177 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005178 addSource(deviceList.itemAt(0));
5179 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005180 }
5181 }
5182 return status;
5183}
5184
Eric Laurent6a94d692014-05-20 11:18:06 -07005185status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5186 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005187{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005188 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 ssize_t index;
5190 if (patchHandle) {
5191 index = mAudioPatches.indexOfKey(*patchHandle);
5192 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005193 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005194 }
5195 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005196 return INVALID_OPERATION;
5197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5199 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005200 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005201 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 removeAudioPatch(patchDesc->mHandle);
5203 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005204 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005205 return status;
5206}
5207
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005208sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005209 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005210 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005211 audio_format_t& format,
5212 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005213 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005214{
5215 // Choose an input profile based on the requested capture parameters: select the first available
5216 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005217 //
5218 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5219 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005220
Glenn Kasten730b9262018-03-29 15:01:26 -07005221 sp<IOProfile> firstInexact;
5222 uint32_t updatedSamplingRate = 0;
5223 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5224 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005225 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005226 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005227 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005228 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005229 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005230 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005231 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005232 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005233 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005234 &channelMask /*updatedChannelMask*/,
5235 // FIXME ugly cast
5236 (audio_output_flags_t) flags,
5237 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005238 return profile;
5239 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005240 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5241 samplingRate,
5242 &updatedSamplingRate,
5243 format,
5244 &updatedFormat,
5245 channelMask,
5246 &updatedChannelMask,
5247 // FIXME ugly cast
5248 (audio_output_flags_t) flags,
5249 false /*exactMatchRequiredForInputFlags*/)) {
5250 firstInexact = profile;
5251 }
5252
Eric Laurente552edb2014-03-10 17:42:56 -07005253 }
5254 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005255 if (firstInexact != nullptr) {
5256 samplingRate = updatedSamplingRate;
5257 format = updatedFormat;
5258 channelMask = updatedChannelMask;
5259 return firstInexact;
5260 }
Eric Laurente552edb2014-03-10 17:42:56 -07005261 return NULL;
5262}
5263
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005264
5265audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005266 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005267{
Eric Laurent97ac8712018-07-27 18:59:02 -07005268 // Honor explicit routing requests only if all active clients have a preferred route in which
5269 // case the last active client route is used
5270 sp<DeviceDescriptor> deviceDesc =
5271 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5272 if (deviceDesc != nullptr) {
5273 return deviceDesc->type();
5274 }
5275
5276
François Gaffie036e1e92015-03-19 10:16:24 +01005277 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5278 audio_devices_t selectedDeviceFromMix =
5279 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005280
François Gaffie036e1e92015-03-19 10:16:24 +01005281 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5282 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005283 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005284 return getDeviceForInputSource(inputSource);
5285}
5286
5287audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5288{
Eric Laurent97ac8712018-07-27 18:59:02 -07005289 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005290}
5291
Eric Laurente0720872014-03-11 09:30:41 -07005292float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005293 int index,
5294 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005295{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005296 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005297
5298 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5299 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5300 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5301 // the ringtone volume
5302 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5303 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5304 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5305 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5306 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5307 }
5308
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005309 // in-call: always cap volume by voice volume + some low headroom
5310 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005311 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005312 switch (stream) {
5313 case AUDIO_STREAM_SYSTEM:
5314 case AUDIO_STREAM_RING:
5315 case AUDIO_STREAM_MUSIC:
5316 case AUDIO_STREAM_ALARM:
5317 case AUDIO_STREAM_NOTIFICATION:
5318 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5319 case AUDIO_STREAM_DTMF:
5320 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005321 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005322 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005323 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005324 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005325 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005326 if (volumeDB > maxVoiceVolDb) {
5327 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5328 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5329 volumeDB = maxVoiceVolDb;
5330 }
5331 } break;
5332 default:
5333 break;
5334 }
5335 }
5336
Eric Laurente552edb2014-03-10 17:42:56 -07005337 // if a headset is connected, apply the following rules to ring tones and notifications
5338 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005339 // - always attenuate notifications volume by 6dB
5340 // - attenuate ring tones volume by 6dB unless music is not playing and
5341 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005342 // - if music is playing, always limit the volume to current music volume,
5343 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005344 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005345 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5346 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5347 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005348 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005349 AUDIO_DEVICE_OUT_USB_HEADSET |
5350 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005351 ((stream_strategy == STRATEGY_SONIFICATION)
5352 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005353 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005354 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005355 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005356 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005357 // when the phone is ringing we must consider that music could have been paused just before
5358 // by the music application and behave as if music was active if the last music track was
5359 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005360 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005361 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005362 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005363 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005364 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005365 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5366 musicDevice),
5367 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005368 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5369 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005370 if (volumeDB > minVolDB) {
5371 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005372 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005373 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005374 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5375 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5376 // on A2DP, also ensure notification volume is not too low compared to media when
5377 // intended to be played
5378 if ((volumeDB > -96.0f) &&
5379 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5380 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5381 stream, device,
5382 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5383 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5384 }
5385 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005386 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5387 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005388 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005389 }
5390 }
5391
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005392 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005393}
5394
Eric Laurent3839bc02018-07-10 18:33:34 -07005395int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5396 audio_stream_type_t srcStream,
5397 audio_stream_type_t dstStream)
5398{
5399 if (srcStream == dstStream) {
5400 return srcIndex;
5401 }
5402 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5403 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5404 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5405 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5406
5407 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5408}
5409
Eric Laurente0720872014-03-11 09:30:41 -07005410status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005411 int index,
5412 const sp<AudioOutputDescriptor>& outputDesc,
5413 audio_devices_t device,
5414 int delayMs,
5415 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005416{
Eric Laurente552edb2014-03-10 17:42:56 -07005417 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005418 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005419 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005420 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005421 return NO_ERROR;
5422 }
François Gaffie2110e042015-03-24 08:41:51 +01005423 audio_policy_forced_cfg_t forceUseForComm =
5424 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005425 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005426 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5427 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005428 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005429 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005430 return INVALID_OPERATION;
5431 }
5432
Eric Laurentc75307b2015-03-17 15:29:32 -07005433 if (device == AUDIO_DEVICE_NONE) {
5434 device = outputDesc->device();
5435 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005436
Eric Laurentffbc80f2015-03-18 18:30:19 -07005437 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005438 if (outputDesc->isFixedVolume(device) ||
5439 // Force VoIP volume to max for bluetooth SCO
5440 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5441 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005442 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005443 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005444
Eric Laurentffbc80f2015-03-18 18:30:19 -07005445 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005446
Eric Laurent3b73df72014-03-11 09:06:29 -07005447 if (stream == AUDIO_STREAM_VOICE_CALL ||
5448 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005449 float voiceVolume;
5450 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005451 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005452 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005453 } else {
5454 voiceVolume = 1.0;
5455 }
5456
Eric Laurent18fba842016-03-31 14:41:26 -07005457 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005458 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5459 mLastVoiceVolume = voiceVolume;
5460 }
5461 }
5462
5463 return NO_ERROR;
5464}
5465
Eric Laurentc75307b2015-03-17 15:29:32 -07005466void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5467 audio_devices_t device,
5468 int delayMs,
5469 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005470{
Eric Laurentc75307b2015-03-17 15:29:32 -07005471 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005472
Eric Laurent794fde22016-03-11 09:50:45 -08005473 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005474 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005475 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005476 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005477 device,
5478 delayMs,
5479 force);
5480 }
5481}
5482
Eric Laurente0720872014-03-11 09:30:41 -07005483void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005484 bool on,
5485 const sp<AudioOutputDescriptor>& outputDesc,
5486 int delayMs,
5487 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005488{
Eric Laurent72249d52015-06-08 11:12:15 -07005489 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5490 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005491 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005492 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005493 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005494 }
5495 }
5496}
5497
Eric Laurente0720872014-03-11 09:30:41 -07005498void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005499 bool on,
5500 const sp<AudioOutputDescriptor>& outputDesc,
5501 int delayMs,
5502 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005503{
Eric Laurente552edb2014-03-10 17:42:56 -07005504 if (device == AUDIO_DEVICE_NONE) {
5505 device = outputDesc->device();
5506 }
5507
Eric Laurentc75307b2015-03-17 15:29:32 -07005508 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5509 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005510
5511 if (on) {
5512 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005513 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005514 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005515 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005516 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005517 }
5518 }
5519 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5520 outputDesc->mMuteCount[stream]++;
5521 } else {
5522 if (outputDesc->mMuteCount[stream] == 0) {
5523 ALOGV("setStreamMute() unmuting non muted stream!");
5524 return;
5525 }
5526 if (--outputDesc->mMuteCount[stream] == 0) {
5527 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005528 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005529 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005530 device,
5531 delayMs);
5532 }
5533 }
5534}
5535
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005536audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5537{
5538 // flags to stream type mapping
5539 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5540 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5541 }
5542 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5543 return AUDIO_STREAM_BLUETOOTH_SCO;
5544 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005545 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5546 return AUDIO_STREAM_TTS;
5547 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005548
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005549 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005550}
Eric Laurente83b55d2014-11-14 10:06:21 -08005551
François Gaffie53615e22015-03-19 09:24:12 +01005552bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5553{
Eric Laurente83b55d2014-11-14 10:06:21 -08005554 // has flags that map to a strategy?
5555 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5556 return true;
5557 }
5558
5559 // has known usage?
5560 switch (paa->usage) {
5561 case AUDIO_USAGE_UNKNOWN:
5562 case AUDIO_USAGE_MEDIA:
5563 case AUDIO_USAGE_VOICE_COMMUNICATION:
5564 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5565 case AUDIO_USAGE_ALARM:
5566 case AUDIO_USAGE_NOTIFICATION:
5567 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5568 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5569 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5570 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5571 case AUDIO_USAGE_NOTIFICATION_EVENT:
5572 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5573 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5574 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5575 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005576 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005577 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005578 break;
5579 default:
5580 return false;
5581 }
5582 return true;
5583}
5584
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005585bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005586 routing_strategy strategy, uint32_t inPastMs,
5587 nsecs_t sysTime) const
5588{
5589 if ((sysTime == 0) && (inPastMs != 0)) {
5590 sysTime = systemTime();
5591 }
Eric Laurent794fde22016-03-11 09:50:45 -08005592 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005593 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005594 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005595 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5596 return true;
5597 }
5598 }
5599 return false;
5600}
5601
Eric Laurent484e9272018-06-07 17:29:23 -07005602bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5603 routing_strategy strategy, uint32_t inPastMs,
5604 nsecs_t sysTime) const
5605{
5606 for (size_t i = 0; i < mOutputs.size(); i++) {
5607 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5608 if (outputDesc->sharesHwModuleWith(desc)
5609 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5610 return true;
5611 }
5612 }
5613 return false;
5614}
5615
François Gaffie2110e042015-03-24 08:41:51 +01005616audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5617{
5618 return mEngine->getForceUse(usage);
5619}
5620
5621bool AudioPolicyManager::isInCall()
5622{
5623 return isStateInCall(mEngine->getPhoneState());
5624}
5625
5626bool AudioPolicyManager::isStateInCall(int state)
5627{
5628 return is_state_in_call(state);
5629}
5630
Eric Laurentd60560a2015-04-10 11:31:20 -07005631void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5632{
5633 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005634 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5635 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5636 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5637 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005638 }
5639 }
5640
5641 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5642 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5643 bool release = false;
5644 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5645 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5646 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5647 source->ext.device.type == deviceDesc->type()) {
5648 release = true;
5649 }
5650 }
5651 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5652 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5653 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5654 sink->ext.device.type == deviceDesc->type()) {
5655 release = true;
5656 }
5657 }
5658 if (release) {
5659 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5660 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5661 }
5662 }
5663}
5664
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005665void AudioPolicyManager::modifySurroundFormats(
5666 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
5667 // Use a set because FormatVector is unsorted.
5668 std::unordered_set<audio_format_t> enforcedSurround(
5669 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Phil Burk09bc4612016-02-24 15:58:15 -08005670
5671 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5672 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005673 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005674
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005675 std::unordered_set<audio_format_t> formatSet;
5676 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5677 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5678 // Only copy non-surround formats to formatSet.
5679 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
5680 if (mConfig.getSurroundFormats().count(*formatIter) == 0 &&
5681 enforcedSurround.count(*formatIter) == 0) {
5682 formatSet.insert(*formatIter);
5683 }
5684 }
5685 } else {
5686 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5687 }
5688 formatsPtr->clear(); // Re-filled from the formatSet in the end.
5689
jiabin81772902018-04-02 17:52:27 -07005690 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5691 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005692 formatSet.insert(mSurroundFormats.begin(), mSurroundFormats.end());
5693 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5694 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5695 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005696 }
jiabin81772902018-04-02 17:52:27 -07005697 } else { // NEVER, AUTO or ALWAYS
jiabin81772902018-04-02 17:52:27 -07005698 mSurroundFormats.clear();
jiabin81772902018-04-02 17:52:27 -07005699 // Modify formats based on surround preferences.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005700 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
jiabin81772902018-04-02 17:52:27 -07005701 // If ALWAYS, add support for raw surround formats if all are missing.
5702 // This assumes that if any of these formats are reported by the HAL
5703 // then the report is valid and should not be modified.
5704 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005705 for (const auto& format : mConfig.getSurroundFormats()) {
5706 formatSet.insert(format.first);
5707 }
jiabin81772902018-04-02 17:52:27 -07005708 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005709 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
jiabin81772902018-04-02 17:52:27 -07005710
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005711 for (const auto& format : formatSet) {
Mikhail Naganov02743e22018-11-28 15:56:55 -08005712 if (mConfig.getSurroundFormats().count(format) != 0) {
5713 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005714 }
Phil Burk09bc4612016-02-24 15:58:15 -08005715 }
Phil Burk07ac1142016-03-25 13:39:29 -07005716 }
Phil Burk09bc4612016-02-24 15:58:15 -08005717 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005718 for (const auto& format : formatSet) {
5719 formatsPtr->push(format);
5720 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005721}
5722
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005723void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005724 ChannelsVector &channelMasks = *channelMasksPtr;
5725 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5726 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5727
5728 // If NEVER, then remove support for channelMasks > stereo.
5729 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5730 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5731 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5732 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5733 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5734 channelMasks.removeAt(maskIndex);
5735 } else {
5736 maskIndex++;
5737 }
5738 }
jiabin81772902018-04-02 17:52:27 -07005739 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5740 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5741 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005742 bool supports5dot1 = false;
5743 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005744 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005745 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5746 supports5dot1 = true;
5747 break;
5748 }
5749 }
5750 // If not then add 5.1 support.
5751 if (!supports5dot1) {
5752 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5753 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5754 }
Phil Burk09bc4612016-02-24 15:58:15 -08005755 }
5756}
5757
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005758void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005759 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005760 AudioProfileVector &profiles)
5761{
5762 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005763 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005764
François Gaffie112b0af2015-11-19 16:13:25 +01005765 // Format MUST be checked first to update the list of AudioProfile
5766 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005767 reply = mpClientInterface->getParameters(
5768 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005769 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005770 AudioParameter repliedParameters(reply);
5771 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005772 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005773 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5774 return;
5775 }
Phil Burk09bc4612016-02-24 15:58:15 -08005776 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005777 if (device == AUDIO_DEVICE_OUT_HDMI) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005778 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005779 }
Phil Burk09bc4612016-02-24 15:58:15 -08005780 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005781 }
François Gaffie112b0af2015-11-19 16:13:25 +01005782
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005783 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005784 ChannelsVector channelMasks;
5785 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005786 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005787 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005788
5789 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005790 reply = mpClientInterface->getParameters(
5791 ioHandle,
5792 requestedParameters.toString() + ";" +
5793 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005794 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005795 AudioParameter repliedParameters(reply);
5796 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005797 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005798 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005799 }
5800 }
5801 if (profiles.hasDynamicChannelsFor(format)) {
5802 reply = mpClientInterface->getParameters(ioHandle,
5803 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005804 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005805 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005806 AudioParameter repliedParameters(reply);
5807 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005808 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005809 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005810 if (device == AUDIO_DEVICE_OUT_HDMI) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005811 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005812 }
François Gaffie112b0af2015-11-19 16:13:25 +01005813 }
5814 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005815 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005816 }
5817}
Eric Laurentd60560a2015-04-10 11:31:20 -07005818
Mikhail Naganovdc769682018-05-04 15:34:08 -07005819status_t AudioPolicyManager::installPatch(const char *caller,
5820 audio_patch_handle_t *patchHandle,
5821 AudioIODescriptorInterface *ioDescriptor,
5822 const struct audio_patch *patch,
5823 int delayMs)
5824{
5825 ssize_t index = mAudioPatches.indexOfKey(
5826 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5827 *patchHandle : ioDescriptor->getPatchHandle());
5828 sp<AudioPatch> patchDesc;
5829 status_t status = installPatch(
5830 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5831 if (status == NO_ERROR) {
5832 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5833 }
5834 return status;
5835}
5836
5837status_t AudioPolicyManager::installPatch(const char *caller,
5838 ssize_t index,
5839 audio_patch_handle_t *patchHandle,
5840 const struct audio_patch *patch,
5841 int delayMs,
5842 uid_t uid,
5843 sp<AudioPatch> *patchDescPtr)
5844{
5845 sp<AudioPatch> patchDesc;
5846 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5847 if (index >= 0) {
5848 patchDesc = mAudioPatches.valueAt(index);
5849 afPatchHandle = patchDesc->mAfPatchHandle;
5850 }
5851
5852 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5853 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5854 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5855 if (status == NO_ERROR) {
5856 if (index < 0) {
5857 patchDesc = new AudioPatch(patch, uid);
5858 addAudioPatch(patchDesc->mHandle, patchDesc);
5859 } else {
5860 patchDesc->mPatch = *patch;
5861 }
5862 patchDesc->mAfPatchHandle = afPatchHandle;
5863 if (patchHandle) {
5864 *patchHandle = patchDesc->mHandle;
5865 }
5866 nextAudioPortGeneration();
5867 mpClientInterface->onAudioPatchListUpdate();
5868 }
5869 if (patchDescPtr) *patchDescPtr = patchDesc;
5870 return status;
5871}
5872
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005873} // namespace android