blob: 5dbd5b385a40bc599f77e5be652090f0190c0fae [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"
Cheney Ni6851adb2018-11-01 06:30:37 +080036#define AUDIO_POLICY_BLUETOOTH_HAL_ENABLED_XML_CONFIG_FILE_NAME \
37 "audio_policy_configuration_bluetooth_hal_enabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010038
Eric Laurentd4692962014-05-05 18:13:44 -070039#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070040#include <math.h>
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>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070048#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070050#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010053#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010054#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010055#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010056#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010057#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010058#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Eric Laurentdc462862016-07-19 12:29:53 -070062//FIXME: workaround for truncated touch sounds
63// to be removed when the problem is handled by system UI
64#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070065
66// Largest difference in dB on earpiece in call between the voice volume and another
67// media / notification / system volume.
68constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
69
jiabin81772902018-04-02 17:52:27 -070070#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
71// Array of all surround formats.
72static const audio_format_t SURROUND_FORMATS[] = {
73 AUDIO_FORMAT_AC3,
74 AUDIO_FORMAT_E_AC3,
75 AUDIO_FORMAT_DTS,
76 AUDIO_FORMAT_DTS_HD,
77 AUDIO_FORMAT_AAC_LC,
78 AUDIO_FORMAT_DOLBY_TRUEHD,
79 AUDIO_FORMAT_E_AC3_JOC,
80};
81// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
82static const audio_format_t AAC_FORMATS[] = {
83 AUDIO_FORMAT_AAC_LC,
84 AUDIO_FORMAT_AAC_HE_V1,
85 AUDIO_FORMAT_AAC_HE_V2,
86 AUDIO_FORMAT_AAC_ELD,
87 AUDIO_FORMAT_AAC_XHE,
88};
89
Eric Laurente552edb2014-03-10 17:42:56 -070090// ----------------------------------------------------------------------------
91// AudioPolicyInterface implementation
92// ----------------------------------------------------------------------------
93
Eric Laurente0720872014-03-11 09:30:41 -070094status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080095 audio_policy_dev_state_t state,
96 const char *device_address,
97 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070098{
jiabina7b43792018-02-15 16:04:46 -080099 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
100 nextAudioPortGeneration();
101 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102}
103
François Gaffie44481e72016-04-20 07:49:57 +0200104void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
105 audio_policy_dev_state_t state,
106 const String8 &device_address)
107{
108 AudioParameter param(device_address);
109 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700110 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200111 param.addInt(key, device);
112 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
113}
114
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800115status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800116 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800117 const char *device_address,
118 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800119{
Paul McLeane743a472015-01-28 11:07:31 -0800120 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800121 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700122
123 // connect/disconnect only 1 device at a time
124 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
125
François Gaffie53615e22015-03-19 09:24:12 +0100126 sp<DeviceDescriptor> devDesc =
127 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800128
Eric Laurente552edb2014-03-10 17:42:56 -0700129 // handle output devices
130 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700131 SortedVector <audio_io_handle_t> outputs;
132
Eric Laurent3a4311c2014-03-17 12:00:47 -0700133 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
134
Eric Laurente552edb2014-03-10 17:42:56 -0700135 // save a copy of the opened output descriptors before any output is opened or closed
136 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
137 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700138 switch (state)
139 {
140 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800141 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700142 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700143 ALOGW("setDeviceConnectionState() device already connected: %x", device);
144 return INVALID_OPERATION;
145 }
146 ALOGV("setDeviceConnectionState() connecting device %x", device);
147
Eric Laurente552edb2014-03-10 17:42:56 -0700148 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700149 index = mAvailableOutputDevices.add(devDesc);
150 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100151 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700152 if (module == 0) {
153 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
154 device);
155 mAvailableOutputDevices.remove(devDesc);
156 return INVALID_OPERATION;
157 }
Paul McLeane743a472015-01-28 11:07:31 -0800158 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 } else {
160 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700161 }
162
François Gaffie44481e72016-04-20 07:49:57 +0200163 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
164 // parameters on newly connected devices (instead of opening the outputs...)
165 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
166
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700168 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200169
170 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
171 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 return INVALID_OPERATION;
173 }
François Gaffie2110e042015-03-24 08:41:51 +0100174 // Propagate device availability to Engine
175 mEngine->setDeviceConnectionState(devDesc, state);
176
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700177 // outputs should never be empty here
178 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
179 "checkOutputsForDevice() returned no outputs but status OK");
180 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
181 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800182
Eric Laurent3ae5f312015-02-03 17:12:08 -0800183 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700185 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700186 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700187 ALOGW("setDeviceConnectionState() device not connected: %x", device);
188 return INVALID_OPERATION;
189 }
190
Paul McLean5c477aa2014-08-20 16:47:57 -0700191 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
192
Paul McLeane743a472015-01-28 11:07:31 -0800193 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200194 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700195
Eric Laurente552edb2014-03-10 17:42:56 -0700196 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700198
Eric Laurenta1d525f2015-01-29 13:36:45 -0800199 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100200
201 // Propagate device availability to Engine
202 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700203 } break;
204
205 default:
206 ALOGE("setDeviceConnectionState() invalid state: %x", state);
207 return BAD_VALUE;
208 }
209
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
211 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700212 checkA2dpSuspend();
213 checkOutputForAllStrategies();
214 // outputs must be closed after checkOutputForAllStrategies() is executed
215 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800216 for (audio_io_handle_t output : outputs) {
217 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700218 // close unused outputs after device disconnection or direct outputs that have been
219 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700220 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700221 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
222 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800223 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700224 }
225 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 // check again after closing A2DP output to reset mA2dpSuspended if needed
227 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700228 }
229
230 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700231 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
233 updateCallRouting(newDevice);
234 }
Eric Laurente552edb2014-03-10 17:42:56 -0700235 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700236 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
237 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
238 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700239 // do not force device change on duplicated output because if device is 0, it will
240 // also force a device 0 for the two outputs it is duplicated to which may override
241 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700242 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100243 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700244 // always force when disconnecting (a non-duplicated device)
245 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700246 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700247 }
Eric Laurente552edb2014-03-10 17:42:56 -0700248 }
249
Eric Laurentd60560a2015-04-10 11:31:20 -0700250 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
251 cleanUpForDevice(devDesc);
252 }
253
Eric Laurent72aa32f2014-05-30 18:51:48 -0700254 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700255 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700256 } // end if is output device
257
Eric Laurente552edb2014-03-10 17:42:56 -0700258 // handle input devices
259 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700260 SortedVector <audio_io_handle_t> inputs;
261
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700263 switch (state)
264 {
265 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700266 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700267 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700268 ALOGW("setDeviceConnectionState() device already connected: %d", device);
269 return INVALID_OPERATION;
270 }
François Gaffie53615e22015-03-19 09:24:12 +0100271 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700272 if (module == NULL) {
273 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
274 device);
275 return INVALID_OPERATION;
276 }
François Gaffie44481e72016-04-20 07:49:57 +0200277
278 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
279 // parameters on newly connected devices (instead of opening the inputs...)
280 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
281
Paul McLean9080a4c2015-06-18 08:24:02 -0700282 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200283 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
284 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700285 return INVALID_OPERATION;
286 }
287
Eric Laurent3a4311c2014-03-17 12:00:47 -0700288 index = mAvailableInputDevices.add(devDesc);
289 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800290 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700291 } else {
292 return NO_MEMORY;
293 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800294
François Gaffie2110e042015-03-24 08:41:51 +0100295 // Propagate device availability to Engine
296 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700297 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700298
299 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700300 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700302 ALOGW("setDeviceConnectionState() device not connected: %d", device);
303 return INVALID_OPERATION;
304 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700305
306 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
307
308 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200309 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700310
Paul McLean9080a4c2015-06-18 08:24:02 -0700311 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700312 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700313
François Gaffie2110e042015-03-24 08:41:51 +0100314 // Propagate device availability to Engine
315 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700316 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700317
318 default:
319 ALOGE("setDeviceConnectionState() invalid state: %x", state);
320 return BAD_VALUE;
321 }
322
Eric Laurentd4692962014-05-05 18:13:44 -0700323 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700324 // As the input device list can impact the output device selection, update
325 // getDeviceForStrategy() cache
326 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700327
Eric Laurent87ffa392015-05-22 10:32:38 -0700328 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700329 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
330 updateCallRouting(newDevice);
331 }
332
Eric Laurentd60560a2015-04-10 11:31:20 -0700333 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
334 cleanUpForDevice(devDesc);
335 }
336
Eric Laurentb52c1522014-05-20 11:27:36 -0700337 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700338 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700339 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700340
341 ALOGW("setDeviceConnectionState() invalid device: %x", device);
342 return BAD_VALUE;
343}
344
Eric Laurente0720872014-03-11 09:30:41 -0700345audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100346 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700347{
Eric Laurent634b7142016-04-20 13:48:02 -0700348 sp<DeviceDescriptor> devDesc =
349 mHwModules.getDeviceDescriptor(device, device_address, "",
350 (strlen(device_address) != 0)/*matchAddress*/);
351
352 if (devDesc == 0) {
353 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
354 device, device_address);
355 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
356 }
François Gaffie53615e22015-03-19 09:24:12 +0100357
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 DeviceVector *deviceVector;
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700362 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700363 deviceVector = &mAvailableInputDevices;
364 } else {
365 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
366 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700367 }
Eric Laurent634b7142016-04-20 13:48:02 -0700368
369 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
370 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800371}
372
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800373status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
374 const char *device_address,
375 const char *device_name)
376{
377 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700378 String8 reply;
379 AudioParameter param;
380 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381
382 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
383 device, device_address, device_name);
384
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800385 // connect/disconnect only 1 device at a time
386 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
387
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800388 // Check if the device is currently connected
389 sp<DeviceDescriptor> devDesc =
390 mHwModules.getDeviceDescriptor(device, device_address, device_name);
391 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
392 if (index < 0) {
393 // Nothing to do: device is not connected
394 return NO_ERROR;
395 }
396
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700397 // For offloaded A2DP, Hw modules may have the capability to
398 // configure codecs. Check if any of the loaded hw modules
399 // supports this.
400 // If supported, send a set parameter to configure A2DP codecs
401 // and return. No need to toggle device state.
402 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
403 reply = mpClientInterface->getParameters(
404 AUDIO_IO_HANDLE_NONE,
405 String8(AudioParameter::keyReconfigA2dpSupported));
406 AudioParameter repliedParameters(reply);
407 repliedParameters.getInt(
408 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
409 if (isReconfigA2dpSupported) {
410 const String8 key(AudioParameter::keyReconfigA2dp);
411 param.add(key, String8("true"));
412 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
413 return NO_ERROR;
414 }
415 }
416
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800417 // Toggle the device state: UNAVAILABLE -> AVAILABLE
418 // This will force reading again the device configuration
419 status = setDeviceConnectionState(device,
420 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
421 device_address, device_name);
422 if (status != NO_ERROR) {
423 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
424 status);
425 return status;
426 }
427
428 status = setDeviceConnectionState(device,
429 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
430 device_address, device_name);
431 if (status != NO_ERROR) {
432 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
433 status);
434 return status;
435 }
436
437 return NO_ERROR;
438}
439
Eric Laurentdc462862016-07-19 12:29:53 -0700440uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441{
442 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700443 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700444
Andy Hunga76c7de2016-12-13 19:14:31 -0800445 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700446 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700447 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800448 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700449 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
450
451 // release existing RX patch if any
452 if (mCallRxPatch != 0) {
453 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
454 mCallRxPatch.clear();
455 }
456 // release TX patch if any
457 if (mCallTxPatch != 0) {
458 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
459 mCallTxPatch.clear();
460 }
461
462 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
463 // via setOutputDevice() on primary output.
464 // Otherwise, create two audio patches for TX and RX path.
465 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700466 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700467 // If the TX device is also on the primary HW module, setOutputDevice() will take care
468 // of it due to legacy implementation. If not, create a patch.
469 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
470 == AUDIO_DEVICE_NONE) {
471 createTxPatch = true;
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700475 createTxPatch = true;
476 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700477 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
479 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700480
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 return muteWaitMs;
482}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700483
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800484sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
485 bool isRx, audio_devices_t device, uint32_t delayMs) {
486 struct audio_patch patch;
487 patch.num_sources = 1;
488 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700489
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800490 sp<DeviceDescriptor> txSourceDeviceDesc;
491 if (isRx) {
492 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
493 fillAudioPortConfigForDevice(
494 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
495 } else {
496 txSourceDeviceDesc = fillAudioPortConfigForDevice(
497 mAvailableInputDevices, device, &patch.sources[0]);
498 fillAudioPortConfigForDevice(
499 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
500 }
501
502 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
503 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
504 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
505 // request to reuse existing output stream if one is already opened to reach the target device
506 if (output != AUDIO_IO_HANDLE_NONE) {
507 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
508 ALOG_ASSERT(!outputDesc->isDuplicated(),
509 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
510 outputDesc->toAudioPortConfig(&patch.sources[1]);
511 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
512 patch.num_sources = 2;
513 }
514
515 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700516 // terminate active capture if on the same HW module as the call TX source device
517 // FIXME: would be better to refine to only inputs whose profile connects to the
518 // call TX device but this information is not in the audio patch and logic here must be
519 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800520 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800521 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
522 AudioSessionCollection activeSessions =
523 activeDesc->getAudioSessions(true /*activeOnly*/);
524 for (size_t j = 0; j < activeSessions.size(); j++) {
525 audio_session_t activeSession = activeSessions.keyAt(j);
526 stopInput(activeDesc->mIoHandle, activeSession);
527 releaseInput(activeDesc->mIoHandle, activeSession);
528 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700529 }
530 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700531 }
Eric Laurentdc462862016-07-19 12:29:53 -0700532
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800533 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
534 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
535 ALOGW_IF(status != NO_ERROR,
536 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
537 sp<AudioPatch> audioPatch;
538 if (status == NO_ERROR) {
539 audioPatch = new AudioPatch(&patch, mUidCached);
540 audioPatch->mAfPatchHandle = afPatchHandle;
541 audioPatch->mUid = mUidCached;
542 }
543 return audioPatch;
544}
545
546sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
547 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
548 DeviceVector deviceList = devices.getDevicesFromType(device);
549 ALOG_ASSERT(!deviceList.isEmpty(),
550 "%s() selected device type %#x is not in devices list", __func__, device);
551 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
552 deviceDesc->toAudioPortConfig(config);
553 return deviceDesc;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700554}
555
Eric Laurente0720872014-03-11 09:30:41 -0700556void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700557{
558 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100559 // store previous phone state for management of sonification strategy below
560 int oldState = mEngine->getPhoneState();
561
562 if (mEngine->setPhoneState(state) != NO_ERROR) {
563 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 return;
565 }
François Gaffie2110e042015-03-24 08:41:51 +0100566 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700567 // if leaving call state, handle special case of active streams
568 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700569 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700570 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800571 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700572 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700573 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800574
Eric Laurent63dea1d2015-07-02 17:10:28 -0700575 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800576 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700577 }
578
François Gaffie2110e042015-03-24 08:41:51 +0100579 /**
580 * Switching to or from incall state or switching between telephony and VoIP lead to force
581 * routing command.
582 */
583 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
584 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700585
586 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700587 checkA2dpSuspend();
588 checkOutputForAllStrategies();
589 updateDevicesAndOutputs();
590
Eric Laurente552edb2014-03-10 17:42:56 -0700591 int delayMs = 0;
592 if (isStateInCall(state)) {
593 nsecs_t sysTime = systemTime();
594 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700596 // mute media and sonification strategies and delay device switch by the largest
597 // latency of any output where either strategy is active.
598 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100599 if ((isStrategyActive(desc, STRATEGY_MEDIA,
600 SONIFICATION_HEADSET_MUSIC_DELAY,
601 sysTime) ||
602 isStrategyActive(desc, STRATEGY_SONIFICATION,
603 SONIFICATION_HEADSET_MUSIC_DELAY,
604 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700605 (delayMs < (int)desc->latency()*2)) {
606 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700607 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700608 setStrategyMute(STRATEGY_MEDIA, true, desc);
609 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700610 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700611 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
612 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700613 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
614 }
615 }
616
Eric Laurent87ffa392015-05-22 10:32:38 -0700617 if (hasPrimaryOutput()) {
618 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
619 // the device returned is not necessarily reachable via this output
620 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
621 // force routing command to audio hardware when ending call
622 // even if no device change is needed
623 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
624 rxDevice = mPrimaryOutput->device();
625 }
Eric Laurente552edb2014-03-10 17:42:56 -0700626
Eric Laurent87ffa392015-05-22 10:32:38 -0700627 if (state == AUDIO_MODE_IN_CALL) {
628 updateCallRouting(rxDevice, delayMs);
629 } else if (oldState == AUDIO_MODE_IN_CALL) {
630 if (mCallRxPatch != 0) {
631 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
632 mCallRxPatch.clear();
633 }
634 if (mCallTxPatch != 0) {
635 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
636 mCallTxPatch.clear();
637 }
638 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
639 } else {
640 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700641 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700642 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700643
644 // reevaluate routing on all outputs in case tracks have been started during the call
645 for (size_t i = 0; i < mOutputs.size(); i++) {
646 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
647 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
648 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800649 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700650 }
651 }
652
Eric Laurente552edb2014-03-10 17:42:56 -0700653 // if entering in call state, handle special case of active streams
654 // pertaining to sonification strategy see handleIncallSonification()
655 if (isStateInCall(state)) {
656 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800657 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700658 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700659 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700660
661 // force reevaluating accessibility routing when call starts
662 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700663 }
664
665 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700666 if (state == AUDIO_MODE_RINGTONE &&
667 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700668 mLimitRingtoneVolume = true;
669 } else {
670 mLimitRingtoneVolume = false;
671 }
672}
673
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700674audio_mode_t AudioPolicyManager::getPhoneState() {
675 return mEngine->getPhoneState();
676}
677
Eric Laurente0720872014-03-11 09:30:41 -0700678void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700679 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700680{
François Gaffie2110e042015-03-24 08:41:51 +0100681 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700682 if (config == mEngine->getForceUse(usage)) {
683 return;
684 }
Eric Laurente552edb2014-03-10 17:42:56 -0700685
François Gaffie2110e042015-03-24 08:41:51 +0100686 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
687 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
688 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700689 }
François Gaffie2110e042015-03-24 08:41:51 +0100690 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
691 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
692 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700693
694 // check for device and output changes triggered by new force usage
695 checkA2dpSuspend();
696 checkOutputForAllStrategies();
697 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800698
Eric Laurentdc462862016-07-19 12:29:53 -0700699 //FIXME: workaround for truncated touch sounds
700 // to be removed when the problem is handled by system UI
701 uint32_t delayMs = 0;
702 uint32_t waitMs = 0;
703 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
704 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
705 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700706 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700707 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700708 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 }
Eric Laurente552edb2014-03-10 17:42:56 -0700710 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700711 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
712 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
713 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700714 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
715 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700716 }
Eric Laurente552edb2014-03-10 17:42:56 -0700717 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700718 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700719 }
720 }
721
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800722 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800723 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700724 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800725 if (activeDesc->mProfile->getSupportedDevices().types() &
726 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
727 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700728 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800729 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700730 }
Eric Laurente552edb2014-03-10 17:42:56 -0700731 }
Eric Laurente552edb2014-03-10 17:42:56 -0700732}
733
Eric Laurente0720872014-03-11 09:30:41 -0700734void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700735{
736 ALOGV("setSystemProperty() property %s, value %s", property, value);
737}
738
739// Find a direct output profile compatible with the parameters passed, even if the input flags do
740// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800741sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700742 audio_devices_t device,
743 uint32_t samplingRate,
744 audio_format_t format,
745 audio_channel_mask_t channelMask,
746 audio_output_flags_t flags)
747{
Eric Laurent861a6282015-05-18 15:40:16 -0700748 // only retain flags that will drive the direct output profile selection
749 // if explicitly requested
750 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700751 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
752 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700753 flags =
754 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
755
756 sp<IOProfile> profile;
757
Mikhail Naganovd4120142017-12-06 15:49:22 -0800758 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800759 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700760 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700761 samplingRate, NULL /*updatedSamplingRate*/,
762 format, NULL /*updatedFormat*/,
763 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700764 flags)) {
765 continue;
766 }
767 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100768 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700769 continue;
770 }
771 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100772 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700773 continue;
774 }
775 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100776 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700777 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700778 }
Eric Laurente552edb2014-03-10 17:42:56 -0700779 }
780 }
Eric Laurent861a6282015-05-18 15:40:16 -0700781 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700782}
783
Eric Laurentf4e63452017-11-06 19:31:46 +0000784audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700785{
Eric Laurent3b73df72014-03-11 09:06:29 -0700786 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700787 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800788
789 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
790 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
791 // format, flags, etc. This may result in some discrepancy for functions that utilize
792 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
793 // and AudioSystem::getOutputSamplingRate().
794
Eric Laurentf4e63452017-11-06 19:31:46 +0000795 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
796 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700797
Eric Laurentf4e63452017-11-06 19:31:46 +0000798 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
799 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700800}
801
Eric Laurente83b55d2014-11-14 10:06:21 -0800802status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
803 audio_io_handle_t *output,
804 audio_session_t session,
805 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700806 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800807 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200808 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700809 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800810 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700811{
Eric Laurente83b55d2014-11-14 10:06:21 -0800812 audio_attributes_t attributes;
813 if (attr != NULL) {
814 if (!isValidAttributes(attr)) {
815 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
816 attr->usage, attr->content_type, attr->flags,
817 attr->tags);
818 return BAD_VALUE;
819 }
820 attributes = *attr;
821 } else {
822 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
823 ALOGE("getOutputForAttr(): invalid stream type");
824 return BAD_VALUE;
825 }
826 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700827 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800828
829 // TODO: check for existing client for this port ID
830 if (*portId == AUDIO_PORT_HANDLE_NONE) {
831 *portId = AudioPort::getNextUniqueId();
832 }
833
Eric Laurentc75307b2015-03-17 15:29:32 -0700834 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800835 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100836 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800837 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100838 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800839 }
François Gaffie036e1e92015-03-19 10:16:24 +0100840 *stream = streamTypefromAttributesInt(&attributes);
841 *output = desc->mIoHandle;
842 ALOGV("getOutputForAttr() returns output %d", *output);
843 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800844 }
845 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
846 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
847 return BAD_VALUE;
848 }
849
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700850 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
851 " session %d selectedDeviceId %d",
852 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700853 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700854
855 *stream = streamTypefromAttributesInt(&attributes);
856
857 // Explicit routing?
858 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700859 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800860 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700861 }
862 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863
Eric Laurente83b55d2014-11-14 10:06:21 -0800864 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700866
Eric Laurente83b55d2014-11-14 10:06:21 -0800867 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200868 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700869 }
870
Nadav Bar0d143ae2018-07-18 13:01:53 +0300871 // Set incall music only if device was explicitly set, and fallback to the device which is
872 // chosen by the engine if not.
873 // FIXME: provide a more generic approach which is not device specific and move this back
874 // to getOutputForDevice.
875 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
876 *stream == AUDIO_STREAM_MUSIC &&
877 audio_is_linear_pcm(config->format) &&
878 isInCall()) {
879 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
880 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
881 } else {
882 device = mEngine->getDeviceForStrategy(strategy);
883 }
884 }
885
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800886 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
887 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200888 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889
Andy Hungc88b0642018-04-27 15:42:35 -0700890 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800891 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700892 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 return INVALID_OPERATION;
894 }
Paul McLeanaa981192015-03-21 09:55:15 -0700895
Eric Laurent2ac76942017-06-22 17:17:09 -0700896 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
897 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
898 : AUDIO_PORT_HANDLE_NONE;
899
900 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
901
Eric Laurente83b55d2014-11-14 10:06:21 -0800902 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700903}
904
905audio_io_handle_t AudioPolicyManager::getOutputForDevice(
906 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800907 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700908 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800909 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200910 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700911{
Andy Hungc88b0642018-04-27 15:42:35 -0700912 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700913 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700914
Eric Laurente552edb2014-03-10 17:42:56 -0700915 // open a direct output if required by specified parameters
916 //force direct flag if offload flag is set: offloading implies a direct output stream
917 // and all common behaviors are driven by checking only the direct flag
918 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200919 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
920 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
Nadav Bar766fb022018-01-07 12:18:03 +0200922 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
923 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700924 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800925 // only allow deep buffering for music stream type
926 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200927 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700928 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200929 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700930 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
931 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200932 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800933 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700934 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200935 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700936 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800937 audio_is_linear_pcm(config->format)) {
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
996 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
997 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
998 : String8("");
999
Nadav Bar766fb022018-01-07 12:18:03 +02001000 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001001
1002 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001003 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001004 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001005 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001006 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1007 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1008 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1009 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1010 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001011 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001012 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001013 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001014 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001015 if (audio_is_linear_pcm(config->format) &&
1016 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001017 goto non_direct_output;
1018 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001020 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001021 outputDesc->mRefCount[stream] = 0;
1022 outputDesc->mStopTime[stream] = 0;
1023 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001024 outputDesc->mDirectClientSession = session;
1025
Eric Laurente552edb2014-03-10 17:42:56 -07001026 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001028 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001029 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001030 return output;
1031 }
1032
Eric Laurentb732cf52014-09-24 19:08:21 -07001033non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001034
1035 // A request for HW A/V sync cannot fallback to a mixed output because time
1036 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001037 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001038 return AUDIO_IO_HANDLE_NONE;
1039 }
1040
Eric Laurente552edb2014-03-10 17:42:56 -07001041 // ignoring channel mask due to downmix capability in mixer
1042
1043 // open a non direct output
1044
1045 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001046 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 // get which output is suitable for the specified stream. The actual
1048 // routing change will happen when startOutput() will be called
1049 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1050
Eric Laurent8838a382014-09-08 16:44:28 -07001051 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001052 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1053 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001055 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001056 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001057 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001058
Eric Laurente552edb2014-03-10 17:42:56 -07001059 return output;
1060}
1061
Eric Laurente0720872014-03-11 09:30:41 -07001062audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001063 audio_output_flags_t flags,
1064 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001065{
1066 // select one output among several that provide a path to a particular device or set of
1067 // devices (the list was previously build by getOutputsForDevice()).
1068 // The priority is as follows:
1069 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001070 // 2: the output with the bit depth the closest to the requested one
1071 // 3: the primary output
1072 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001073
1074 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001075 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 if (outputs.size() == 1) {
1078 return outputs[0];
1079 }
1080
1081 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001082 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1083 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1084 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001085 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1086 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001087
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001088 for (audio_io_handle_t output : outputs) {
1089 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001090 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001091 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1092 continue;
1093 }
Eric Laurent8838a382014-09-08 16:44:28 -07001094 // if a valid format is specified, skip output if not compatible
1095 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001096 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001097 continue;
1098 }
Eric Laurente6930022016-02-11 10:20:40 -08001099 if (AudioPort::isBetterFormatMatch(
1100 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001101 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001102 bestFormat = outputDesc->mFormat;
1103 }
Eric Laurent8838a382014-09-08 16:44:28 -07001104 }
1105
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001106 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001107 if (commonFlags >= maxCommonFlags) {
1108 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001109 if (format != AUDIO_FORMAT_INVALID
1110 && AudioPort::isBetterFormatMatch(
1111 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001112 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001113 bestFormatForFlags = outputDesc->mFormat;
1114 }
1115 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001116 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001117 maxCommonFlags = commonFlags;
1118 bestFormatForFlags = outputDesc->mFormat;
1119 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001120 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001121 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001122 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001123 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001124 }
1125 }
1126 }
1127
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001128 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001129 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001130 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001131 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001132 return outputForFormat;
1133 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001134 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001135 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001136 }
1137
1138 return outputs[0];
1139}
1140
Eric Laurente0720872014-03-11 09:30:41 -07001141status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001142 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001143 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001144{
Paul McLeanaa981192015-03-21 09:55:15 -07001145 ALOGV("startOutput() output %d, stream %d, session %d",
1146 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001147 ssize_t index = mOutputs.indexOfKey(output);
1148 if (index < 0) {
1149 ALOGW("startOutput() unknown output %d", output);
1150 return BAD_VALUE;
1151 }
1152
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1154
Eric Laurent733ce942017-12-07 12:18:25 -08001155 status_t status = outputDesc->start();
1156 if (status != NO_ERROR) {
1157 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001158 }
1159
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001160 // Routing?
1161 mOutputRoutes.incRouteActivity(session);
1162
Eric Laurentc75307b2015-03-17 15:29:32 -07001163 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001164 AudioMix *policyMix = NULL;
1165 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001167 policyMix = outputDesc->mPolicyMix;
1168 address = policyMix->mDeviceAddress.string();
1169 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1170 newDevice = policyMix->mDeviceType;
1171 } else {
1172 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1173 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001174 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001175 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001176 if (newDevice != outputDesc->device()) {
1177 checkStrategyRoute(getStrategy(stream), output);
1178 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001179 } else {
1180 newDevice = AUDIO_DEVICE_NONE;
1181 }
1182
1183 uint32_t delayMs = 0;
1184
Eric Laurent733ce942017-12-07 12:18:25 -08001185 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001186
1187 if (status != NO_ERROR) {
1188 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001189 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001190 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001191 }
1192 // Automatically enable the remote submix input when output is started on a re routing mix
1193 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001194 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1195 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001196 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1197 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001198 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001199 "remote-submix");
1200 }
1201
1202 if (delayMs != 0) {
1203 usleep(delayMs * 1000);
1204 }
1205
1206 return status;
1207}
1208
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001209status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001210 audio_stream_type_t stream,
1211 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001212 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001213 uint32_t *delayMs)
1214{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001215 // cannot start playback of STREAM_TTS if any other output is being used
1216 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001217
1218 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001219 if (stream == AUDIO_STREAM_TTS) {
1220 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001221 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001222 return INVALID_OPERATION;
1223 } else {
1224 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1225 }
1226 } else {
1227 // some playback other than beacon starts
1228 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1229 }
1230
Eric Laurent77305a62016-07-25 16:39:22 -07001231 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001232 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001233 bool force = !outputDesc->isActive() &&
1234 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001235
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001236 // requiresMuteCheck is false when we can bypass mute strategy.
1237 // It covers a common case when there is no materially active audio
1238 // and muting would result in unnecessary delay and dropped audio.
1239 const uint32_t outputLatencyMs = outputDesc->latency();
1240 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1241
Eric Laurente552edb2014-03-10 17:42:56 -07001242 // increment usage count for this stream on the requested output:
1243 // NOTE that the usage count is the same for duplicated output and hardware output which is
1244 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1245 outputDesc->changeRefCount(stream, 1);
1246
Eric Laurent36829f92017-04-07 19:04:42 -07001247 if (stream == AUDIO_STREAM_MUSIC) {
1248 selectOutputForMusicEffects();
1249 }
1250
Eric Laurent493404d2015-04-21 15:07:36 -07001251 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001252 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001253 if (device == AUDIO_DEVICE_NONE) {
1254 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001255 }
Eric Laurent36829f92017-04-07 19:04:42 -07001256
Eric Laurente552edb2014-03-10 17:42:56 -07001257 routing_strategy strategy = getStrategy(stream);
1258 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001259 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1260 (beaconMuteLatency > 0);
1261 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001262 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001263 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001264 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001265 // An output has a shared device if
1266 // - managed by the same hw module
1267 // - supports the currently selected device
1268 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1269 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1270
Eric Laurent77305a62016-07-25 16:39:22 -07001271 // force a device change if any other output is:
1272 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001273 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001274 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001275 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001276 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001277 // change the device currently selected by the other output.
1278 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001279 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001280 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001281 force = true;
1282 }
1283 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001284 // a notification so that audio focus effect can propagate, or that a mute/unmute
1285 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001286 const uint32_t latencyMs = desc->latency();
1287 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1288
1289 if (shouldWait && isActive && (waitMs < latencyMs)) {
1290 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001291 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001292
1293 // Require mute check if another output is on a shared device
1294 // and currently active to have proper drain and avoid pops.
1295 // Note restoring AudioTracks onto this output needs to invoke
1296 // a volume ramp if there is no mute.
1297 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001298 }
1299 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001300
1301 const uint32_t muteWaitMs =
1302 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001303
1304 // handle special case for sonification while in call
1305 if (isInCall()) {
1306 handleIncallSonification(stream, true, false);
1307 }
1308
1309 // apply volume rules for current stream and device if necessary
1310 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001311 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001312 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001313 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001314
1315 // update the outputs if starting an output with a stream that can affect notification
1316 // routing
1317 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001318
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001319 // force reevaluating accessibility routing when ringtone or alarm starts
1320 if (strategy == STRATEGY_SONIFICATION) {
1321 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1322 }
Eric Laurentdc462862016-07-19 12:29:53 -07001323
1324 if (waitMs > muteWaitMs) {
1325 *delayMs = waitMs - muteWaitMs;
1326 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001327
1328 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1329 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1330 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1331 // change occurs after the MixerThread starts and causes a stream volume
1332 // glitch.
1333 //
1334 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001335 }
Eric Laurentdc462862016-07-19 12:29:53 -07001336
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001337 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1338 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1339 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1340 }
1341
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001342 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1343 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1344 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1345 }
1346
Eric Laurente552edb2014-03-10 17:42:56 -07001347 return NO_ERROR;
1348}
1349
1350
Eric Laurente0720872014-03-11 09:30:41 -07001351status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001352 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001353 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001354{
1355 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1356 ssize_t index = mOutputs.indexOfKey(output);
1357 if (index < 0) {
1358 ALOGW("stopOutput() unknown output %d", output);
1359 return BAD_VALUE;
1360 }
1361
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001363
Eric Laurentc75307b2015-03-17 15:29:32 -07001364 if (outputDesc->mRefCount[stream] == 1) {
1365 // Automatically disable the remote submix input when output is stopped on a
1366 // re routing mix of type MIX_TYPE_RECORDERS
1367 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1368 outputDesc->mPolicyMix != NULL &&
1369 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1370 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1371 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001372 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 "remote-submix");
1374 }
1375 }
1376
1377 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001378 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001380 int activityCount = mOutputRoutes.decRouteActivity(session);
1381 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1382
1383 if (forceDeviceUpdate) {
1384 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1385 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 }
1387
Eric Laurent3974e3b2017-12-07 17:58:43 -08001388 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1389
Eric Laurent733ce942017-12-07 12:18:25 -08001390 if (status == NO_ERROR ) {
1391 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001392 }
1393 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001394}
1395
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001396status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001397 audio_stream_type_t stream,
1398 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001399{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001400 // always handle stream stop, check which stream type is stopping
1401 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1402
Eric Laurente552edb2014-03-10 17:42:56 -07001403 // handle special case for sonification while in call
1404 if (isInCall()) {
1405 handleIncallSonification(stream, false, false);
1406 }
1407
1408 if (outputDesc->mRefCount[stream] > 0) {
1409 // decrement usage count of this stream on the output
1410 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001411
Eric Laurente552edb2014-03-10 17:42:56 -07001412 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001413 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001414 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001416 // delay the device switch by twice the latency because stopOutput() is executed when
1417 // the track stop() command is received and at that time the audio track buffer can
1418 // still contain data that needs to be drained. The latency only covers the audio HAL
1419 // and kernel buffers. Also the latency does not always include additional delay in the
1420 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001421 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001422
1423 // force restoring the device selection on other active outputs if it differs from the
1424 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001425 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001426 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001428 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001429 desc->isActive() &&
1430 outputDesc->sharesHwModuleWith(desc) &&
1431 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001432 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1433 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001434
Eric Laurentc75307b2015-03-17 15:29:32 -07001435 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001436 newDevice2,
1437 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001438 delayMs);
1439 // re-apply device specific volume if not done by setOutputDevice()
1440 if (!force) {
1441 applyStreamVolumes(desc, newDevice2, delayMs);
1442 }
Eric Laurente552edb2014-03-10 17:42:56 -07001443 }
1444 }
1445 // update the outputs if stopping one with a stream that can affect notification routing
1446 handleNotificationRoutingForStream(stream);
1447 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001448
1449 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1450 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1451 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1452 }
1453
Eric Laurent36829f92017-04-07 19:04:42 -07001454 if (stream == AUDIO_STREAM_MUSIC) {
1455 selectOutputForMusicEffects();
1456 }
Eric Laurente552edb2014-03-10 17:42:56 -07001457 return NO_ERROR;
1458 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001459 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001460 return INVALID_OPERATION;
1461 }
1462}
1463
Eric Laurente83b55d2014-11-14 10:06:21 -08001464void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001465 audio_stream_type_t stream __unused,
1466 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001467{
1468 ALOGV("releaseOutput() %d", output);
1469 ssize_t index = mOutputs.indexOfKey(output);
1470 if (index < 0) {
1471 ALOGW("releaseOutput() releasing unknown output %d", output);
1472 return;
1473 }
1474
Paul McLeanaa981192015-03-21 09:55:15 -07001475 // Routing
1476 mOutputRoutes.removeRoute(session);
1477
Eric Laurentc75307b2015-03-17 15:29:32 -07001478 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001479 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001480 if (desc->mDirectOpenCount <= 0) {
1481 ALOGW("releaseOutput() invalid open count %d for output %d",
1482 desc->mDirectOpenCount, output);
1483 return;
1484 }
1485 if (--desc->mDirectOpenCount == 0) {
1486 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001487 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001488 }
1489 }
1490}
1491
1492
Eric Laurentcaf7f482014-11-25 17:50:47 -08001493status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1494 audio_io_handle_t *input,
1495 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001496 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001497 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001498 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001499 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001500 input_type_t *inputType,
1501 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001502{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001503 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001504 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001505 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001506
Eric Laurentad2e7b92017-09-14 20:06:42 -07001507 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001508 // handle legacy remote submix case where the address was not always specified
1509 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001510 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001511 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001512 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001513 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001514
Eric Laurentfe231122017-11-17 17:48:06 -08001515 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1516 inputSource = AUDIO_SOURCE_MIC;
1517 }
1518
Paul McLean466dc8e2015-04-17 13:15:36 -06001519 // Explicit routing?
1520 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001521 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001522 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001523 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001524 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001525
Eric Laurentad2e7b92017-09-14 20:06:42 -07001526 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1527 // possible
1528 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1529 *input != AUDIO_IO_HANDLE_NONE) {
1530 ssize_t index = mInputs.indexOfKey(*input);
1531 if (index < 0) {
1532 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1533 status = BAD_VALUE;
1534 goto error;
1535 }
1536 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1537 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1538 if (audioSession == 0) {
1539 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1540 status = BAD_VALUE;
1541 goto error;
1542 }
1543 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1544 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001545 // corresponds to a new client and is only permitted from the same UID.
1546 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001547 if (audioSession->openCount() == 1) {
1548 audioSession->setUid(uid);
1549 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001550 if (!audioSession->isSilenced()) {
1551 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1552 uid, session, audioSession->uid());
1553 status = INVALID_OPERATION;
1554 goto error;
1555 }
1556 audioSession->setUid(uid);
1557 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001558 }
1559 audioSession->changeOpenCount(1);
1560 *inputType = API_INPUT_LEGACY;
1561 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1562 *portId = AudioPort::getNextUniqueId();
1563 }
1564 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1565 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1566 : AUDIO_PORT_HANDLE_NONE;
1567 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1568
1569 return NO_ERROR;
1570 }
1571
1572 *input = AUDIO_IO_HANDLE_NONE;
1573 *inputType = API_INPUT_INVALID;
1574
Eric Laurentad2e7b92017-09-14 20:06:42 -07001575 halInputSource = inputSource;
1576
1577 // TODO: check for existing client for this port ID
1578 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1579 *portId = AudioPort::getNextUniqueId();
1580 }
1581
1582 audio_devices_t device;
1583
Eric Laurentc447ded2015-01-06 08:47:05 -08001584 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001585 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001586 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1587 if (status != NO_ERROR) {
1588 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001589 }
1590 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001591 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1592 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001593 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001594 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001595 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001596 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001597 status = BAD_VALUE;
1598 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001599 }
Eric Laurentc722f302014-12-10 11:21:49 -08001600 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001601 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001602 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1603 // there is an external policy, but this input is attached to a mix of recorders,
1604 // meaning it receives audio injected into the framework, so the recorder doesn't
1605 // know about it and is therefore considered "legacy"
1606 *inputType = API_INPUT_LEGACY;
1607 } else {
1608 // recording a mix of players defined by an external policy, we're rerouting for
1609 // an external policy
1610 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1611 }
Eric Laurentc722f302014-12-10 11:21:49 -08001612 } else if (audio_is_remote_submix_device(device)) {
1613 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001614 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001615 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1616 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001617 } else {
1618 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001619 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001620
Eric Laurent599c7582015-12-07 18:05:55 -08001621 }
1622
1623 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001624 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001625 policyMix);
1626 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001627 status = INVALID_OPERATION;
1628 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001629 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001630
Eric Laurentad2e7b92017-09-14 20:06:42 -07001631 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001632 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1633 : AUDIO_PORT_HANDLE_NONE;
1634
1635 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1636 *input, *inputType, *selectedDeviceId);
1637
Eric Laurent599c7582015-12-07 18:05:55 -08001638 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001639
1640error:
1641 mInputRoutes.removeRoute(session);
1642 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001643}
1644
1645
1646audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1647 String8 address,
1648 audio_session_t session,
1649 uid_t uid,
1650 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001651 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001652 audio_input_flags_t flags,
1653 AudioMix *policyMix)
1654{
1655 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1656 audio_source_t halInputSource = inputSource;
1657 bool isSoundTrigger = false;
1658
1659 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1660 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1661 if (index >= 0) {
1662 input = mSoundTriggerSessions.valueFor(session);
1663 isSoundTrigger = true;
1664 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1665 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1666 } else {
1667 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001668 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001669 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001670 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001671 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001672 }
1673
Andy Hungf129b032015-04-07 13:45:50 -07001674 // find a compatible input profile (not necessarily identical in parameters)
1675 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001676 // sampling rate and flags may be updated by getInputProfile
1677 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1678 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001679 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001680 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001681 audio_input_flags_t profileFlags = flags;
1682 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001683 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001684 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001685 profileSamplingRate, profileFormat, profileChannelMask,
1686 profileFlags);
1687 if (profile != 0) {
1688 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001689 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1690 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001691 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1692 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1693 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001694 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001695 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1696 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001697 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001698 }
Eric Laurente552edb2014-03-10 17:42:56 -07001699 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001700 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001701 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001702 if (samplingRate == 0) {
1703 samplingRate = profileSamplingRate;
1704 }
Eric Laurente552edb2014-03-10 17:42:56 -07001705
Eric Laurent322b4d22015-04-03 15:57:54 -07001706 if (profile->getModuleHandle() == 0) {
1707 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001708 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001709 }
1710
Eric Laurent599c7582015-12-07 18:05:55 -08001711 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001712 inputSource,
1713 config->format,
1714 samplingRate,
1715 config->channel_mask,
1716 flags,
1717 uid,
1718 isSoundTrigger,
1719 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001720
Eric Laurent74708e72017-04-07 17:13:42 -07001721// FIXME: disable concurrent capture until UI is ready
1722#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001723 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001724 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001725 for (size_t i = 0; i < mInputs.size(); i++) {
1726 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001727 // reuse input if:
1728 // - it shares the same profile
1729 // AND
1730 // - it is not a reroute submix input
1731 // AND
1732 // - it is: not used for sound trigger
1733 // OR
1734 // used for sound trigger and all clients use the same session ID
1735 //
1736 if ((profile == desc->mProfile) &&
1737 (isSoundTrigger == desc->isSoundTrigger()) &&
1738 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001739
1740 sp<AudioSession> as = desc->getAudioSession(session);
1741 if (as != 0) {
1742 // do not allow unmatching properties on same session
1743 if (as->matches(audioSession)) {
1744 as->changeOpenCount(1);
1745 } else {
1746 ALOGW("getInputForDevice() record with different attributes"
1747 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001748 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001749 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001750 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001751 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001752 }
Eric Laurentbb948092017-01-23 18:33:30 -08001753
Eric Laurent555530a2017-02-07 18:17:24 -08001754 // Reuse the already opened input stream on this profile if:
1755 // - the new capture source is background OR
1756 // - the path requested configurations match OR
1757 // - the new source priority is less than the highest source priority on this input
1758 // If the input stream cannot be reused, close it before opening a new stream
1759 // on the same profile for the new client so that the requested path configuration
1760 // can be selected.
1761 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001762 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001763 desc->mChannelMask != config->channel_mask ||
1764 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001765 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001766 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001767 reusedInputDesc = desc;
1768 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001769 } else {
1770 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001771 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1772 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001773 }
Eric Laurent599c7582015-12-07 18:05:55 -08001774 }
1775 }
Eric Laurent599c7582015-12-07 18:05:55 -08001776
Eric Laurent555530a2017-02-07 18:17:24 -08001777 if (reusedInputDesc != 0) {
1778 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1779 for (size_t j = 0; j < sessions.size(); j++) {
1780 audio_session_t currentSession = sessions.keyAt(j);
1781 stopInput(reusedInputDesc->mIoHandle, currentSession);
1782 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1783 }
1784 }
Eric Laurent74708e72017-04-07 17:13:42 -07001785#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001786
Eric Laurent3974e3b2017-12-07 17:58:43 -08001787 if (!profile->canOpenNewIo()) {
1788 return AUDIO_IO_HANDLE_NONE;
1789 }
1790
Eric Laurentfe231122017-11-17 17:48:06 -08001791 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001792
Eric Laurentfe231122017-11-17 17:48:06 -08001793 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1794 lConfig.sample_rate = profileSamplingRate;
1795 lConfig.channel_mask = profileChannelMask;
1796 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001797
Eric Laurent53b810e2017-12-10 17:25:10 -08001798 if (address == "") {
1799 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1800 // the inputs vector must be of size >= 1, but we don't want to crash here
1801 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1802 }
1803
Eric Laurentfe231122017-11-17 17:48:06 -08001804 status_t status = inputDesc->open(&lConfig, device, address,
1805 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001806
1807 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001808 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001809 (profileSamplingRate != lConfig.sample_rate) ||
1810 !audio_formats_match(profileFormat, lConfig.format) ||
1811 (profileChannelMask != lConfig.channel_mask)) {
1812 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001813 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001814 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001815 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001816 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001817 }
Eric Laurent599c7582015-12-07 18:05:55 -08001818 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001819 }
1820
Eric Laurentc722f302014-12-10 11:21:49 -08001821 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001822 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001823
Eric Laurent599c7582015-12-07 18:05:55 -08001824 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001825 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001826
Eric Laurent599c7582015-12-07 18:05:55 -08001827 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001828}
1829
Eric Laurentbb948092017-01-23 18:33:30 -08001830//static
1831bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1832{
1833 return (source == AUDIO_SOURCE_HOTWORD) ||
1834 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1835 (source == AUDIO_SOURCE_FM_TUNER);
1836}
1837
Eric Laurentfb66dd92016-01-28 18:32:03 -08001838bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1839 const sp<AudioSession>& audioSession)
1840{
1841 // Do not allow capture if an active voice call is using a software patch and
1842 // the call TX source device is on the same HW module.
1843 // FIXME: would be better to refine to only inputs whose profile connects to the
1844 // call TX device but this information is not in the audio patch
1845 if (mCallTxPatch != 0 &&
1846 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1847 return false;
1848 }
1849
1850 // starting concurrent capture is enabled if:
1851 // 1) capturing for re-routing
1852 // 2) capturing for HOTWORD source
1853 // 3) capturing for FM TUNER source
1854 // 3) All other active captures are either for re-routing or HOTWORD
1855
1856 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001857 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001858 return true;
1859 }
1860
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001861 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001862 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001863 !is_virtual_input_device(activeInput->mDevice)) {
1864 return false;
1865 }
1866 }
1867
1868 return true;
1869}
1870
Chris Thornton2b864642017-06-27 21:26:07 -07001871// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1872bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1873 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1874 bool soundTriggerSupportsConcurrentCapture = false;
1875 unsigned int numModules = 0;
1876 struct sound_trigger_module_descriptor* nModules = NULL;
1877
1878 status_t status = SoundTrigger::listModules(nModules, &numModules);
1879 if (status == NO_ERROR && numModules != 0) {
1880 nModules = (struct sound_trigger_module_descriptor*) calloc(
1881 numModules, sizeof(struct sound_trigger_module_descriptor));
1882 if (nModules == NULL) {
1883 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1884 // ram the next time this function is called.
1885 ALOGE("Failed to allocate buffer for module descriptors");
1886 return false;
1887 }
1888
1889 status = SoundTrigger::listModules(nModules, &numModules);
1890 if (status == NO_ERROR) {
1891 soundTriggerSupportsConcurrentCapture = true;
1892 for (size_t i = 0; i < numModules; ++i) {
1893 soundTriggerSupportsConcurrentCapture &=
1894 nModules[i].properties.concurrent_capture;
1895 }
1896 }
1897 free(nModules);
1898 }
1899 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1900 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1901 }
1902 return mSoundTriggerSupportsConcurrentCapture;
1903}
1904
Eric Laurentfb66dd92016-01-28 18:32:03 -08001905
Eric Laurent4dc68062014-07-28 17:26:49 -07001906status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001907 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001908 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001909 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001910{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001911
1912 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1913 input, session, silenced, *concurrency);
1914
Eric Laurentfb66dd92016-01-28 18:32:03 -08001915 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001916
Eric Laurente552edb2014-03-10 17:42:56 -07001917 ssize_t index = mInputs.indexOfKey(input);
1918 if (index < 0) {
1919 ALOGW("startInput() unknown input %d", input);
1920 return BAD_VALUE;
1921 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001922 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001923
Eric Laurent599c7582015-12-07 18:05:55 -08001924 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1925 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001926 ALOGW("startInput() unknown session %d on input %d", session, input);
1927 return BAD_VALUE;
1928 }
1929
Eric Laurent74708e72017-04-07 17:13:42 -07001930// FIXME: disable concurrent capture until UI is ready
1931#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001932 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1933 ALOGW("startInput(%d) failed: other input already started", input);
1934 return INVALID_OPERATION;
1935 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001936
Eric Laurentfb66dd92016-01-28 18:32:03 -08001937 if (isInCall()) {
1938 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1939 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001940 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001941 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001942 }
Eric Laurent74708e72017-04-07 17:13:42 -07001943#else
1944 if (!is_virtual_input_device(inputDesc->mDevice)) {
1945 if (mCallTxPatch != 0 &&
1946 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1947 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001948 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001949 return INVALID_OPERATION;
1950 }
1951
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001952 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001953
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001954 // If a UID is idle and records silence and another not silenced recording starts
1955 // from another UID (idle or active) we stop the current idle UID recording in
1956 // favor of the new one - "There can be only one" TM
1957 if (!silenced) {
1958 for (const auto& activeDesc : activeInputs) {
1959 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1960 activeDesc->getId() == inputDesc->getId()) {
1961 continue;
1962 }
1963
1964 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1965 true /*activeOnly*/);
1966 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1967 if (activeSession->isSilenced()) {
1968 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1969 audio_session_t activeSessionId = activeSession->session();
1970 stopInput(activeInput, activeSessionId);
1971 releaseInput(activeInput, activeSessionId);
1972 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1973 activeInputs = mInputs.getActiveInputs();
1974 }
1975 }
1976 }
1977
1978 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001979 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1980 activeDesc->getId() == inputDesc->getId()) {
1981 continue;
1982 }
1983
Eric Laurent74708e72017-04-07 17:13:42 -07001984 audio_source_t activeSource = activeDesc->inputSource(true);
1985 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1986 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1987 if (activeDesc->hasPreemptedSession(session)) {
1988 ALOGW("startInput(%d) failed for HOTWORD: "
1989 "other input %d already started for HOTWORD",
1990 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001991 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001992 return INVALID_OPERATION;
1993 }
1994 } else {
1995 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1996 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001997 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001998 return INVALID_OPERATION;
1999 }
2000 } else {
2001 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2002 ALOGW("startInput(%d) failed: other input %d already started",
2003 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002004 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002005 return INVALID_OPERATION;
2006 }
2007 }
2008 }
2009
Chris Thornton2b864642017-06-27 21:26:07 -07002010 // We only need to check if the sound trigger session supports concurrent capture if the
2011 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2012 // that's running.
2013 const bool allowConcurrentWithSoundTrigger =
2014 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2015
Eric Laurent74708e72017-04-07 17:13:42 -07002016 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002017 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002018 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2019 continue;
2020 }
2021
Eric Laurent74708e72017-04-07 17:13:42 -07002022 audio_source_t activeSource = activeDesc->inputSource(true);
2023 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2024 AudioSessionCollection activeSessions =
2025 activeDesc->getAudioSessions(true /*activeOnly*/);
2026 audio_session_t activeSession = activeSessions.keyAt(0);
2027 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2028 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002029 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002030 sessions.add(activeSession);
2031 inputDesc->setPreemptedSessions(sessions);
2032 stopInput(activeHandle, activeSession);
2033 releaseInput(activeHandle, activeSession);
2034 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2035 input, activeDesc->mIoHandle);
2036 }
2037 }
2038 }
2039#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002040
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002041 // Make sure we start with the correct silence state
2042 audioSession->setSilenced(silenced);
2043
Eric Laurent313d1e72016-01-29 09:56:57 -08002044 // increment activity count before calling getNewInputDevice() below as only active sessions
2045 // are considered for device selection
2046 audioSession->changeActiveCount(1);
2047
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002048 // Routing?
2049 mInputRoutes.incRouteActivity(session);
2050
Eric Laurent2157f5b2018-04-25 18:33:02 -07002051 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002052 // indicate active capture to sound trigger service if starting capture from a mic on
2053 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002054 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002055 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002056
Eric Laurent733ce942017-12-07 12:18:25 -08002057 status_t status = inputDesc->start();
2058 if (status != NO_ERROR) {
2059 mInputRoutes.decRouteActivity(session);
2060 audioSession->changeActiveCount(-1);
2061 return status;
2062 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002063
Eric Laurent733ce942017-12-07 12:18:25 -08002064 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002065 // if input maps to a dynamic policy with an activity listener, notify of state change
2066 if ((inputDesc->mPolicyMix != NULL)
2067 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2068 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2069 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002070 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002071
Eric Laurentf7c50102016-09-30 15:19:43 -07002072 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2073 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002074 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002075 SoundTrigger::setCaptureState(true);
2076 }
2077
2078 // automatically enable the remote submix output when input is started if not
2079 // used by a policy mix of type MIX_TYPE_RECORDERS
2080 // For remote submix (a virtual device), we open only one input per capture request.
2081 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2082 String8 address = String8("");
2083 if (inputDesc->mPolicyMix == NULL) {
2084 address = String8("0");
2085 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2086 address = inputDesc->mPolicyMix->mDeviceAddress;
2087 }
2088 if (address != "") {
2089 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2090 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2091 address, "remote-submix");
2092 }
Eric Laurentc722f302014-12-10 11:21:49 -08002093 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002094 }
Eric Laurente552edb2014-03-10 17:42:56 -07002095 }
2096
Eric Laurent599c7582015-12-07 18:05:55 -08002097 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002098
Eric Laurente552edb2014-03-10 17:42:56 -07002099 return NO_ERROR;
2100}
2101
Eric Laurent4dc68062014-07-28 17:26:49 -07002102status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2103 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002104{
2105 ALOGV("stopInput() input %d", input);
2106 ssize_t index = mInputs.indexOfKey(input);
2107 if (index < 0) {
2108 ALOGW("stopInput() unknown input %d", input);
2109 return BAD_VALUE;
2110 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002111 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002112
Eric Laurent599c7582015-12-07 18:05:55 -08002113 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002114 if (index < 0) {
2115 ALOGW("stopInput() unknown session %d on input %d", session, input);
2116 return BAD_VALUE;
2117 }
2118
Eric Laurent599c7582015-12-07 18:05:55 -08002119 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002120 ALOGW("stopInput() input %d already stopped", input);
2121 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002122 }
2123
Eric Laurent599c7582015-12-07 18:05:55 -08002124 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002125
2126 // Routing?
2127 mInputRoutes.decRouteActivity(session);
2128
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002129 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002130 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002131 if (inputDesc->isActive()) {
2132 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2133 } else {
2134 // if input maps to a dynamic policy with an activity listener, notify of state change
2135 if ((inputDesc->mPolicyMix != NULL)
2136 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2137 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2138 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002139 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002140
2141 // automatically disable the remote submix output when input is stopped if not
2142 // used by a policy mix of type MIX_TYPE_RECORDERS
2143 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2144 String8 address = String8("");
2145 if (inputDesc->mPolicyMix == NULL) {
2146 address = String8("0");
2147 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2148 address = inputDesc->mPolicyMix->mDeviceAddress;
2149 }
2150 if (address != "") {
2151 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2152 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2153 address, "remote-submix");
2154 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002155 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002156
Eric Laurentf7c50102016-09-30 15:19:43 -07002157 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002158 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002159
Eric Laurentf7c50102016-09-30 15:19:43 -07002160 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2161 // primary HW module
2162 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2163 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2164 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002165 SoundTrigger::setCaptureState(false);
2166 }
2167 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002168 }
Eric Laurente552edb2014-03-10 17:42:56 -07002169 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002170 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002171}
2172
Eric Laurent4dc68062014-07-28 17:26:49 -07002173void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2174 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002175{
2176 ALOGV("releaseInput() %d", input);
2177 ssize_t index = mInputs.indexOfKey(input);
2178 if (index < 0) {
2179 ALOGW("releaseInput() releasing unknown input %d", input);
2180 return;
2181 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002182
2183 // Routing
2184 mInputRoutes.removeRoute(session);
2185
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002186 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2187 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002188
Eric Laurent599c7582015-12-07 18:05:55 -08002189 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002190 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002191 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2192 return;
2193 }
Eric Laurent599c7582015-12-07 18:05:55 -08002194
2195 if (audioSession->openCount() == 0) {
2196 ALOGW("releaseInput() invalid open count %d on session %d",
2197 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002198 return;
2199 }
Eric Laurent599c7582015-12-07 18:05:55 -08002200
2201 if (audioSession->changeOpenCount(-1) == 0) {
2202 inputDesc->removeAudioSession(session);
2203 }
2204
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002205 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002206 ALOGV("releaseInput() exit > 0");
2207 return;
2208 }
2209
Eric Laurent05b90f82014-08-27 15:32:29 -07002210 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002211 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002212 ALOGV("releaseInput() exit");
2213}
2214
Eric Laurentd4692962014-05-05 18:13:44 -07002215void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002216 bool patchRemoved = false;
2217
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002218 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002219 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002220 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002221 if (patch_index >= 0) {
2222 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002223 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002224 mAudioPatches.removeItemsAt(patch_index);
2225 patchRemoved = true;
2226 }
Eric Laurentfe231122017-11-17 17:48:06 -08002227 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002228 }
jiabin829a00b2018-04-04 16:28:32 -07002229 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002230 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002231 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002232 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002233
2234 if (patchRemoved) {
2235 mpClientInterface->onAudioPatchListUpdate();
2236 }
Eric Laurentd4692962014-05-05 18:13:44 -07002237}
2238
Eric Laurente0720872014-03-11 09:30:41 -07002239void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002240 int indexMin,
2241 int indexMax)
2242{
2243 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002244 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002245
2246 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002247 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2248 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002249 continue;
2250 }
2251 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002252 }
Eric Laurente552edb2014-03-10 17:42:56 -07002253}
2254
Eric Laurente0720872014-03-11 09:30:41 -07002255status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002256 int index,
2257 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002258{
2259
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002260 // VOICE_CALL and BLUETOOTH_SCO stream have minVolumeIndex > 0 but
2261 // can be muted directly by an app that has MODIFY_PHONE_STATE permission.
Nadav Bar7c605f62017-12-25 00:01:52 +02002262 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
Tomoharu Kasahara63c15502019-01-23 12:42:04 +09002263 !((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
2264 index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002265 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002266 return BAD_VALUE;
2267 }
2268 if (!audio_is_output_device(device)) {
2269 return BAD_VALUE;
2270 }
2271
2272 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002273 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002274
Eric Laurent1fd372e2016-04-06 14:23:53 -07002275 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002276 stream, device, index);
2277
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002279 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2280 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002281 continue;
2282 }
2283 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2284 }
Eric Laurente552edb2014-03-10 17:42:56 -07002285
Eric Laurent1fd372e2016-04-06 14:23:53 -07002286 // update volume on all outputs and streams matching the following:
2287 // - The requested stream (or a stream matching for volume control) is active on the output
2288 // - The device (or devices) selected by the strategy corresponding to this stream includes
2289 // the requested device
2290 // - For non default requested device, currently selected device on the output is either the
2291 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002292 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2293 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002294 status_t status = NO_ERROR;
2295 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002297 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002298 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2299 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002300 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002301 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002302 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2303 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002304 continue;
2305 }
Eric Laurent794fde22016-03-11 09:50:45 -08002306 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002307 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2308 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002309 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2310 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002311 continue;
2312 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002313 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002314 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002315 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002316 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002317 } else {
2318 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002319 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002320 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002321
Eric Laurente76f29c2016-09-14 17:17:53 -07002322 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002323 //FIXME: workaround for truncated touch sounds
2324 // delayed volume change for system stream to be removed when the problem is
2325 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002326 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002327 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2328 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002329 if (volStatus != NO_ERROR) {
2330 status = volStatus;
2331 }
2332 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002333 }
Eric Laurente552edb2014-03-10 17:42:56 -07002334 }
2335 return status;
2336}
2337
Eric Laurente0720872014-03-11 09:30:41 -07002338status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002339 int *index,
2340 audio_devices_t device)
2341{
2342 if (index == NULL) {
2343 return BAD_VALUE;
2344 }
2345 if (!audio_is_output_device(device)) {
2346 return BAD_VALUE;
2347 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002348 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002349 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002350 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002351 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2352 }
François Gaffiedfd74092015-03-19 12:10:59 +01002353 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002354
François Gaffied1ab2bd2015-12-02 18:20:06 +01002355 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002356 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2357 return NO_ERROR;
2358}
2359
Eric Laurent36829f92017-04-07 19:04:42 -07002360audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002361{
2362 // select one output among several suitable for global effects.
2363 // The priority is as follows:
2364 // 1: An offloaded output. If the effect ends up not being offloadable,
2365 // AudioFlinger will invalidate the track and the offloaded output
2366 // will be closed causing the effect to be moved to a PCM output.
2367 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002368 // 3: The primary output
2369 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002370
Eric Laurent3b73df72014-03-11 09:06:29 -07002371 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002372 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002373 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002374
Eric Laurent36829f92017-04-07 19:04:42 -07002375 if (outputs.size() == 0) {
2376 return AUDIO_IO_HANDLE_NONE;
2377 }
Eric Laurente552edb2014-03-10 17:42:56 -07002378
Eric Laurent36829f92017-04-07 19:04:42 -07002379 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2380 bool activeOnly = true;
2381
2382 while (output == AUDIO_IO_HANDLE_NONE) {
2383 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2384 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2385 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2386
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002387 for (audio_io_handle_t output : outputs) {
2388 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002389 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2390 continue;
2391 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002392 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2393 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002394 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002395 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002396 }
2397 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002398 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002399 }
2400 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002401 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002402 }
2403 }
2404 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2405 output = outputOffloaded;
2406 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2407 output = outputDeepBuffer;
2408 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2409 output = outputPrimary;
2410 } else {
2411 output = outputs[0];
2412 }
2413 activeOnly = false;
2414 }
2415
2416 if (output != mMusicEffectOutput) {
2417 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2418 mMusicEffectOutput = output;
2419 }
2420
2421 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002422 return output;
2423}
2424
Eric Laurent36829f92017-04-07 19:04:42 -07002425audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2426{
2427 return selectOutputForMusicEffects();
2428}
2429
Eric Laurente0720872014-03-11 09:30:41 -07002430status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002431 audio_io_handle_t io,
2432 uint32_t strategy,
2433 int session,
2434 int id)
2435{
2436 ssize_t index = mOutputs.indexOfKey(io);
2437 if (index < 0) {
2438 index = mInputs.indexOfKey(io);
2439 if (index < 0) {
2440 ALOGW("registerEffect() unknown io %d", io);
2441 return INVALID_OPERATION;
2442 }
2443 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002444 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002445}
2446
Eric Laurentc75307b2015-03-17 15:29:32 -07002447bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2448{
Eric Laurent28d09f02016-03-08 10:43:05 -08002449 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002450 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2451 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002452 continue;
2453 }
2454 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2455 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002456 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002457}
2458
2459bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2460{
2461 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2462}
2463
Eric Laurente0720872014-03-11 09:30:41 -07002464bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002465{
2466 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002467 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002468 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002469 return true;
2470 }
2471 }
2472 return false;
2473}
2474
Eric Laurent275e8e92014-11-30 15:14:47 -08002475// Register a list of custom mixes with their attributes and format.
2476// When a mix is registered, corresponding input and output profiles are
2477// added to the remote submix hw module. The profile contains only the
2478// parameters (sampling rate, format...) specified by the mix.
2479// The corresponding input remote submix device is also connected.
2480//
2481// When a remote submix device is connected, the address is checked to select the
2482// appropriate profile and the corresponding input or output stream is opened.
2483//
2484// When capture starts, getInputForAttr() will:
2485// - 1 look for a mix matching the address passed in attribtutes tags if any
2486// - 2 if none found, getDeviceForInputSource() will:
2487// - 2.1 look for a mix matching the attributes source
2488// - 2.2 if none found, default to device selection by policy rules
2489// At this time, the corresponding output remote submix device is also connected
2490// and active playback use cases can be transferred to this mix if needed when reconnecting
2491// after AudioTracks are invalidated
2492//
2493// When playback starts, getOutputForAttr() will:
2494// - 1 look for a mix matching the address passed in attribtutes tags if any
2495// - 2 if none found, look for a mix matching the attributes usage
2496// - 3 if none found, default to device and output selection by policy rules.
2497
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002498status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002499{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002500 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2501 status_t res = NO_ERROR;
2502
2503 sp<HwModule> rSubmixModule;
2504 // examine each mix's route type
2505 for (size_t i = 0; i < mixes.size(); i++) {
2506 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2507 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2508 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002509 break;
2510 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002511 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002513 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002514 rSubmixModule = mHwModules.getModuleFromName(
2515 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2516 if (rSubmixModule == 0) {
2517 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2518 i);
2519 res = INVALID_OPERATION;
2520 break;
2521 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002523
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002525
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 res = INVALID_OPERATION;
2529 break;
2530 }
2531 audio_config_t outputConfig = mixes[i].mFormat;
2532 audio_config_t inputConfig = mixes[i].mFormat;
2533 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2534 // stereo and let audio flinger do the channel conversion if needed.
2535 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2536 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2537 rSubmixModule->addOutputProfile(address, &outputConfig,
2538 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2539 rSubmixModule->addInputProfile(address, &inputConfig,
2540 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002541
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002542 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2543 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2544 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2545 address.string(), "remote-submix");
2546 } else {
2547 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2548 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2549 address.string(), "remote-submix");
2550 }
2551 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002554 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2555 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002557 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002558 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2560 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2561 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2562 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2563 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002564 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2565 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2567 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002568 } else {
2569 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 }
2571 break;
2572 }
2573 }
2574
2575 if (res != NO_ERROR) {
2576 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002577 i, device, address.string());
2578 res = INVALID_OPERATION;
2579 break;
2580 } else if (!foundOutput) {
2581 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2582 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 res = INVALID_OPERATION;
2584 break;
2585 }
Eric Laurentc722f302014-12-10 11:21:49 -08002586 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002587 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 if (res != NO_ERROR) {
2589 unregisterPolicyMixes(mixes);
2590 }
2591 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002592}
2593
2594status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2595{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002596 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002597 status_t res = NO_ERROR;
2598 sp<HwModule> rSubmixModule;
2599 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002600 for (const auto& mix : mixes) {
2601 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002602
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002604 rSubmixModule = mHwModules.getModuleFromName(
2605 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2606 if (rSubmixModule == 0) {
2607 res = INVALID_OPERATION;
2608 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 }
2610 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002611
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002612 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002613
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002614 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2615 res = INVALID_OPERATION;
2616 continue;
2617 }
2618
2619 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2620 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2621 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2622 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2623 address.string(), "remote-submix");
2624 }
2625 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2627 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2628 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2629 address.string(), "remote-submix");
2630 }
2631 rSubmixModule->removeOutputProfile(address);
2632 rSubmixModule->removeInputProfile(address);
2633
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002634 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2635 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002636 res = INVALID_OPERATION;
2637 continue;
2638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002639 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002640 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002641 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002642}
2643
Eric Laurente552edb2014-03-10 17:42:56 -07002644
Eric Laurente0720872014-03-11 09:30:41 -07002645status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002646{
2647 const size_t SIZE = 256;
2648 char buffer[SIZE];
2649 String8 result;
2650
2651 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2652 result.append(buffer);
2653
Eric Laurent87ffa392015-05-22 10:32:38 -07002654 snprintf(buffer, SIZE, " Primary Output: %d\n",
2655 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002656 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002657 std::string stateLiteral;
2658 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2659 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002660 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002661 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002662 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002663 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002664 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002665 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002666 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002667 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002668 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002669 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002670 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002671 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002672 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002673 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002674 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002675 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2676 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2677 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002678 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2679 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002680 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2681 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002682
François Gaffie2110e042015-03-24 08:41:51 +01002683 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002684
François Gaffie112b0af2015-11-19 16:13:25 +01002685 mAvailableOutputDevices.dump(fd, String8("Available output"));
2686 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002687 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002688 mOutputs.dump(fd);
2689 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002690 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002691 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002692 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002693 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002694
2695 return NO_ERROR;
2696}
2697
2698// This function checks for the parameters which can be offloaded.
2699// This can be enhanced depending on the capability of the DSP and policy
2700// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002701bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002702{
2703 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002704 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002705 offloadInfo.sample_rate, offloadInfo.channel_mask,
2706 offloadInfo.format,
2707 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2708 offloadInfo.has_video);
2709
Andy Hung2ddee192015-12-18 17:34:44 -08002710 if (mMasterMono) {
2711 return false; // no offloading if mono is set.
2712 }
2713
Eric Laurente552edb2014-03-10 17:42:56 -07002714 // Check if offload has been disabled
2715 char propValue[PROPERTY_VALUE_MAX];
2716 if (property_get("audio.offload.disable", propValue, "0")) {
2717 if (atoi(propValue) != 0) {
2718 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2719 return false;
2720 }
2721 }
2722
2723 // Check if stream type is music, then only allow offload as of now.
2724 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2725 {
2726 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2727 return false;
2728 }
2729
2730 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002731 const bool allowOffloadWithVideo =
2732 property_get_bool("audio.offload.video", false /* default_value */);
2733 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002734 ALOGV("isOffloadSupported: has_video == true, returning false");
2735 return false;
2736 }
2737
2738 //If duration is less than minimum value defined in property, return false
2739 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2740 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2741 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2742 return false;
2743 }
2744 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2745 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2746 return false;
2747 }
2748
2749 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2750 // creating an offloaded track and tearing it down immediately after start when audioflinger
2751 // detects there is an active non offloadable effect.
2752 // FIXME: We should check the audio session here but we do not have it in this context.
2753 // This may prevent offloading in rare situations where effects are left active by apps
2754 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002755 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002756 return false;
2757 }
2758
2759 // See if there is a profile to support this.
2760 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002761 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002762 offloadInfo.sample_rate,
2763 offloadInfo.format,
2764 offloadInfo.channel_mask,
2765 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002766 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2767 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002768}
2769
Eric Laurent6a94d692014-05-20 11:18:06 -07002770status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2771 audio_port_type_t type,
2772 unsigned int *num_ports,
2773 struct audio_port *ports,
2774 unsigned int *generation)
2775{
2776 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2777 generation == NULL) {
2778 return BAD_VALUE;
2779 }
2780 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2781 if (ports == NULL) {
2782 *num_ports = 0;
2783 }
2784
2785 size_t portsWritten = 0;
2786 size_t portsMax = *num_ports;
2787 *num_ports = 0;
2788 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002789 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2790 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002791 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002792 for (const auto& dev : mAvailableOutputDevices) {
2793 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002794 continue;
2795 }
2796 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002797 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002798 }
2799 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002800 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002801 }
2802 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002803 for (const auto& dev : mAvailableInputDevices) {
2804 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002805 continue;
2806 }
2807 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002808 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002809 }
2810 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002811 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 }
2813 }
2814 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2815 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2816 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2817 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2818 }
2819 *num_ports += mInputs.size();
2820 }
2821 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002822 size_t numOutputs = 0;
2823 for (size_t i = 0; i < mOutputs.size(); i++) {
2824 if (!mOutputs[i]->isDuplicated()) {
2825 numOutputs++;
2826 if (portsWritten < portsMax) {
2827 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2828 }
2829 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002830 }
Eric Laurent84c70242014-06-23 08:46:27 -07002831 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 }
2833 }
2834 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002835 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002836 return NO_ERROR;
2837}
2838
Eric Laurent99fcae42018-05-17 16:59:18 -07002839status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002840{
Eric Laurent99fcae42018-05-17 16:59:18 -07002841 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2842 return BAD_VALUE;
2843 }
2844 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2845 if (dev != 0) {
2846 dev->toAudioPort(port);
2847 return NO_ERROR;
2848 }
2849 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2850 if (dev != 0) {
2851 dev->toAudioPort(port);
2852 return NO_ERROR;
2853 }
2854 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2855 if (out != 0) {
2856 out->toAudioPort(port);
2857 return NO_ERROR;
2858 }
2859 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2860 if (in != 0) {
2861 in->toAudioPort(port);
2862 return NO_ERROR;
2863 }
2864 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002865}
2866
Eric Laurent6a94d692014-05-20 11:18:06 -07002867status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2868 audio_patch_handle_t *handle,
2869 uid_t uid)
2870{
2871 ALOGV("createAudioPatch()");
2872
2873 if (handle == NULL || patch == NULL) {
2874 return BAD_VALUE;
2875 }
2876 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2877
Eric Laurent874c42872014-08-08 15:13:39 -07002878 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2879 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2880 return BAD_VALUE;
2881 }
2882 // only one source per audio patch supported for now
2883 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 return INVALID_OPERATION;
2885 }
Eric Laurent874c42872014-08-08 15:13:39 -07002886
2887 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002888 return INVALID_OPERATION;
2889 }
Eric Laurent874c42872014-08-08 15:13:39 -07002890 for (size_t i = 0; i < patch->num_sinks; i++) {
2891 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2892 return INVALID_OPERATION;
2893 }
2894 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002895
2896 sp<AudioPatch> patchDesc;
2897 ssize_t index = mAudioPatches.indexOfKey(*handle);
2898
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2900 patch->sources[0].role,
2901 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002902#if LOG_NDEBUG == 0
2903 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002904 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002905 patch->sinks[i].role,
2906 patch->sinks[i].type);
2907 }
2908#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002909
2910 if (index >= 0) {
2911 patchDesc = mAudioPatches.valueAt(index);
2912 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2913 mUidCached, patchDesc->mUid, uid);
2914 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2915 return INVALID_OPERATION;
2916 }
2917 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002918 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 }
2920
2921 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002922 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 if (outputDesc == NULL) {
2924 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2925 return BAD_VALUE;
2926 }
Eric Laurent84c70242014-06-23 08:46:27 -07002927 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2928 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 if (patchDesc != 0) {
2930 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2931 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2932 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2933 return BAD_VALUE;
2934 }
2935 }
Eric Laurent874c42872014-08-08 15:13:39 -07002936 DeviceVector devices;
2937 for (size_t i = 0; i < patch->num_sinks; i++) {
2938 // Only support mix to devices connection
2939 // TODO add support for mix to mix connection
2940 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2941 ALOGV("createAudioPatch() source mix but sink is not a device");
2942 return INVALID_OPERATION;
2943 }
2944 sp<DeviceDescriptor> devDesc =
2945 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2946 if (devDesc == 0) {
2947 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2948 return BAD_VALUE;
2949 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002950
François Gaffie53615e22015-03-19 09:24:12 +01002951 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002952 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002953 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002954 NULL, // updatedSamplingRate
2955 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002956 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002957 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002958 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002959 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002960 ALOGV("createAudioPatch() profile not supported for device %08x",
2961 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002962 return INVALID_OPERATION;
2963 }
2964 devices.add(devDesc);
2965 }
2966 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002967 return INVALID_OPERATION;
2968 }
Eric Laurent874c42872014-08-08 15:13:39 -07002969
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 // TODO: reconfigure output format and channels here
2971 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002972 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002973 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 index = mAudioPatches.indexOfKey(*handle);
2975 if (index >= 0) {
2976 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2977 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2978 }
2979 patchDesc = mAudioPatches.valueAt(index);
2980 patchDesc->mUid = uid;
2981 ALOGV("createAudioPatch() success");
2982 } else {
2983 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2984 return INVALID_OPERATION;
2985 }
2986 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2987 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2988 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002989 // only one sink supported when connecting an input device to a mix
2990 if (patch->num_sinks > 1) {
2991 return INVALID_OPERATION;
2992 }
François Gaffie53615e22015-03-19 09:24:12 +01002993 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002994 if (inputDesc == NULL) {
2995 return BAD_VALUE;
2996 }
2997 if (patchDesc != 0) {
2998 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2999 return BAD_VALUE;
3000 }
3001 }
3002 sp<DeviceDescriptor> devDesc =
3003 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3004 if (devDesc == 0) {
3005 return BAD_VALUE;
3006 }
3007
François Gaffie53615e22015-03-19 09:24:12 +01003008 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003009 devDesc->mAddress,
3010 patch->sinks[0].sample_rate,
3011 NULL, /*updatedSampleRate*/
3012 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003013 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003014 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003015 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003016 // FIXME for the parameter type,
3017 // and the NONE
3018 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003019 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 return INVALID_OPERATION;
3021 }
3022 // TODO: reconfigure output format and channels here
3023 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003024 devDesc->type(), inputDesc->mIoHandle);
3025 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 index = mAudioPatches.indexOfKey(*handle);
3027 if (index >= 0) {
3028 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3029 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3030 }
3031 patchDesc = mAudioPatches.valueAt(index);
3032 patchDesc->mUid = uid;
3033 ALOGV("createAudioPatch() success");
3034 } else {
3035 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3036 return INVALID_OPERATION;
3037 }
3038 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3039 // device to device connection
3040 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003041 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 return BAD_VALUE;
3043 }
3044 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 sp<DeviceDescriptor> srcDeviceDesc =
3046 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003047 if (srcDeviceDesc == 0) {
3048 return BAD_VALUE;
3049 }
Eric Laurent874c42872014-08-08 15:13:39 -07003050
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 //update source and sink with our own data as the data passed in the patch may
3052 // be incomplete.
3053 struct audio_patch newPatch = *patch;
3054 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003055
Eric Laurent874c42872014-08-08 15:13:39 -07003056 for (size_t i = 0; i < patch->num_sinks; i++) {
3057 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3058 ALOGV("createAudioPatch() source device but one sink is not a device");
3059 return INVALID_OPERATION;
3060 }
3061
3062 sp<DeviceDescriptor> sinkDeviceDesc =
3063 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3064 if (sinkDeviceDesc == 0) {
3065 return BAD_VALUE;
3066 }
3067 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3068
Eric Laurent3bcf8592015-04-03 12:13:24 -07003069 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003070 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003071 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003072 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003073 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003074 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003075 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003076 return INVALID_OPERATION;
3077 }
Eric Laurent874c42872014-08-08 15:13:39 -07003078 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003079 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003080 // if the sink device is reachable via an opened output stream, request to go via
3081 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003082 audio_io_handle_t output = selectOutput(outputs,
3083 AUDIO_OUTPUT_FLAG_NONE,
3084 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003085 if (output != AUDIO_IO_HANDLE_NONE) {
3086 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3087 if (outputDesc->isDuplicated()) {
3088 return INVALID_OPERATION;
3089 }
3090 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003091 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003092 newPatch.num_sources = 2;
3093 }
Eric Laurent83b88082014-06-20 18:31:16 -07003094 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003095 }
3096 // TODO: check from routing capabilities in config file and other conflicting patches
3097
3098 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3099 if (index >= 0) {
3100 afPatchHandle = patchDesc->mAfPatchHandle;
3101 }
3102
3103 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3104 &afPatchHandle,
3105 0);
3106 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3107 status, afPatchHandle);
3108 if (status == NO_ERROR) {
3109 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003110 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 addAudioPatch(patchDesc->mHandle, patchDesc);
3112 } else {
3113 patchDesc->mPatch = newPatch;
3114 }
3115 patchDesc->mAfPatchHandle = afPatchHandle;
3116 *handle = patchDesc->mHandle;
3117 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003118 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003119 } else {
3120 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3121 status);
3122 return INVALID_OPERATION;
3123 }
3124 } else {
3125 return BAD_VALUE;
3126 }
3127 } else {
3128 return BAD_VALUE;
3129 }
3130 return NO_ERROR;
3131}
3132
3133status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3134 uid_t uid)
3135{
3136 ALOGV("releaseAudioPatch() patch %d", handle);
3137
3138 ssize_t index = mAudioPatches.indexOfKey(handle);
3139
3140 if (index < 0) {
3141 return BAD_VALUE;
3142 }
3143 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3144 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3145 mUidCached, patchDesc->mUid, uid);
3146 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3147 return INVALID_OPERATION;
3148 }
3149
3150 struct audio_patch *patch = &patchDesc->mPatch;
3151 patchDesc->mUid = mUidCached;
3152 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003154 if (outputDesc == NULL) {
3155 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3156 return BAD_VALUE;
3157 }
3158
Eric Laurentc75307b2015-03-17 15:29:32 -07003159 setOutputDevice(outputDesc,
3160 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003161 true,
3162 0,
3163 NULL);
3164 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3165 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003166 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167 if (inputDesc == NULL) {
3168 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3169 return BAD_VALUE;
3170 }
3171 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003172 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003173 true,
3174 NULL);
3175 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3177 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3178 status, patchDesc->mAfPatchHandle);
3179 removeAudioPatch(patchDesc->mHandle);
3180 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003181 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003182 } else {
3183 return BAD_VALUE;
3184 }
3185 } else {
3186 return BAD_VALUE;
3187 }
3188 return NO_ERROR;
3189}
3190
3191status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3192 struct audio_patch *patches,
3193 unsigned int *generation)
3194{
François Gaffie53615e22015-03-19 09:24:12 +01003195 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 return BAD_VALUE;
3197 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003198 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003199 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003200}
3201
Eric Laurente1715a42014-05-20 11:30:42 -07003202status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003203{
Eric Laurente1715a42014-05-20 11:30:42 -07003204 ALOGV("setAudioPortConfig()");
3205
3206 if (config == NULL) {
3207 return BAD_VALUE;
3208 }
3209 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3210 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003211 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3212 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003213 }
3214
Eric Laurenta121f902014-06-03 13:32:54 -07003215 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003216 if (config->type == AUDIO_PORT_TYPE_MIX) {
3217 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003218 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003219 if (outputDesc == NULL) {
3220 return BAD_VALUE;
3221 }
Eric Laurent84c70242014-06-23 08:46:27 -07003222 ALOG_ASSERT(!outputDesc->isDuplicated(),
3223 "setAudioPortConfig() called on duplicated output %d",
3224 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003225 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003226 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003227 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003228 if (inputDesc == NULL) {
3229 return BAD_VALUE;
3230 }
Eric Laurenta121f902014-06-03 13:32:54 -07003231 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003232 } else {
3233 return BAD_VALUE;
3234 }
3235 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3236 sp<DeviceDescriptor> deviceDesc;
3237 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3238 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3239 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3240 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3241 } else {
3242 return BAD_VALUE;
3243 }
3244 if (deviceDesc == NULL) {
3245 return BAD_VALUE;
3246 }
Eric Laurenta121f902014-06-03 13:32:54 -07003247 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003248 } else {
3249 return BAD_VALUE;
3250 }
3251
Eric Laurenta121f902014-06-03 13:32:54 -07003252 struct audio_port_config backupConfig;
3253 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3254 if (status == NO_ERROR) {
3255 struct audio_port_config newConfig;
3256 audioPortConfig->toAudioPortConfig(&newConfig, config);
3257 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003258 }
Eric Laurenta121f902014-06-03 13:32:54 -07003259 if (status != NO_ERROR) {
3260 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003261 }
Eric Laurente1715a42014-05-20 11:30:42 -07003262
3263 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003264}
3265
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003266void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3267{
Eric Laurentd60560a2015-04-10 11:31:20 -07003268 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003269 clearAudioPatches(uid);
3270 clearSessionRoutes(uid);
3271}
3272
Eric Laurent6a94d692014-05-20 11:18:06 -07003273void AudioPolicyManager::clearAudioPatches(uid_t uid)
3274{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003275 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003276 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3277 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003278 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003279 }
3280 }
3281}
3282
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003283void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3284 audio_io_handle_t ouptutToSkip)
3285{
3286 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3287 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3288 for (size_t j = 0; j < mOutputs.size(); j++) {
3289 if (mOutputs.keyAt(j) == ouptutToSkip) {
3290 continue;
3291 }
3292 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3293 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3294 continue;
3295 }
3296 // If the default device for this strategy is on another output mix,
3297 // invalidate all tracks in this strategy to force re connection.
3298 // Otherwise select new device on the output mix.
3299 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003300 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003301 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3302 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3303 }
3304 }
3305 } else {
3306 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3307 setOutputDevice(outputDesc, newDevice, false);
3308 }
3309 }
3310}
3311
3312void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3313{
3314 // remove output routes associated with this uid
3315 SortedVector<routing_strategy> affectedStrategies;
3316 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3317 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3318 if (route->mUid == uid) {
3319 mOutputRoutes.removeItemsAt(i);
3320 if (route->mDeviceDescriptor != 0) {
3321 affectedStrategies.add(getStrategy(route->mStreamType));
3322 }
3323 }
3324 }
3325 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003326 for (const auto& strategy : affectedStrategies) {
3327 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003328 }
3329
3330 // remove input routes associated with this uid
3331 SortedVector<audio_source_t> affectedSources;
3332 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3333 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3334 if (route->mUid == uid) {
3335 mInputRoutes.removeItemsAt(i);
3336 if (route->mDeviceDescriptor != 0) {
3337 affectedSources.add(route->mSource);
3338 }
3339 }
3340 }
3341 // reroute inputs if necessary
3342 SortedVector<audio_io_handle_t> inputsToClose;
3343 for (size_t i = 0; i < mInputs.size(); i++) {
3344 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003345 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003346 inputsToClose.add(inputDesc->mIoHandle);
3347 }
3348 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003349 for (const auto& input : inputsToClose) {
3350 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003351 }
3352}
3353
Eric Laurentd60560a2015-04-10 11:31:20 -07003354void AudioPolicyManager::clearAudioSources(uid_t uid)
3355{
3356 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3357 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3358 if (sourceDesc->mUid == uid) {
3359 stopAudioSource(mAudioSources.keyAt(i));
3360 }
3361 }
3362}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003363
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003364status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3365 audio_io_handle_t *ioHandle,
3366 audio_devices_t *device)
3367{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003368 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3369 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003370 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003371
François Gaffiedf372692015-03-19 10:43:27 +01003372 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003373}
3374
Eric Laurentd60560a2015-04-10 11:31:20 -07003375status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3376 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003377 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003378 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003379{
Eric Laurentd60560a2015-04-10 11:31:20 -07003380 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3381 if (source == NULL || attributes == NULL || handle == NULL) {
3382 return BAD_VALUE;
3383 }
3384
Glenn Kasten559d4392016-03-29 13:42:57 -07003385 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003386
3387 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3388 source->type != AUDIO_PORT_TYPE_DEVICE) {
3389 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3390 return INVALID_OPERATION;
3391 }
3392
3393 sp<DeviceDescriptor> srcDeviceDesc =
3394 mAvailableInputDevices.getDevice(source->ext.device.type,
3395 String8(source->ext.device.address));
3396 if (srcDeviceDesc == 0) {
3397 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3398 return BAD_VALUE;
3399 }
3400 sp<AudioSourceDescriptor> sourceDesc =
3401 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3402
3403 struct audio_patch dummyPatch;
3404 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3405 sourceDesc->mPatchDesc = patchDesc;
3406
3407 status_t status = connectAudioSource(sourceDesc);
3408 if (status == NO_ERROR) {
3409 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3410 *handle = sourceDesc->getHandle();
3411 }
3412 return status;
3413}
3414
3415status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3416{
3417 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3418
3419 // make sure we only have one patch per source.
3420 disconnectAudioSource(sourceDesc);
3421
3422 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003423 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003424 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3425
3426 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3427 sp<DeviceDescriptor> sinkDeviceDesc =
3428 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3429
3430 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3431 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3432
3433 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3434 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003435 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003436 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3437 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3438 // create patch between src device and output device
3439 // create Hwoutput and add to mHwOutputs
3440 } else {
3441 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3442 audio_io_handle_t output =
3443 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3444 if (output == AUDIO_IO_HANDLE_NONE) {
3445 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3446 return INVALID_OPERATION;
3447 }
3448 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3449 if (outputDesc->isDuplicated()) {
3450 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3451 return INVALID_OPERATION;
3452 }
Eric Laurent733ce942017-12-07 12:18:25 -08003453 status_t status = outputDesc->start();
3454 if (status != NO_ERROR) {
3455 return status;
3456 }
3457
Eric Laurentd60560a2015-04-10 11:31:20 -07003458 // create a special patch with no sink and two sources:
3459 // - the second source indicates to PatchPanel through which output mix this patch should
3460 // be connected as well as the stream type for volume control
3461 // - the sink is defined by whatever output device is currently selected for the output
3462 // though which this patch is routed.
3463 patch->num_sinks = 0;
3464 patch->num_sources = 2;
3465 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3466 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3467 patch->sources[1].ext.mix.usecase.stream = stream;
Eric Laurent733ce942017-12-07 12:18:25 -08003468 status = mpClientInterface->createAudioPatch(patch,
Eric Laurentd60560a2015-04-10 11:31:20 -07003469 &afPatchHandle,
3470 0);
3471 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3472 status, afPatchHandle);
3473 if (status != NO_ERROR) {
3474 ALOGW("%s patch panel could not connect device patch, error %d",
3475 __FUNCTION__, status);
3476 return INVALID_OPERATION;
3477 }
3478 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003479 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003480
3481 if (status != NO_ERROR) {
3482 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3483 return status;
3484 }
3485 sourceDesc->mSwOutput = outputDesc;
3486 if (delayMs != 0) {
3487 usleep(delayMs * 1000);
3488 }
3489 }
3490
3491 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3492 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3493
3494 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003495}
3496
Glenn Kasten559d4392016-03-29 13:42:57 -07003497status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003498{
Eric Laurentd60560a2015-04-10 11:31:20 -07003499 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3500 ALOGV("%s handle %d", __FUNCTION__, handle);
3501 if (sourceDesc == 0) {
3502 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3503 return BAD_VALUE;
3504 }
3505 status_t status = disconnectAudioSource(sourceDesc);
3506
3507 mAudioSources.removeItem(handle);
3508 return status;
3509}
3510
Andy Hung2ddee192015-12-18 17:34:44 -08003511status_t AudioPolicyManager::setMasterMono(bool mono)
3512{
3513 if (mMasterMono == mono) {
3514 return NO_ERROR;
3515 }
3516 mMasterMono = mono;
3517 // if enabling mono we close all offloaded devices, which will invalidate the
3518 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3519 // for recreating the new AudioTrack as non-offloaded PCM.
3520 //
3521 // If disabling mono, we leave all tracks as is: we don't know which clients
3522 // and tracks are able to be recreated as offloaded. The next "song" should
3523 // play back offloaded.
3524 if (mMasterMono) {
3525 Vector<audio_io_handle_t> offloaded;
3526 for (size_t i = 0; i < mOutputs.size(); ++i) {
3527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3528 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3529 offloaded.push(desc->mIoHandle);
3530 }
3531 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003532 for (const auto& handle : offloaded) {
3533 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003534 }
3535 }
3536 // update master mono for all remaining outputs
3537 for (size_t i = 0; i < mOutputs.size(); ++i) {
3538 updateMono(mOutputs.keyAt(i));
3539 }
3540 return NO_ERROR;
3541}
3542
3543status_t AudioPolicyManager::getMasterMono(bool *mono)
3544{
3545 *mono = mMasterMono;
3546 return NO_ERROR;
3547}
3548
Eric Laurentac9cef52017-06-09 15:46:26 -07003549float AudioPolicyManager::getStreamVolumeDB(
3550 audio_stream_type_t stream, int index, audio_devices_t device)
3551{
3552 return computeVolume(stream, index, device);
3553}
3554
jiabin81772902018-04-02 17:52:27 -07003555status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3556 FormatVector& formats) {
3557 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3558 return BAD_VALUE;
3559 }
3560 String8 reply;
3561 reply = mpClientInterface->getParameters(
3562 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3563 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3564 AudioParameter repliedParameters(reply);
3565 if (repliedParameters.get(
3566 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3567 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3568 return BAD_VALUE;
3569 }
3570 for (auto format : formatsFromString(reply.string())) {
3571 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3572 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3573 if (format == AAC_FORMATS[i]) {
3574 format = AUDIO_FORMAT_AAC_LC;
3575 break;
3576 }
3577 }
3578 bool exist = false;
3579 for (size_t i = 0; i < formats.size(); i++) {
3580 if (format == formats[i]) {
3581 exist = true;
3582 break;
3583 }
3584 }
3585 bool isSurroundFormat = false;
3586 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3587 if (SURROUND_FORMATS[i] == format) {
3588 isSurroundFormat = true;
3589 break;
3590 }
3591 }
3592 if (!exist && isSurroundFormat) {
3593 formats.add(format);
3594 }
3595 }
3596 return NO_ERROR;
3597}
3598
3599status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3600 audio_format_t *surroundFormats,
3601 bool *surroundFormatsEnabled,
3602 bool reported)
3603{
3604 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3605 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3606 return BAD_VALUE;
3607 }
3608 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3609 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3610
3611 // Only return value if there is HDMI output.
3612 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3613 return INVALID_OPERATION;
3614 }
3615
3616 size_t formatsWritten = 0;
3617 size_t formatsMax = *numSurroundFormats;
3618 *numSurroundFormats = 0;
3619 FormatVector formats;
3620 if (reported) {
3621 // Only get surround formats which are reported by device.
3622 // First list already open outputs that can be routed to this device
3623 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3624 SortedVector<audio_io_handle_t> outputs;
3625 bool reportedFormatFound = false;
3626 status_t status;
3627 sp<SwAudioOutputDescriptor> desc;
3628 for (size_t i = 0; i < mOutputs.size(); i++) {
3629 desc = mOutputs.valueAt(i);
3630 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3631 outputs.add(mOutputs.keyAt(i));
3632 }
3633 }
3634 // Open an output to query dynamic parameters.
3635 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3636 AUDIO_DEVICE_OUT_HDMI);
3637 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3638 String8 address = hdmiOutputDevices[i]->mAddress;
3639 for (const auto& hwModule : mHwModules) {
3640 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3641 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3642 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3643 profile->supportDeviceAddress(address)) {
3644 size_t j;
3645 for (j = 0; j < outputs.size(); j++) {
3646 desc = mOutputs.valueFor(outputs.itemAt(j));
3647 if (!desc->isDuplicated() && desc->mProfile == profile) {
3648 break;
3649 }
3650 }
3651 if (j != outputs.size()) {
3652 status = getSupportedFormats(outputs.itemAt(j), formats);
3653 reportedFormatFound |= (status == NO_ERROR);
3654 continue;
3655 }
3656
3657 if (!profile->canOpenNewIo()) {
3658 ALOGW("Max Output number %u already opened for this profile %s",
3659 profile->maxOpenCount, profile->getTagName().c_str());
3660 continue;
3661 }
3662
3663 ALOGV("opening output for device %08x with params %s profile %p name %s",
3664 device, address.string(), profile.get(), profile->getName().string());
3665 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3666 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3667 status_t status = desc->open(nullptr, device, address,
3668 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3669 &output);
3670
3671 if (status == NO_ERROR) {
3672 status = getSupportedFormats(output, formats);
3673 reportedFormatFound |= (status == NO_ERROR);
3674 desc->close();
3675 output = AUDIO_IO_HANDLE_NONE;
3676 }
3677 }
3678 }
3679 }
3680 }
3681
3682 if (!reportedFormatFound) {
3683 return UNKNOWN_ERROR;
3684 }
3685 } else {
3686 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3687 formats.add(SURROUND_FORMATS[i]);
3688 }
3689 }
3690 for (size_t i = 0; i < formats.size(); i++) {
3691 if (formatsWritten < formatsMax) {
3692 surroundFormats[formatsWritten] = formats[i];
3693 bool formatEnabled = false;
3694 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3695 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3696 formatEnabled =
3697 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3698 break;
3699 }
3700 } else {
3701 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3702 }
3703 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3704 }
3705 (*numSurroundFormats)++;
3706 }
3707 return NO_ERROR;
3708}
3709
3710status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3711{
3712 // Check if audio format is a surround formats.
3713 bool isSurroundFormat = false;
3714 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3715 if (audioFormat == SURROUND_FORMATS[i]) {
3716 isSurroundFormat = true;
3717 break;
3718 }
3719 }
3720 if (!isSurroundFormat) {
3721 return BAD_VALUE;
3722 }
3723
3724 // Should only be called when MANUAL.
3725 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3726 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3727 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3728 return INVALID_OPERATION;
3729 }
3730
3731 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3732 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3733 return NO_ERROR;
3734 }
3735
3736 // The operation is valid only when there is HDMI output available.
3737 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3738 return INVALID_OPERATION;
3739 }
3740
3741 if (enabled) {
3742 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3743 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3744 mSurroundFormats.insert(AAC_FORMATS[i]);
3745 }
3746 } else {
3747 mSurroundFormats.insert(audioFormat);
3748 }
3749 } else {
3750 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3751 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3752 mSurroundFormats.erase(AAC_FORMATS[i]);
3753 }
3754 } else {
3755 mSurroundFormats.erase(audioFormat);
3756 }
3757 }
3758
3759 sp<SwAudioOutputDescriptor> outputDesc;
3760 bool profileUpdated = false;
3761 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3762 AUDIO_DEVICE_OUT_HDMI);
3763 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3764 // Simulate reconnection to update enabled surround sound formats.
3765 String8 address = hdmiOutputDevices[i]->mAddress;
3766 String8 name = hdmiOutputDevices[i]->getName();
3767 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3768 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3769 address.c_str(),
3770 name.c_str());
3771 if (status != NO_ERROR) {
3772 continue;
3773 }
3774 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3775 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3776 address.c_str(),
3777 name.c_str());
3778 profileUpdated |= (status == NO_ERROR);
3779 }
3780 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3781 AUDIO_DEVICE_IN_HDMI);
3782 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3783 // Simulate reconnection to update enabled surround sound formats.
3784 String8 address = hdmiInputDevices[i]->mAddress;
3785 String8 name = hdmiInputDevices[i]->getName();
3786 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3787 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3788 address.c_str(),
3789 name.c_str());
3790 if (status != NO_ERROR) {
3791 continue;
3792 }
3793 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3794 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3795 address.c_str(),
3796 name.c_str());
3797 profileUpdated |= (status == NO_ERROR);
3798 }
3799
3800 // Undo the surround formats change due to no audio profiles updated.
3801 if (!profileUpdated) {
3802 if (enabled) {
3803 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3804 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3805 mSurroundFormats.erase(AAC_FORMATS[i]);
3806 }
3807 } else {
3808 mSurroundFormats.erase(audioFormat);
3809 }
3810 } else {
3811 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3812 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3813 mSurroundFormats.insert(AAC_FORMATS[i]);
3814 }
3815 } else {
3816 mSurroundFormats.insert(audioFormat);
3817 }
3818 }
3819 }
3820
3821 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3822}
3823
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003824void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3825{
3826 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3827
3828 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3829 for (size_t i = 0; i < activeInputs.size(); i++) {
3830 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3831 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3832 for (size_t j = 0; j < activeSessions.size(); j++) {
3833 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3834 if (activeSession->uid() == uid) {
3835 activeSession->setSilenced(silenced);
3836 }
3837 }
3838 }
3839}
3840
Eric Laurentd60560a2015-04-10 11:31:20 -07003841status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3842{
3843 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3844
3845 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3846 if (patchDesc == 0) {
3847 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3848 sourceDesc->mPatchDesc->mHandle);
3849 return BAD_VALUE;
3850 }
3851 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3852
Eric Laurent28d09f02016-03-08 10:43:05 -08003853 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003854 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3855 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003856 status_t status = stopSource(swOutputDesc, stream, false);
3857 if (status == NO_ERROR) {
3858 swOutputDesc->stop();
3859 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003860 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3861 } else {
3862 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3863 if (hwOutputDesc != 0) {
3864 // release patch between src device and output device
3865 // close Hwoutput and remove from mHwOutputs
3866 } else {
3867 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3868 }
3869 }
3870 return NO_ERROR;
3871}
3872
3873sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3874 audio_io_handle_t output, routing_strategy strategy)
3875{
3876 sp<AudioSourceDescriptor> source;
3877 for (size_t i = 0; i < mAudioSources.size(); i++) {
3878 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3879 routing_strategy sourceStrategy =
3880 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3881 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3882 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3883 source = sourceDesc;
3884 break;
3885 }
3886 }
3887 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003888}
3889
Eric Laurente552edb2014-03-10 17:42:56 -07003890// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003891// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003892// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003893uint32_t AudioPolicyManager::nextAudioPortGeneration()
3894{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003895 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003896}
3897
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003898#ifdef USE_XML_AUDIO_POLICY_CONF
3899// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3900static const char *kConfigLocationList[] =
3901 {"/odm/etc", "/vendor/etc", "/system/etc"};
3902static const int kConfigLocationListSize =
3903 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3904
3905static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3906 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003907 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003908 status_t ret;
3909
Cheney Ni00ce33d2018-11-01 06:30:37 +08003910 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
3911 if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
Cheney Ni6851adb2018-11-01 06:30:37 +08003912 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
Cheney Ni00ce33d2018-11-01 06:30:37 +08003913 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.enabled", false)) {
3914 // This property persist.bluetooth.bluetooth_audio_hal.enabled is temporary only.
3915 // xml files AUDIO_POLICY_BLUETOOTH_HAL_ENABLED_XML_CONFIG_FILE_NAME, although having
3916 // the same name, must be different in offload and non offload cases in device
3917 // specific configuration file.
3918 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_HAL_ENABLED_XML_CONFIG_FILE_NAME);
Cheney Ni6851adb2018-11-01 06:30:37 +08003919 }
Cheney Ni00ce33d2018-11-01 06:30:37 +08003920 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.enabled", false)) {
3921 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_HAL_ENABLED_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07003922 }
3923 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3924
3925 for (const char* fileName : fileNames) {
3926 for (int i = 0; i < kConfigLocationListSize; i++) {
3927 PolicySerializer serializer;
3928 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3929 "%s/%s", kConfigLocationList[i], fileName);
3930 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3931 if (ret == NO_ERROR) {
3932 return ret;
3933 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003934 }
3935 }
3936 return ret;
3937}
3938#endif
3939
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003940AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3941 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003942 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003943 mUidCached(getuid()),
3944 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003945 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003946 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003947#ifdef USE_XML_AUDIO_POLICY_CONF
3948 mVolumeCurves(new VolumeCurvesCollection()),
3949 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003950 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003951#else
3952 mVolumeCurves(new StreamDescriptorCollection()),
3953 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3954 mDefaultOutputDevice),
3955#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003956 mAudioPortGeneration(1),
3957 mBeaconMuteRefCount(0),
3958 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003959 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003960 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003961 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003962 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3963 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003964{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003965}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003966
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003967AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3968 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3969{
3970 loadConfig();
3971 initialize();
3972}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003973
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003974void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003975#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003976 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003977#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003978 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3979 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003980#endif
3981 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003982 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003983 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003984}
3985
3986status_t AudioPolicyManager::initialize() {
3987 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003988
3989 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003990 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3991 if (!engineInstance) {
3992 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003993 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003994 }
3995 // Retrieve the Policy Manager Interface
3996 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3997 if (mEngine == NULL) {
3998 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003999 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01004000 }
4001 mEngine->setObserver(this);
4002 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004003 if (status != NO_ERROR) {
4004 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4005 return status;
4006 }
François Gaffie2110e042015-03-24 08:41:51 +01004007
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07004009 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004010 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4011 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004012 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004013 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004014 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4015 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004016 continue;
4017 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004018 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004019 // open all output streams needed to access attached devices
4020 // except for direct output streams that are only opened when they are actually
4021 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004022 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004023 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004024 if (!outProfile->canOpenNewIo()) {
4025 ALOGE("Invalid Output profile max open count %u for profile %s",
4026 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4027 continue;
4028 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004029 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004030 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004031 continue;
4032 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004033 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004034 mTtsOutputAvailable = true;
4035 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004036
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004037 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004038 continue;
4039 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004040 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004041 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4042 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004043 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004044 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004045 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004046 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004047 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004048 if ((profileType & outputDeviceTypes) == 0) {
4049 continue;
4050 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004051 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4052 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004053 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4054 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
4055 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4056 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004057 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004058 status_t status = outputDesc->open(nullptr, profileType, address,
4059 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004060
4061 if (status != NO_ERROR) {
4062 ALOGW("Cannot open output stream for device %08x on hw module %s",
4063 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004064 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004065 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004066 for (const auto& dev : supportedDevices) {
4067 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004068 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004069 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004070 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004071 }
4072 }
4073 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004074 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004075 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004076 }
4077 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004078 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004079 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004080 true,
4081 0,
4082 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004083 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004084 }
Eric Laurente552edb2014-03-10 17:42:56 -07004085 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 // open input streams needed to access attached devices to validate
4087 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004088 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004089 if (!inProfile->canOpenNewIo()) {
4090 ALOGE("Invalid Input profile max open count %u for profile %s",
4091 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4092 continue;
4093 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004094 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004095 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004096 continue;
4097 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004098 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004099 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004100 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4101
Eric Laurentd78f1532014-09-16 16:38:20 -07004102 if ((profileType & inputDeviceTypes) == 0) {
4103 continue;
4104 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004105 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004106 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004107
Eric Laurent53b810e2017-12-10 17:25:10 -08004108 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4109 // the inputs vector must be of size >= 1, but we don't want to crash here
4110 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4111 : String8("");
4112 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4113 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4114
Eric Laurentd78f1532014-09-16 16:38:20 -07004115 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004116 status_t status = inputDesc->open(nullptr,
4117 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004118 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004119 AUDIO_SOURCE_MIC,
4120 AUDIO_INPUT_FLAG_NONE,
4121 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004122
4123 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004124 for (const auto& dev : inProfile->getSupportedDevices()) {
4125 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004126 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004127 if (index >= 0) {
4128 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4129 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004130 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004131 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004132 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004133 }
4134 }
Eric Laurentfe231122017-11-17 17:48:06 -08004135 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004136 } else {
4137 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004138 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004139 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004140 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 }
4142 }
4143 // make sure all attached devices have been allocated a unique ID
4144 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004145 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004146 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004147 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4148 continue;
4149 }
François Gaffie2110e042015-03-24 08:41:51 +01004150 // The device is now validated and can be appended to the available devices of the engine
4151 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 i++;
4154 }
4155 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004156 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004157 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004158 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4159 continue;
4160 }
François Gaffie2110e042015-03-24 08:41:51 +01004161 // The device is now validated and can be appended to the available devices of the engine
4162 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4163 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004164 i++;
4165 }
4166 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004167 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004168 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004169 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004170 }
jiabin9ff780e2018-03-19 18:19:52 -07004171 // If microphones address is empty, set it according to device type
4172 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4173 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4174 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4175 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4176 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4177 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4178 }
4179 }
4180 }
Eric Laurente552edb2014-03-10 17:42:56 -07004181
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004182 if (mPrimaryOutput == 0) {
4183 ALOGE("Failed to open primary output");
4184 status = NO_INIT;
4185 }
Eric Laurente552edb2014-03-10 17:42:56 -07004186
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004187 // Silence ALOGV statements
4188 property_set("log.tag." LOG_TAG, "D");
4189
Eric Laurente552edb2014-03-10 17:42:56 -07004190 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004191 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004192}
4193
Eric Laurente0720872014-03-11 09:30:41 -07004194AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004195{
Eric Laurente552edb2014-03-10 17:42:56 -07004196 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004197 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004198 }
4199 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004200 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004201 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004202 mAvailableOutputDevices.clear();
4203 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004204 mOutputs.clear();
4205 mInputs.clear();
4206 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004207 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004208 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004209}
4210
Eric Laurente0720872014-03-11 09:30:41 -07004211status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004212{
Eric Laurent87ffa392015-05-22 10:32:38 -07004213 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004214}
4215
Eric Laurente552edb2014-03-10 17:42:56 -07004216// ---
4217
Eric Laurent98e38192018-02-15 18:31:53 -08004218void AudioPolicyManager::addOutput(audio_io_handle_t output,
4219 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004220{
Eric Laurent1c333e22014-05-20 10:48:17 -07004221 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004222 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004223 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004224 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004225 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004226}
4227
François Gaffie53615e22015-03-19 09:24:12 +01004228void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4229{
4230 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004231 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004232}
4233
Eric Laurent98e38192018-02-15 18:31:53 -08004234void AudioPolicyManager::addInput(audio_io_handle_t input,
4235 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004236{
Eric Laurent1c333e22014-05-20 10:48:17 -07004237 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004238 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004239}
Eric Laurente552edb2014-03-10 17:42:56 -07004240
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004241void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004242 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004243 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004244 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004245 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004246 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004247 if (devDesc != 0) {
4248 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4249 desc->mIoHandle, address.string());
4250 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004251 }
4252}
4253
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004254status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004255 audio_policy_dev_state_t state,
4256 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004257 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004258{
François Gaffie53615e22015-03-19 09:24:12 +01004259 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004260 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004261
4262 if (audio_device_is_digital(device)) {
4263 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004264 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004265 }
Eric Laurente552edb2014-03-10 17:42:56 -07004266
Eric Laurent3b73df72014-03-11 09:06:29 -07004267 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004268 // first list already open outputs that can be routed to this device
4269 for (size_t i = 0; i < mOutputs.size(); i++) {
4270 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004271 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004272 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004273 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4274 outputs.add(mOutputs.keyAt(i));
4275 } else {
4276 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004277 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004278 }
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
4280 }
4281 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004282 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004283 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004284 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4285 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004286 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004287 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004288 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004289 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004290 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4291 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004292 }
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294 }
4295 }
4296
Eric Laurent7b279bb2015-12-14 10:18:23 -08004297 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004298
Eric Laurente552edb2014-03-10 17:42:56 -07004299 if (profiles.isEmpty() && outputs.isEmpty()) {
4300 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4301 return BAD_VALUE;
4302 }
4303
4304 // open outputs for matching profiles if needed. Direct outputs are also opened to
4305 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4306 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004307 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004308
4309 // nothing to do if one output is already opened for this profile
4310 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004311 for (j = 0; j < outputs.size(); j++) {
4312 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004313 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004314 // matching profile: save the sample rates, format and channel masks supported
4315 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004316 if (audio_device_is_digital(device)) {
4317 devDesc->importAudioPort(profile);
4318 }
Eric Laurente552edb2014-03-10 17:42:56 -07004319 break;
4320 }
4321 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004323 continue;
4324 }
4325
Eric Laurent3974e3b2017-12-07 17:58:43 -08004326 if (!profile->canOpenNewIo()) {
4327 ALOGW("Max Output number %u already opened for this profile %s",
4328 profile->maxOpenCount, profile->getTagName().c_str());
4329 continue;
4330 }
4331
Eric Laurent83efe1c2017-07-09 16:51:08 -07004332 ALOGV("opening output for device %08x with params %s profile %p name %s",
4333 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004334 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004335 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004336 status_t status = desc->open(nullptr, device, address,
4337 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004338
Eric Laurentfe231122017-11-17 17:48:06 -08004339 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004340 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004341 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004342 char *param = audio_device_address_to_parameter(device, address);
4343 mpClientInterface->setParameters(output, String8(param));
4344 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004345 }
Phil Burk00eeb322016-03-31 12:41:00 -07004346 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004347 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004348 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004349 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004350 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004351 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004352 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004353 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004354 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4355 profile->pickAudioProfile(
4356 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004357 config.offload_info.sample_rate = config.sample_rate;
4358 config.offload_info.channel_mask = config.channel_mask;
4359 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004360
4361 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4362 AUDIO_OUTPUT_FLAG_NONE, &output);
4363 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004364 output = AUDIO_IO_HANDLE_NONE;
4365 }
Eric Laurentd4692962014-05-05 18:13:44 -07004366 }
4367
Eric Laurentcf2c0212014-07-25 16:20:43 -07004368 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004369 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004370 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004371 sp<AudioPolicyMix> policyMix;
4372 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004373 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4374 address.string());
4375 }
François Gaffie036e1e92015-03-19 10:16:24 +01004376 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004377 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004378
Eric Laurent87ffa392015-05-22 10:32:38 -07004379 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4380 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004381 // no duplicated output for direct outputs and
4382 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004383 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004384
Eric Laurentd4692962014-05-05 18:13:44 -07004385 //TODO: configure audio effect output stage here
4386
4387 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004388 sp<SwAudioOutputDescriptor> dupOutputDesc =
4389 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4390 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4391 &duplicatedOutput);
4392 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004393 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004394 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004395 } else {
4396 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004397 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004398 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004399 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004400 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004401 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004402 }
Eric Laurente552edb2014-03-10 17:42:56 -07004403 }
4404 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004405 } else {
4406 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004407 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004408 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004409 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004410 profiles.removeAt(profile_index);
4411 profile_index--;
4412 } else {
4413 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004414 // Load digital format info only for digital devices
4415 if (audio_device_is_digital(device)) {
4416 devDesc->importAudioPort(profile);
4417 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004418
François Gaffie53615e22015-03-19 09:24:12 +01004419 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004420 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4421 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004422 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004423 NULL/*patch handle*/, address.string());
4424 }
Eric Laurente552edb2014-03-10 17:42:56 -07004425 ALOGV("checkOutputsForDevice(): adding output %d", output);
4426 }
4427 }
4428
4429 if (profiles.isEmpty()) {
4430 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4431 return BAD_VALUE;
4432 }
Eric Laurentd4692962014-05-05 18:13:44 -07004433 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004434 // check if one opened output is not needed any more after disconnecting one device
4435 for (size_t i = 0; i < mOutputs.size(); i++) {
4436 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004437 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004438 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004439 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004440 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004441 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004442 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004443 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4444 mOutputs.keyAt(i));
4445 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004446 }
Eric Laurente552edb2014-03-10 17:42:56 -07004447 }
4448 }
Eric Laurentd4692962014-05-05 18:13:44 -07004449 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004450 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004451 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4452 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004453 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004454 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004455 "clearing direct output profile %zu on module %s",
4456 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004457 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004458 }
4459 }
4460 }
4461 }
4462 return NO_ERROR;
4463}
4464
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004465status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004466 audio_policy_dev_state_t state,
4467 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004468 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004469{
Paul McLean9080a4c2015-06-18 08:24:02 -07004470 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004471 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004472
4473 if (audio_device_is_digital(device)) {
4474 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004475 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004476 }
4477
Eric Laurentd4692962014-05-05 18:13:44 -07004478 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4479 // first list already open inputs that can be routed to this device
4480 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4481 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004482 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004483 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4484 inputs.add(mInputs.keyAt(input_index));
4485 }
4486 }
4487
4488 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004489 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004490 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004491 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004492 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004493 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004494 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004495
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004496 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004497 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004498 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004499 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004500 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4501 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004502 }
Eric Laurentd4692962014-05-05 18:13:44 -07004503 }
4504 }
4505 }
4506
4507 if (profiles.isEmpty() && inputs.isEmpty()) {
4508 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4509 return BAD_VALUE;
4510 }
4511
4512 // open inputs for matching profiles if needed. Direct inputs are also opened to
4513 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4514 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4515
Eric Laurent1c333e22014-05-20 10:48:17 -07004516 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004517
Eric Laurentd4692962014-05-05 18:13:44 -07004518 // nothing to do if one input is already opened for this profile
4519 size_t input_index;
4520 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4521 desc = mInputs.valueAt(input_index);
4522 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004523 if (audio_device_is_digital(device)) {
4524 devDesc->importAudioPort(profile);
4525 }
Eric Laurentd4692962014-05-05 18:13:44 -07004526 break;
4527 }
4528 }
4529 if (input_index != mInputs.size()) {
4530 continue;
4531 }
4532
Eric Laurent3974e3b2017-12-07 17:58:43 -08004533 if (!profile->canOpenNewIo()) {
4534 ALOGW("Max Input number %u already opened for this profile %s",
4535 profile->maxOpenCount, profile->getTagName().c_str());
4536 continue;
4537 }
4538
Eric Laurentfe231122017-11-17 17:48:06 -08004539 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004540 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004541 status_t status = desc->open(nullptr,
4542 device,
4543 address,
4544 AUDIO_SOURCE_MIC,
4545 AUDIO_INPUT_FLAG_NONE,
4546 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004547
Eric Laurentcf2c0212014-07-25 16:20:43 -07004548 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004549 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004550 char *param = audio_device_address_to_parameter(device, address);
4551 mpClientInterface->setParameters(input, String8(param));
4552 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004553 }
Phil Burk00eeb322016-03-31 12:41:00 -07004554 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004555 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004556 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004557 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004558 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004559 }
4560
4561 if (input != 0) {
4562 addInput(input, desc);
4563 }
4564 } // endif input != 0
4565
Eric Laurentcf2c0212014-07-25 16:20:43 -07004566 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004567 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004568 profiles.removeAt(profile_index);
4569 profile_index--;
4570 } else {
4571 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004572 if (audio_device_is_digital(device)) {
4573 devDesc->importAudioPort(profile);
4574 }
Eric Laurentd4692962014-05-05 18:13:44 -07004575 ALOGV("checkInputsForDevice(): adding input %d", input);
4576 }
4577 } // end scan profiles
4578
4579 if (profiles.isEmpty()) {
4580 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4581 return BAD_VALUE;
4582 }
4583 } else {
4584 // Disconnect
4585 // check if one opened input is not needed any more after disconnecting one device
4586 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4587 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004588 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004589 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4590 mInputs.keyAt(input_index));
4591 inputs.add(mInputs.keyAt(input_index));
4592 }
4593 }
4594 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004595 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004596 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004597 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004598 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004599 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004600 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004601 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4602 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004603 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004604 }
4605 }
4606 }
4607 } // end disconnect
4608
4609 return NO_ERROR;
4610}
4611
4612
Eric Laurente0720872014-03-11 09:30:41 -07004613void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004614{
4615 ALOGV("closeOutput(%d)", output);
4616
Eric Laurentc75307b2015-03-17 15:29:32 -07004617 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004618 if (outputDesc == NULL) {
4619 ALOGW("closeOutput() unknown output %d", output);
4620 return;
4621 }
François Gaffie036e1e92015-03-19 10:16:24 +01004622 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004623
Eric Laurente552edb2014-03-10 17:42:56 -07004624 // look for duplicated outputs connected to the output being removed.
4625 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004626 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if (dupOutputDesc->isDuplicated() &&
4628 (dupOutputDesc->mOutput1 == outputDesc ||
4629 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004630 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004631 if (dupOutputDesc->mOutput1 == outputDesc) {
4632 outputDesc2 = dupOutputDesc->mOutput2;
4633 } else {
4634 outputDesc2 = dupOutputDesc->mOutput1;
4635 }
4636 // As all active tracks on duplicated output will be deleted,
4637 // and as they were also referenced on the other output, the reference
4638 // count for their stream type must be adjusted accordingly on
4639 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004640 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004641 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004642 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
Eric Laurent733ce942017-12-07 12:18:25 -08004645 // stop() will be a no op if the output is still active but is needed in case all
4646 // active streams refcounts where cleared above
4647 if (wasActive) {
4648 outputDesc2->stop();
4649 }
Eric Laurente552edb2014-03-10 17:42:56 -07004650 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4651 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4652
4653 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004654 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004655 }
4656 }
4657
Eric Laurent05b90f82014-08-27 15:32:29 -07004658 nextAudioPortGeneration();
4659
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004660 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004661 if (index >= 0) {
4662 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004663 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004664 mAudioPatches.removeItemsAt(index);
4665 mpClientInterface->onAudioPatchListUpdate();
4666 }
4667
Eric Laurentfe231122017-11-17 17:48:06 -08004668 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004669
François Gaffie53615e22015-03-19 09:24:12 +01004670 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004671 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004672}
4673
4674void AudioPolicyManager::closeInput(audio_io_handle_t input)
4675{
4676 ALOGV("closeInput(%d)", input);
4677
4678 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4679 if (inputDesc == NULL) {
4680 ALOGW("closeInput() unknown input %d", input);
4681 return;
4682 }
4683
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004685
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004686 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004687 if (index >= 0) {
4688 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004689 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004690 mAudioPatches.removeItemsAt(index);
4691 mpClientInterface->onAudioPatchListUpdate();
4692 }
4693
Eric Laurentfe231122017-11-17 17:48:06 -08004694 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004695 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004696}
4697
Eric Laurentc75307b2015-03-17 15:29:32 -07004698SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4699 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004700 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004701{
4702 SortedVector<audio_io_handle_t> outputs;
4703
4704 ALOGVV("getOutputsForDevice() device %04x", device);
4705 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004706 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004707 i, openOutputs.valueAt(i)->isDuplicated(),
4708 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004709 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4710 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4711 outputs.add(openOutputs.keyAt(i));
4712 }
4713 }
4714 return outputs;
4715}
4716
Eric Laurente0720872014-03-11 09:30:41 -07004717bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004718 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004719{
4720 if (outputs1.size() != outputs2.size()) {
4721 return false;
4722 }
4723 for (size_t i = 0; i < outputs1.size(); i++) {
4724 if (outputs1[i] != outputs2[i]) {
4725 return false;
4726 }
4727 }
4728 return true;
4729}
4730
Eric Laurente0720872014-03-11 09:30:41 -07004731void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004732{
4733 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4734 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4735 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4736 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4737
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004738 // also take into account external policy-related changes: add all outputs which are
4739 // associated with policies in the "before" and "after" output vectors
4740 ALOGVV("checkOutputForStrategy(): policy related outputs");
4741 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004742 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004743 if (desc != 0 && desc->mPolicyMix != NULL) {
4744 srcOutputs.add(desc->mIoHandle);
4745 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4746 }
4747 }
4748 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004749 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004750 if (desc != 0 && desc->mPolicyMix != NULL) {
4751 dstOutputs.add(desc->mIoHandle);
4752 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4753 }
4754 }
4755
Eric Laurente552edb2014-03-10 17:42:56 -07004756 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004757 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4758 // audio from invalidated tracks will be rendered when unmuting
4759 uint32_t maxLatency = 0;
4760 for (audio_io_handle_t srcOut : srcOutputs) {
4761 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4762 if (desc != 0 && maxLatency < desc->latency()) {
4763 maxLatency = desc->latency();
4764 }
4765 }
Eric Laurente552edb2014-03-10 17:42:56 -07004766 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4767 strategy, srcOutputs[0], dstOutputs[0]);
4768 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004769 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004770 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4771 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004772 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004773 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004774 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004775 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004776 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004777 if (source != 0){
4778 connectAudioSource(source);
4779 }
Eric Laurente552edb2014-03-10 17:42:56 -07004780 }
4781
4782 // Move effects associated to this strategy from previous output to new output
4783 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004784 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004785 }
4786 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004787 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004788 if (getStrategy((audio_stream_type_t)i) == strategy) {
4789 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004790 }
4791 }
4792 }
4793}
4794
Eric Laurente0720872014-03-11 09:30:41 -07004795void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004796{
François Gaffie2110e042015-03-24 08:41:51 +01004797 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004798 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004799 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004800 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004801 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004802 checkOutputForStrategy(STRATEGY_SONIFICATION);
4803 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004804 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004805 checkOutputForStrategy(STRATEGY_MEDIA);
4806 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004807 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004808}
4809
Eric Laurente0720872014-03-11 09:30:41 -07004810void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004811{
François Gaffie53615e22015-03-19 09:24:12 +01004812 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004813 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004814 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004815 return;
4816 }
4817
Eric Laurent3a4311c2014-03-17 12:00:47 -07004818 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004819 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4820 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4821 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004822
4823 // if suspended, restore A2DP output if:
4824 // ((SCO device is NOT connected) ||
4825 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4826 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004827 //
Eric Laurentf732e072016-08-03 19:30:28 -07004828 // if not suspended, suspend A2DP output if:
4829 // (SCO device is connected) &&
4830 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4831 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004832 //
4833 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004834 if (!isScoConnected ||
4835 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4836 AUDIO_POLICY_FORCE_BT_SCO) &&
4837 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4838 AUDIO_POLICY_FORCE_BT_SCO) &&
4839 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004840 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841
4842 mpClientInterface->restoreOutput(a2dpOutput);
4843 mA2dpSuspended = false;
4844 }
4845 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004846 if (isScoConnected &&
4847 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4848 AUDIO_POLICY_FORCE_BT_SCO) ||
4849 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4850 AUDIO_POLICY_FORCE_BT_SCO) ||
4851 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004852 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004853
4854 mpClientInterface->suspendOutput(a2dpOutput);
4855 mA2dpSuspended = true;
4856 }
4857 }
4858}
4859
Eric Laurentc75307b2015-03-17 15:29:32 -07004860audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4861 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004862{
4863 audio_devices_t device = AUDIO_DEVICE_NONE;
4864
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004865 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 if (index >= 0) {
4867 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4868 if (patchDesc->mUid != mUidCached) {
4869 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004870 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004871 return outputDesc->device();
4872 }
4873 }
4874
Eric Laurentf3a5a602018-05-22 18:42:55 -07004875 // Check if an explicit routing request exists for an active stream on this output and
4876 // use it in priority before any other rule
4877 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4878 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4879 audio_devices_t forcedDevice =
4880 mOutputRoutes.getActiveDeviceForStream(
4881 (audio_stream_type_t)stream, mAvailableOutputDevices);
4882
4883 if (forcedDevice != AUDIO_DEVICE_NONE) {
4884 return forcedDevice;
4885 }
4886 }
4887 }
4888
Eric Laurente552edb2014-03-10 17:42:56 -07004889 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004890 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004891 // use device for strategy enforced audible
4892 // 2: we are in call or the strategy phone is active on the output:
4893 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004894 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004895 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004896 // 4: the strategy for enforced audible is active but not enforced on the output:
4897 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004898 // 5: the strategy accessibility is active on the output:
4899 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004900 // 6: the strategy "respectful" sonification is active on the output:
4901 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004902 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004903 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004904 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004905 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004906 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004907 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004908
4909 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4910 // with a refined rule considering mutually exclusive devices (using same backend)
4911 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004912 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004913 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004914 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4915 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004916 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004917 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004918 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004920 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4921 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004922 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4923 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004924 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004925 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004926 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004927 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004928 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004929 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004930 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004931 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004932 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004933 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004934 }
4935
Eric Laurent1c333e22014-05-20 10:48:17 -07004936 ALOGV("getNewOutputDevice() selected device %x", device);
4937 return device;
4938}
4939
Eric Laurentfb66dd92016-01-28 18:32:03 -08004940audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004941{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004942 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004943
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004944 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 if (index >= 0) {
4946 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4947 if (patchDesc->mUid != mUidCached) {
4948 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004949 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 return inputDesc->mDevice;
4951 }
4952 }
4953
Eric Laurentdc95a252018-04-12 12:46:56 -07004954 // If we are not in call and no client is active on this input, this methods returns
4955 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004956 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004957 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4958 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4959 }
4960 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004961 device = getDeviceAndMixForInputSource(source);
4962 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004963
Eric Laurente552edb2014-03-10 17:42:56 -07004964 return device;
4965}
4966
Eric Laurent794fde22016-03-11 09:50:45 -08004967bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4968 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004969 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004970}
4971
Eric Laurente0720872014-03-11 09:30:41 -07004972uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004973 return (uint32_t)getStrategy(stream);
4974}
4975
Eric Laurente0720872014-03-11 09:30:41 -07004976audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004977 // By checking the range of stream before calling getStrategy, we avoid
4978 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4979 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004980 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 return AUDIO_DEVICE_NONE;
4982 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004983 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004984 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4985 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004986 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 }
Eric Laurent794fde22016-03-11 09:50:45 -08004988 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004989 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004990 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004991 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4992 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004993 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004994 curDevices |= outputDesc->device();
4995 }
4996 }
4997 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004998 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004999
5000 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5001 and doesn't really need to.*/
5002 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
5003 devices |= AUDIO_DEVICE_OUT_SPEAKER;
5004 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
5005 }
Eric Laurente552edb2014-03-10 17:42:56 -07005006 return devices;
5007}
5008
François Gaffie2110e042015-03-24 08:41:51 +01005009routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5010{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005011 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005012 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005013}
5014
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005015uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5016 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005017 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5018 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5019 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005020 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5021 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5022 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005023 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005024 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005025}
5026
Eric Laurente0720872014-03-11 09:30:41 -07005027void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005028 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005029 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005030 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5031 updateDevicesAndOutputs();
5032 break;
5033 default:
5034 break;
5035 }
5036}
5037
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005038uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005039
5040 // skip beacon mute management if a dedicated TTS output is available
5041 if (mTtsOutputAvailable) {
5042 return 0;
5043 }
5044
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005045 switch(event) {
5046 case STARTING_OUTPUT:
5047 mBeaconMuteRefCount++;
5048 break;
5049 case STOPPING_OUTPUT:
5050 if (mBeaconMuteRefCount > 0) {
5051 mBeaconMuteRefCount--;
5052 }
5053 break;
5054 case STARTING_BEACON:
5055 mBeaconPlayingRefCount++;
5056 break;
5057 case STOPPING_BEACON:
5058 if (mBeaconPlayingRefCount > 0) {
5059 mBeaconPlayingRefCount--;
5060 }
5061 break;
5062 }
5063
5064 if (mBeaconMuteRefCount > 0) {
5065 // any playback causes beacon to be muted
5066 return setBeaconMute(true);
5067 } else {
5068 // no other playback: unmute when beacon starts playing, mute when it stops
5069 return setBeaconMute(mBeaconPlayingRefCount == 0);
5070 }
5071}
5072
5073uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5074 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5075 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5076 // keep track of muted state to avoid repeating mute/unmute operations
5077 if (mBeaconMuted != mute) {
5078 // mute/unmute AUDIO_STREAM_TTS on all outputs
5079 ALOGV("\t muting %d", mute);
5080 uint32_t maxLatency = 0;
5081 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005082 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005083 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005084 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005085 0 /*delay*/, AUDIO_DEVICE_NONE);
5086 const uint32_t latency = desc->latency() * 2;
5087 if (latency > maxLatency) {
5088 maxLatency = latency;
5089 }
5090 }
5091 mBeaconMuted = mute;
5092 return maxLatency;
5093 }
5094 return 0;
5095}
5096
Eric Laurente0720872014-03-11 09:30:41 -07005097audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005098 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005099{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005100 // Check if an explicit routing request exists for a stream type corresponding to the
5101 // specified strategy and use it in priority over default routing rules.
5102 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5103 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5104 audio_devices_t forcedDevice =
5105 mOutputRoutes.getActiveDeviceForStream(
5106 (audio_stream_type_t)stream, mAvailableOutputDevices);
5107 if (forcedDevice != AUDIO_DEVICE_NONE) {
5108 return forcedDevice;
5109 }
Paul McLeanaa981192015-03-21 09:55:15 -07005110 }
5111 }
5112
Eric Laurente552edb2014-03-10 17:42:56 -07005113 if (fromCache) {
5114 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5115 strategy, mDeviceForStrategy[strategy]);
5116 return mDeviceForStrategy[strategy];
5117 }
François Gaffie2110e042015-03-24 08:41:51 +01005118 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005119}
5120
Eric Laurente0720872014-03-11 09:30:41 -07005121void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005122{
5123 for (int i = 0; i < NUM_STRATEGIES; i++) {
5124 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5125 }
5126 mPreviousOutputs = mOutputs;
5127}
5128
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005129uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005130 audio_devices_t prevDevice,
5131 uint32_t delayMs)
5132{
5133 // mute/unmute strategies using an incompatible device combination
5134 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5135 // if unmuting, unmute only after the specified delay
5136 if (outputDesc->isDuplicated()) {
5137 return 0;
5138 }
5139
5140 uint32_t muteWaitMs = 0;
5141 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005142 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005143
5144 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5145 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005146 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005147 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5148 bool doMute = false;
5149
5150 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5151 doMute = true;
5152 outputDesc->mStrategyMutedByDevice[i] = true;
5153 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5154 doMute = true;
5155 outputDesc->mStrategyMutedByDevice[i] = false;
5156 }
Eric Laurent99401132014-05-07 19:48:15 -07005157 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005158 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005159 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005160 // skip output if it does not share any device with current output
5161 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5162 == AUDIO_DEVICE_NONE) {
5163 continue;
5164 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005165 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005166 mute ? "muting" : "unmuting", i, curDevice);
5167 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005168 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005169 if (mute) {
5170 // FIXME: should not need to double latency if volume could be applied
5171 // immediately by the audioflinger mixer. We must account for the delay
5172 // between now and the next time the audioflinger thread for this output
5173 // will process a buffer (which corresponds to one buffer size,
5174 // usually 1/2 or 1/4 of the latency).
5175 if (muteWaitMs < desc->latency() * 2) {
5176 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005177 }
5178 }
5179 }
5180 }
5181 }
5182 }
5183
Eric Laurent99401132014-05-07 19:48:15 -07005184 // temporary mute output if device selection changes to avoid volume bursts due to
5185 // different per device volumes
5186 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005187 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5188 // temporary mute duration is conservatively set to 4 times the reported latency
5189 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5190 if (muteWaitMs < tempMuteWaitMs) {
5191 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005192 }
Eric Laurentdc462862016-07-19 12:29:53 -07005193
Eric Laurent99401132014-05-07 19:48:15 -07005194 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005195 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005196 // make sure that we do not start the temporary mute period too early in case of
5197 // delayed device change
5198 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005199 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005200 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005201 }
5202 }
5203 }
5204
Eric Laurente552edb2014-03-10 17:42:56 -07005205 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5206 if (muteWaitMs > delayMs) {
5207 muteWaitMs -= delayMs;
5208 usleep(muteWaitMs * 1000);
5209 return muteWaitMs;
5210 }
5211 return 0;
5212}
5213
Eric Laurentc75307b2015-03-17 15:29:32 -07005214uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005215 audio_devices_t device,
5216 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005218 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005219 const char *address,
5220 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005221{
Eric Laurentc75307b2015-03-17 15:29:32 -07005222 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005223 AudioParameter param;
5224 uint32_t muteWaitMs;
5225
5226 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005227 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5228 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5229 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5230 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005231 return muteWaitMs;
5232 }
5233 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5234 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005235 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005236 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005237 return 0;
5238 }
5239
5240 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005241 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005242
5243 audio_devices_t prevDevice = outputDesc->mDevice;
5244
Paul McLeanaa981192015-03-21 09:55:15 -07005245 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005246
5247 if (device != AUDIO_DEVICE_NONE) {
5248 outputDesc->mDevice = device;
5249 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005250
5251 // if the outputs are not materially active, there is no need to mute.
5252 if (requiresMuteCheck) {
5253 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5254 } else {
5255 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5256 muteWaitMs = 0;
5257 }
Eric Laurente552edb2014-03-10 17:42:56 -07005258
5259 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005260 // the requested device is AUDIO_DEVICE_NONE
5261 // OR the requested device is the same as current device
5262 // AND force is not specified
5263 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005264 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005265 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5266 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005267 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005268 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005269 return muteWaitMs;
5270 }
5271
5272 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005273
Eric Laurente552edb2014-03-10 17:42:56 -07005274 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005276 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005277 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005278 DeviceVector deviceList;
5279 if ((address == NULL) || (strlen(address) == 0)) {
5280 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5281 } else {
5282 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5283 }
5284
Eric Laurent1c333e22014-05-20 10:48:17 -07005285 if (!deviceList.isEmpty()) {
5286 struct audio_patch patch;
5287 outputDesc->toAudioPortConfig(&patch.sources[0]);
5288 patch.num_sources = 1;
5289 patch.num_sinks = 0;
5290 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5291 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005292 patch.num_sinks++;
5293 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 ssize_t index;
5295 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5296 index = mAudioPatches.indexOfKey(*patchHandle);
5297 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005298 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 }
5300 sp< AudioPatch> patchDesc;
5301 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5302 if (index >= 0) {
5303 patchDesc = mAudioPatches.valueAt(index);
5304 afPatchHandle = patchDesc->mAfPatchHandle;
5305 }
5306
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 &afPatchHandle,
5309 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5311 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005315 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 addAudioPatch(patchDesc->mHandle, patchDesc);
5317 } else {
5318 patchDesc->mPatch = patch;
5319 }
5320 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 if (patchHandle) {
5322 *patchHandle = patchDesc->mHandle;
5323 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005324 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005326 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005327 }
5328 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005329
5330 // inform all input as well
5331 for (size_t i = 0; i < mInputs.size(); i++) {
5332 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005333 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005334 AudioParameter inputCmd = AudioParameter();
5335 ALOGV("%s: inform input %d of device:%d", __func__,
5336 inputDescriptor->mIoHandle, device);
5337 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5338 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5339 inputCmd.toString(),
5340 delayMs);
5341 }
5342 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005343 }
Eric Laurente552edb2014-03-10 17:42:56 -07005344
5345 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005346 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005347
5348 return muteWaitMs;
5349}
5350
Eric Laurentc75307b2015-03-17 15:29:32 -07005351status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005352 int delayMs,
5353 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005354{
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 ssize_t index;
5356 if (patchHandle) {
5357 index = mAudioPatches.indexOfKey(*patchHandle);
5358 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005359 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 }
5361 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005362 return INVALID_OPERATION;
5363 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5365 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005367 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 removeAudioPatch(patchDesc->mHandle);
5369 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005370 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 return status;
5372}
5373
5374status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5375 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 bool force,
5377 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005378{
5379 status_t status = NO_ERROR;
5380
Eric Laurent1f2f2232014-06-02 12:01:23 -07005381 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005382 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5383 inputDesc->mDevice = device;
5384
5385 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5386 if (!deviceList.isEmpty()) {
5387 struct audio_patch patch;
5388 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005389 // AUDIO_SOURCE_HOTWORD is for internal use only:
5390 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005391 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005392 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005393 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5394 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005395 patch.num_sinks = 1;
5396 //only one input device for now
5397 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005398 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005399 ssize_t index;
5400 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5401 index = mAudioPatches.indexOfKey(*patchHandle);
5402 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005403 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 }
5405 sp< AudioPatch> patchDesc;
5406 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5407 if (index >= 0) {
5408 patchDesc = mAudioPatches.valueAt(index);
5409 afPatchHandle = patchDesc->mAfPatchHandle;
5410 }
5411
Eric Laurent1c333e22014-05-20 10:48:17 -07005412 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005414 0);
5415 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005416 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005417 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005419 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005420 addAudioPatch(patchDesc->mHandle, patchDesc);
5421 } else {
5422 patchDesc->mPatch = patch;
5423 }
5424 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005425 if (patchHandle) {
5426 *patchHandle = patchDesc->mHandle;
5427 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005428 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005429 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005430 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005431 }
5432 }
5433 }
5434 return status;
5435}
5436
Eric Laurent6a94d692014-05-20 11:18:06 -07005437status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5438 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005439{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005440 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005441 ssize_t index;
5442 if (patchHandle) {
5443 index = mAudioPatches.indexOfKey(*patchHandle);
5444 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005445 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 }
5447 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005448 return INVALID_OPERATION;
5449 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005450 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5451 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005452 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005453 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005454 removeAudioPatch(patchDesc->mHandle);
5455 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005456 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005457 return status;
5458}
5459
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005460sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005461 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005462 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005463 audio_format_t& format,
5464 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005465 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005466{
5467 // Choose an input profile based on the requested capture parameters: select the first available
5468 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005469 //
5470 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5471 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005472
Glenn Kasten730b9262018-03-29 15:01:26 -07005473 sp<IOProfile> firstInexact;
5474 uint32_t updatedSamplingRate = 0;
5475 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5476 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005477 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005478 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005479 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005480 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005481 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005482 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005483 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005484 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005485 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005486 &channelMask /*updatedChannelMask*/,
5487 // FIXME ugly cast
5488 (audio_output_flags_t) flags,
5489 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005490 return profile;
5491 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005492 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5493 samplingRate,
5494 &updatedSamplingRate,
5495 format,
5496 &updatedFormat,
5497 channelMask,
5498 &updatedChannelMask,
5499 // FIXME ugly cast
5500 (audio_output_flags_t) flags,
5501 false /*exactMatchRequiredForInputFlags*/)) {
5502 firstInexact = profile;
5503 }
5504
Eric Laurente552edb2014-03-10 17:42:56 -07005505 }
5506 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005507 if (firstInexact != nullptr) {
5508 samplingRate = updatedSamplingRate;
5509 format = updatedFormat;
5510 channelMask = updatedChannelMask;
5511 return firstInexact;
5512 }
Eric Laurente552edb2014-03-10 17:42:56 -07005513 return NULL;
5514}
5515
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005516
5517audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005518 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
François Gaffie036e1e92015-03-19 10:16:24 +01005520 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5521 audio_devices_t selectedDeviceFromMix =
5522 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005523
François Gaffie036e1e92015-03-19 10:16:24 +01005524 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5525 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005526 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005527 return getDeviceForInputSource(inputSource);
5528}
5529
5530audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5531{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005532 // Routing
5533 // Scan the whole RouteMap to see if we have an explicit route:
5534 // if the input source in the RouteMap is the same as the argument above,
5535 // and activity count is non-zero and the device in the route descriptor is available
5536 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005537 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5538 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005539 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005540 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005541 return route->mDeviceDescriptor->type();
5542 }
5543 }
5544
5545 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005546}
5547
Eric Laurente0720872014-03-11 09:30:41 -07005548float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005549 int index,
5550 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005551{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005552 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005553
5554 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5555 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5556 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5557 // the ringtone volume
5558 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5559 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5560 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5561 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5562 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5563 }
5564
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005565 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005566 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5567 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005568 switch (stream) {
5569 case AUDIO_STREAM_SYSTEM:
5570 case AUDIO_STREAM_RING:
5571 case AUDIO_STREAM_MUSIC:
5572 case AUDIO_STREAM_ALARM:
5573 case AUDIO_STREAM_NOTIFICATION:
5574 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5575 case AUDIO_STREAM_DTMF:
5576 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005577 int voiceVolumeIndex =
5578 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5579 const float maxVoiceVolDb =
5580 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5581 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005582 if (volumeDB > maxVoiceVolDb) {
5583 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5584 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5585 volumeDB = maxVoiceVolDb;
5586 }
5587 } break;
5588 default:
5589 break;
5590 }
5591 }
5592
Eric Laurente552edb2014-03-10 17:42:56 -07005593 // if a headset is connected, apply the following rules to ring tones and notifications
5594 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005595 // - always attenuate notifications volume by 6dB
5596 // - attenuate ring tones volume by 6dB unless music is not playing and
5597 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005598 // - if music is playing, always limit the volume to current music volume,
5599 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005600 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005601 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5602 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5603 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005604 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005605 AUDIO_DEVICE_OUT_USB_HEADSET |
5606 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005607 ((stream_strategy == STRATEGY_SONIFICATION)
5608 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005609 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005610 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005611 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005612 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005613 // when the phone is ringing we must consider that music could have been paused just before
5614 // by the music application and behave as if music was active if the last music track was
5615 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005616 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005617 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005618 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005619 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005620 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005621 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5622 musicDevice),
5623 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005624 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5625 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005626 if (volumeDB > minVolDB) {
5627 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005628 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005629 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005630 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5631 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5632 // on A2DP, also ensure notification volume is not too low compared to media when
5633 // intended to be played
5634 if ((volumeDB > -96.0f) &&
5635 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5636 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5637 stream, device,
5638 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5639 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5640 }
5641 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005642 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5643 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005644 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005645 }
5646 }
5647
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005648 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005649}
5650
Eric Laurente0720872014-03-11 09:30:41 -07005651status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005652 int index,
5653 const sp<AudioOutputDescriptor>& outputDesc,
5654 audio_devices_t device,
5655 int delayMs,
5656 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005657{
Eric Laurente552edb2014-03-10 17:42:56 -07005658 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005659 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005660 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005661 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005662 return NO_ERROR;
5663 }
François Gaffie2110e042015-03-24 08:41:51 +01005664 audio_policy_forced_cfg_t forceUseForComm =
5665 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005666 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005667 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5668 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005669 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005670 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005671 return INVALID_OPERATION;
5672 }
5673
Eric Laurentc75307b2015-03-17 15:29:32 -07005674 if (device == AUDIO_DEVICE_NONE) {
5675 device = outputDesc->device();
5676 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005677
Eric Laurentffbc80f2015-03-18 18:30:19 -07005678 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005679 if (outputDesc->isFixedVolume(device) ||
5680 // Force VoIP volume to max for bluetooth SCO
5681 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5682 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005683 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005684 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005685
Eric Laurentffbc80f2015-03-18 18:30:19 -07005686 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005687
Eric Laurent3b73df72014-03-11 09:06:29 -07005688 if (stream == AUDIO_STREAM_VOICE_CALL ||
5689 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005690 float voiceVolume;
5691 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005692 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005693 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005694 } else {
5695 voiceVolume = 1.0;
5696 }
5697
Eric Laurent18fba842016-03-31 14:41:26 -07005698 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005699 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5700 mLastVoiceVolume = voiceVolume;
5701 }
5702 }
5703
5704 return NO_ERROR;
5705}
5706
Eric Laurentc75307b2015-03-17 15:29:32 -07005707void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5708 audio_devices_t device,
5709 int delayMs,
5710 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005711{
Eric Laurentc75307b2015-03-17 15:29:32 -07005712 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005713
Eric Laurent794fde22016-03-11 09:50:45 -08005714 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005715 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005716 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005717 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005718 device,
5719 delayMs,
5720 force);
5721 }
5722}
5723
Eric Laurente0720872014-03-11 09:30:41 -07005724void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005725 bool on,
5726 const sp<AudioOutputDescriptor>& outputDesc,
5727 int delayMs,
5728 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005729{
Eric Laurent72249d52015-06-08 11:12:15 -07005730 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5731 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005732 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005733 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005734 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005735 }
5736 }
5737}
5738
Eric Laurente0720872014-03-11 09:30:41 -07005739void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005740 bool on,
5741 const sp<AudioOutputDescriptor>& outputDesc,
5742 int delayMs,
5743 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005744{
Eric Laurente552edb2014-03-10 17:42:56 -07005745 if (device == AUDIO_DEVICE_NONE) {
5746 device = outputDesc->device();
5747 }
5748
Eric Laurentc75307b2015-03-17 15:29:32 -07005749 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5750 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005751
5752 if (on) {
5753 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005754 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005755 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005756 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005757 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005758 }
5759 }
5760 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5761 outputDesc->mMuteCount[stream]++;
5762 } else {
5763 if (outputDesc->mMuteCount[stream] == 0) {
5764 ALOGV("setStreamMute() unmuting non muted stream!");
5765 return;
5766 }
5767 if (--outputDesc->mMuteCount[stream] == 0) {
5768 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005769 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005770 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005771 device,
5772 delayMs);
5773 }
5774 }
5775}
5776
Eric Laurente0720872014-03-11 09:30:41 -07005777void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005778 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005779{
Eric Laurent87ffa392015-05-22 10:32:38 -07005780 if(!hasPrimaryOutput()) {
5781 return;
5782 }
5783
Eric Laurente552edb2014-03-10 17:42:56 -07005784 // if the stream pertains to sonification strategy and we are in call we must
5785 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5786 // in the device used for phone strategy and play the tone if the selected device does not
5787 // interfere with the device used for phone strategy
5788 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5789 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005790 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005791 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5792 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005793 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005794 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5795 stream, starting, outputDesc->mDevice, stateChange);
5796 if (outputDesc->mRefCount[stream]) {
5797 int muteCount = 1;
5798 if (stateChange) {
5799 muteCount = outputDesc->mRefCount[stream];
5800 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005801 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005802 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5803 for (int i = 0; i < muteCount; i++) {
5804 setStreamMute(stream, starting, mPrimaryOutput);
5805 }
5806 } else {
5807 ALOGV("handleIncallSonification() high visibility");
5808 if (outputDesc->device() &
5809 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5810 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5811 for (int i = 0; i < muteCount; i++) {
5812 setStreamMute(stream, starting, mPrimaryOutput);
5813 }
5814 }
5815 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005816 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5817 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005818 } else {
5819 mpClientInterface->stopTone();
5820 }
5821 }
5822 }
5823 }
5824}
5825
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005826audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5827{
5828 // flags to stream type mapping
5829 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5830 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5831 }
5832 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5833 return AUDIO_STREAM_BLUETOOTH_SCO;
5834 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005835 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5836 return AUDIO_STREAM_TTS;
5837 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005838
5839 // usage to stream type mapping
5840 switch (attr->usage) {
5841 case AUDIO_USAGE_MEDIA:
5842 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005843 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005844 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5845 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005846 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5847 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005848 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5849 return AUDIO_STREAM_SYSTEM;
5850 case AUDIO_USAGE_VOICE_COMMUNICATION:
5851 return AUDIO_STREAM_VOICE_CALL;
5852
5853 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5854 return AUDIO_STREAM_DTMF;
5855
5856 case AUDIO_USAGE_ALARM:
5857 return AUDIO_STREAM_ALARM;
5858 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5859 return AUDIO_STREAM_RING;
5860
5861 case AUDIO_USAGE_NOTIFICATION:
5862 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5863 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5864 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5865 case AUDIO_USAGE_NOTIFICATION_EVENT:
5866 return AUDIO_STREAM_NOTIFICATION;
5867
5868 case AUDIO_USAGE_UNKNOWN:
5869 default:
5870 return AUDIO_STREAM_MUSIC;
5871 }
5872}
Eric Laurente83b55d2014-11-14 10:06:21 -08005873
François Gaffie53615e22015-03-19 09:24:12 +01005874bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5875{
Eric Laurente83b55d2014-11-14 10:06:21 -08005876 // has flags that map to a strategy?
5877 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5878 return true;
5879 }
5880
5881 // has known usage?
5882 switch (paa->usage) {
5883 case AUDIO_USAGE_UNKNOWN:
5884 case AUDIO_USAGE_MEDIA:
5885 case AUDIO_USAGE_VOICE_COMMUNICATION:
5886 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5887 case AUDIO_USAGE_ALARM:
5888 case AUDIO_USAGE_NOTIFICATION:
5889 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5890 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5891 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5892 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5893 case AUDIO_USAGE_NOTIFICATION_EVENT:
5894 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5895 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5896 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5897 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005898 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005899 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005900 break;
5901 default:
5902 return false;
5903 }
5904 return true;
5905}
5906
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005907bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005908 routing_strategy strategy, uint32_t inPastMs,
5909 nsecs_t sysTime) const
5910{
5911 if ((sysTime == 0) && (inPastMs != 0)) {
5912 sysTime = systemTime();
5913 }
Eric Laurent794fde22016-03-11 09:50:45 -08005914 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005915 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5916 (NUM_STRATEGIES == strategy)) &&
5917 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5918 return true;
5919 }
5920 }
5921 return false;
5922}
5923
Eric Laurent484e9272018-06-07 17:29:23 -07005924bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5925 routing_strategy strategy, uint32_t inPastMs,
5926 nsecs_t sysTime) const
5927{
5928 for (size_t i = 0; i < mOutputs.size(); i++) {
5929 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5930 if (outputDesc->sharesHwModuleWith(desc)
5931 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5932 return true;
5933 }
5934 }
5935 return false;
5936}
5937
François Gaffie2110e042015-03-24 08:41:51 +01005938audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5939{
5940 return mEngine->getForceUse(usage);
5941}
5942
5943bool AudioPolicyManager::isInCall()
5944{
5945 return isStateInCall(mEngine->getPhoneState());
5946}
5947
5948bool AudioPolicyManager::isStateInCall(int state)
5949{
5950 return is_state_in_call(state);
5951}
5952
Eric Laurentd60560a2015-04-10 11:31:20 -07005953void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5954{
5955 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5956 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5957 if (sourceDesc->mDevice->equals(deviceDesc)) {
5958 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5959 stopAudioSource(sourceDesc->getHandle());
5960 }
5961 }
5962
5963 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5964 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5965 bool release = false;
5966 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5967 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5968 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5969 source->ext.device.type == deviceDesc->type()) {
5970 release = true;
5971 }
5972 }
5973 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5974 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5975 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5976 sink->ext.device.type == deviceDesc->type()) {
5977 release = true;
5978 }
5979 }
5980 if (release) {
5981 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5982 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5983 }
5984 }
5985}
5986
Phil Burk09bc4612016-02-24 15:58:15 -08005987// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005988void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5989 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005990 // TODO Set this based on Config properties.
5991 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005992
5993 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5994 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005995 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005996
jiabin81772902018-04-02 17:52:27 -07005997 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5998 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5999 formats.clear();
6000 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
6001 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08006002 }
jiabin81772902018-04-02 17:52:27 -07006003 // Always enable IEC61937 when in MANUAL mode.
6004 formats.add(AUDIO_FORMAT_IEC61937);
6005 } else { // NEVER, AUTO or ALWAYS
6006 // Analyze original support for various formats.
6007 bool supportsAC3 = false;
6008 bool supportsOtherSurround = false;
6009 bool supportsIEC61937 = false;
6010 mSurroundFormats.clear();
6011 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
6012 audio_format_t format = formats[formatIndex];
6013 switch (format) {
6014 case AUDIO_FORMAT_AC3:
6015 supportsAC3 = true;
6016 break;
6017 case AUDIO_FORMAT_E_AC3:
6018 case AUDIO_FORMAT_DTS:
6019 case AUDIO_FORMAT_DTS_HD:
6020 // If ALWAYS, remove all other surround formats here
6021 // since we will add them later.
6022 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6023 formats.removeAt(formatIndex);
6024 formatIndex--;
6025 }
6026 supportsOtherSurround = true;
6027 break;
6028 case AUDIO_FORMAT_IEC61937:
6029 supportsIEC61937 = true;
6030 break;
6031 default:
6032 break;
6033 }
6034 }
Phil Burk09bc4612016-02-24 15:58:15 -08006035
jiabin81772902018-04-02 17:52:27 -07006036 // Modify formats based on surround preferences.
6037 // If NEVER, remove support for surround formats.
6038 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6039 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
6040 // Remove surround sound related formats.
6041 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
6042 audio_format_t format = formats[formatIndex];
6043 switch(format) {
6044 case AUDIO_FORMAT_AC3:
6045 case AUDIO_FORMAT_E_AC3:
6046 case AUDIO_FORMAT_DTS:
6047 case AUDIO_FORMAT_DTS_HD:
6048 case AUDIO_FORMAT_IEC61937:
6049 formats.removeAt(formatIndex);
6050 break;
6051 default:
6052 formatIndex++; // keep it
6053 break;
6054 }
6055 }
6056 supportsAC3 = false;
6057 supportsOtherSurround = false;
6058 supportsIEC61937 = false;
6059 }
6060 } else { // AUTO or ALWAYS
6061 // Most TVs support AC3 even if they do not report it in the EDID.
6062 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6063 && !supportsAC3) {
6064 formats.add(AUDIO_FORMAT_AC3);
6065 supportsAC3 = true;
6066 }
6067
6068 // If ALWAYS, add support for raw surround formats if all are missing.
6069 // This assumes that if any of these formats are reported by the HAL
6070 // then the report is valid and should not be modified.
6071 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6072 formats.add(AUDIO_FORMAT_E_AC3);
6073 formats.add(AUDIO_FORMAT_DTS);
6074 formats.add(AUDIO_FORMAT_DTS_HD);
6075 supportsOtherSurround = true;
6076 }
6077
6078 // Add support for IEC61937 if any raw surround supported.
6079 // The HAL could do this but add it here, just in case.
6080 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6081 formats.add(AUDIO_FORMAT_IEC61937);
6082 supportsIEC61937 = true;
6083 }
6084
6085 // Add reported surround sound formats to enabled surround formats.
6086 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006087 audio_format_t format = formats[formatIndex];
6088 switch(format) {
6089 case AUDIO_FORMAT_AC3:
6090 case AUDIO_FORMAT_E_AC3:
6091 case AUDIO_FORMAT_DTS:
6092 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006093 case AUDIO_FORMAT_AAC_LC:
6094 case AUDIO_FORMAT_DOLBY_TRUEHD:
6095 case AUDIO_FORMAT_E_AC3_JOC:
6096 mSurroundFormats.insert(format);
Chih-Hung Hsieh39399602018-10-16 14:42:13 -07006097 break;
Phil Burk07ac1142016-03-25 13:39:29 -07006098 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006099 break;
6100 }
Phil Burk09bc4612016-02-24 15:58:15 -08006101 }
Phil Burk07ac1142016-03-25 13:39:29 -07006102 }
Phil Burk09bc4612016-02-24 15:58:15 -08006103 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006104}
6105
6106// Modify the list of channel masks supported.
6107void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6108 ChannelsVector &channelMasks = *channelMasksPtr;
6109 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6110 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6111
6112 // If NEVER, then remove support for channelMasks > stereo.
6113 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6114 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6115 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6116 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6117 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6118 channelMasks.removeAt(maskIndex);
6119 } else {
6120 maskIndex++;
6121 }
6122 }
jiabin81772902018-04-02 17:52:27 -07006123 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6124 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6125 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006126 bool supports5dot1 = false;
6127 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006128 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006129 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6130 supports5dot1 = true;
6131 break;
6132 }
6133 }
6134 // If not then add 5.1 support.
6135 if (!supports5dot1) {
6136 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6137 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6138 }
Phil Burk09bc4612016-02-24 15:58:15 -08006139 }
6140}
6141
Phil Burk00eeb322016-03-31 12:41:00 -07006142void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6143 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006144 AudioProfileVector &profiles)
6145{
6146 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006147
François Gaffie112b0af2015-11-19 16:13:25 +01006148 // Format MUST be checked first to update the list of AudioProfile
6149 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006150 reply = mpClientInterface->getParameters(
6151 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006152 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006153 AudioParameter repliedParameters(reply);
6154 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006155 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006156 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6157 return;
6158 }
Phil Burk09bc4612016-02-24 15:58:15 -08006159 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006160 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006161 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006162 }
Phil Burk09bc4612016-02-24 15:58:15 -08006163 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006164 }
François Gaffie112b0af2015-11-19 16:13:25 +01006165
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006166 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006167 ChannelsVector channelMasks;
6168 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006169 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006170 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006171
6172 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006173 reply = mpClientInterface->getParameters(
6174 ioHandle,
6175 requestedParameters.toString() + ";" +
6176 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006177 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006178 AudioParameter repliedParameters(reply);
6179 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006180 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006181 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006182 }
6183 }
6184 if (profiles.hasDynamicChannelsFor(format)) {
6185 reply = mpClientInterface->getParameters(ioHandle,
6186 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006187 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006188 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006189 AudioParameter repliedParameters(reply);
6190 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006191 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006192 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006193 if (device == AUDIO_DEVICE_OUT_HDMI) {
6194 filterSurroundChannelMasks(&channelMasks);
6195 }
François Gaffie112b0af2015-11-19 16:13:25 +01006196 }
6197 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006198 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006199 }
6200}
Eric Laurentd60560a2015-04-10 11:31:20 -07006201
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006202} // namespace android