blob: 23cc02e689b0acab670987f65b76489ccc602f0a [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039
François Gaffie2110e042015-03-24 08:41:51 +010040#include <AudioPolicyManagerInterface.h>
41#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080045#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070046#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070048#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070049#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010050#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010051#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010053#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010054#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010056#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurent3b73df72014-03-11 09:06:29 -070058namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurentdc462862016-07-19 12:29:53 -070060//FIXME: workaround for truncated touch sounds
61// to be removed when the problem is handled by system UI
62#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070063
64// Largest difference in dB on earpiece in call between the voice volume and another
65// media / notification / system volume.
66constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
67
jiabin81772902018-04-02 17:52:27 -070068#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
69// Array of all surround formats.
70static const audio_format_t SURROUND_FORMATS[] = {
71 AUDIO_FORMAT_AC3,
72 AUDIO_FORMAT_E_AC3,
73 AUDIO_FORMAT_DTS,
74 AUDIO_FORMAT_DTS_HD,
75 AUDIO_FORMAT_AAC_LC,
76 AUDIO_FORMAT_DOLBY_TRUEHD,
77 AUDIO_FORMAT_E_AC3_JOC,
78};
79// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
80static const audio_format_t AAC_FORMATS[] = {
81 AUDIO_FORMAT_AAC_LC,
82 AUDIO_FORMAT_AAC_HE_V1,
83 AUDIO_FORMAT_AAC_HE_V2,
84 AUDIO_FORMAT_AAC_ELD,
85 AUDIO_FORMAT_AAC_XHE,
86};
87
Eric Laurente552edb2014-03-10 17:42:56 -070088// ----------------------------------------------------------------------------
89// AudioPolicyInterface implementation
90// ----------------------------------------------------------------------------
91
Eric Laurente0720872014-03-11 09:30:41 -070092status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080093 audio_policy_dev_state_t state,
94 const char *device_address,
95 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070096{
jiabina7b43792018-02-15 16:04:46 -080097 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
98 nextAudioPortGeneration();
99 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100}
101
François Gaffie44481e72016-04-20 07:49:57 +0200102void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
103 audio_policy_dev_state_t state,
104 const String8 &device_address)
105{
106 AudioParameter param(device_address);
107 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700108 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200109 param.addInt(key, device);
110 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
111}
112
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800113status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800114 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800115 const char *device_address,
116 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800117{
Paul McLeane743a472015-01-28 11:07:31 -0800118 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800119 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700120
121 // connect/disconnect only 1 device at a time
122 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
123
François Gaffie53615e22015-03-19 09:24:12 +0100124 sp<DeviceDescriptor> devDesc =
125 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800126
Eric Laurente552edb2014-03-10 17:42:56 -0700127 // handle output devices
128 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700129 SortedVector <audio_io_handle_t> outputs;
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
132
Eric Laurente552edb2014-03-10 17:42:56 -0700133 // save a copy of the opened output descriptors before any output is opened or closed
134 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
135 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700136 switch (state)
137 {
138 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800139 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700141 ALOGW("setDeviceConnectionState() device already connected: %x", device);
142 return INVALID_OPERATION;
143 }
144 ALOGV("setDeviceConnectionState() connecting device %x", device);
145
Eric Laurente552edb2014-03-10 17:42:56 -0700146 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700147 index = mAvailableOutputDevices.add(devDesc);
148 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100149 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700150 if (module == 0) {
151 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
152 device);
153 mAvailableOutputDevices.remove(devDesc);
154 return INVALID_OPERATION;
155 }
Paul McLeane743a472015-01-28 11:07:31 -0800156 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700157 } else {
158 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700159 }
160
François Gaffie44481e72016-04-20 07:49:57 +0200161 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
162 // parameters on newly connected devices (instead of opening the outputs...)
163 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
164
Eric Laurenta1d525f2015-01-29 13:36:45 -0800165 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700166 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200167
168 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
169 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700170 return INVALID_OPERATION;
171 }
François Gaffie2110e042015-03-24 08:41:51 +0100172 // Propagate device availability to Engine
173 mEngine->setDeviceConnectionState(devDesc, state);
174
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700175 // outputs should never be empty here
176 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
177 "checkOutputsForDevice() returned no outputs but status OK");
178 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
179 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800180
Eric Laurent3ae5f312015-02-03 17:12:08 -0800181 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700183 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700185 ALOGW("setDeviceConnectionState() device not connected: %x", device);
186 return INVALID_OPERATION;
187 }
188
Paul McLean5c477aa2014-08-20 16:47:57 -0700189 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
190
Paul McLeane743a472015-01-28 11:07:31 -0800191 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200192 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700196
Eric Laurenta1d525f2015-01-29 13:36:45 -0800197 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100198
199 // Propagate device availability to Engine
200 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700201 } break;
202
203 default:
204 ALOGE("setDeviceConnectionState() invalid state: %x", state);
205 return BAD_VALUE;
206 }
207
Eric Laurent3a4311c2014-03-17 12:00:47 -0700208 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
209 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700210 checkA2dpSuspend();
211 checkOutputForAllStrategies();
212 // outputs must be closed after checkOutputForAllStrategies() is executed
213 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800214 for (audio_io_handle_t output : outputs) {
215 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700216 // close unused outputs after device disconnection or direct outputs that have been
217 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700218 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700219 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
220 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800221 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 }
223 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 // check again after closing A2DP output to reset mA2dpSuspended if needed
225 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700226 }
227
228 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700229 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
231 updateCallRouting(newDevice);
232 }
Eric Laurente552edb2014-03-10 17:42:56 -0700233 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700234 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
235 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
236 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 // do not force device change on duplicated output because if device is 0, it will
238 // also force a device 0 for the two outputs it is duplicated to which may override
239 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700240 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100241 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700242 // always force when disconnecting (a non-duplicated device)
243 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700244 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700245 }
Eric Laurente552edb2014-03-10 17:42:56 -0700246 }
247
Eric Laurentd60560a2015-04-10 11:31:20 -0700248 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
249 cleanUpForDevice(devDesc);
250 }
251
Eric Laurent72aa32f2014-05-30 18:51:48 -0700252 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700253 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700254 } // end if is output device
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 // handle input devices
257 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700258 SortedVector <audio_io_handle_t> inputs;
259
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700261 switch (state)
262 {
263 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700266 ALOGW("setDeviceConnectionState() device already connected: %d", device);
267 return INVALID_OPERATION;
268 }
François Gaffie53615e22015-03-19 09:24:12 +0100269 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700270 if (module == NULL) {
271 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
272 device);
273 return INVALID_OPERATION;
274 }
François Gaffie44481e72016-04-20 07:49:57 +0200275
276 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
277 // parameters on newly connected devices (instead of opening the inputs...)
278 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
279
Paul McLean9080a4c2015-06-18 08:24:02 -0700280 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200281 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
282 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700283 return INVALID_OPERATION;
284 }
285
Eric Laurent3a4311c2014-03-17 12:00:47 -0700286 index = mAvailableInputDevices.add(devDesc);
287 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800288 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700289 } else {
290 return NO_MEMORY;
291 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800292
François Gaffie2110e042015-03-24 08:41:51 +0100293 // Propagate device availability to Engine
294 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700295 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700296
297 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700298 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700300 ALOGW("setDeviceConnectionState() device not connected: %d", device);
301 return INVALID_OPERATION;
302 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
304 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
305
306 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200307 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700308
Paul McLean9080a4c2015-06-18 08:24:02 -0700309 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700310 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700311
François Gaffie2110e042015-03-24 08:41:51 +0100312 // Propagate device availability to Engine
313 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700314 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700315
316 default:
317 ALOGE("setDeviceConnectionState() invalid state: %x", state);
318 return BAD_VALUE;
319 }
320
Eric Laurentd4692962014-05-05 18:13:44 -0700321 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700322 // As the input device list can impact the output device selection, update
323 // getDeviceForStrategy() cache
324 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700325
Eric Laurent87ffa392015-05-22 10:32:38 -0700326 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
328 updateCallRouting(newDevice);
329 }
330
Eric Laurentd60560a2015-04-10 11:31:20 -0700331 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
332 cleanUpForDevice(devDesc);
333 }
334
Eric Laurentb52c1522014-05-20 11:27:36 -0700335 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700336 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700337 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700338
339 ALOGW("setDeviceConnectionState() invalid device: %x", device);
340 return BAD_VALUE;
341}
342
Eric Laurente0720872014-03-11 09:30:41 -0700343audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100344 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700345{
Eric Laurent634b7142016-04-20 13:48:02 -0700346 sp<DeviceDescriptor> devDesc =
347 mHwModules.getDeviceDescriptor(device, device_address, "",
348 (strlen(device_address) != 0)/*matchAddress*/);
349
350 if (devDesc == 0) {
351 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
352 device, device_address);
353 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
354 }
François Gaffie53615e22015-03-19 09:24:12 +0100355
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
363 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
Eric Laurent634b7142016-04-20 13:48:02 -0700366
367 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
368 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800369}
370
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800371status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
372 const char *device_address,
373 const char *device_name)
374{
375 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700376 String8 reply;
377 AudioParameter param;
378 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800379
380 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
381 device, device_address, device_name);
382
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800383 // connect/disconnect only 1 device at a time
384 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
385
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800386 // Check if the device is currently connected
387 sp<DeviceDescriptor> devDesc =
388 mHwModules.getDeviceDescriptor(device, device_address, device_name);
389 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
390 if (index < 0) {
391 // Nothing to do: device is not connected
392 return NO_ERROR;
393 }
394
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700395 // For offloaded A2DP, Hw modules may have the capability to
396 // configure codecs. Check if any of the loaded hw modules
397 // supports this.
398 // If supported, send a set parameter to configure A2DP codecs
399 // and return. No need to toggle device state.
400 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
401 reply = mpClientInterface->getParameters(
402 AUDIO_IO_HANDLE_NONE,
403 String8(AudioParameter::keyReconfigA2dpSupported));
404 AudioParameter repliedParameters(reply);
405 repliedParameters.getInt(
406 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
407 if (isReconfigA2dpSupported) {
408 const String8 key(AudioParameter::keyReconfigA2dp);
409 param.add(key, String8("true"));
410 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
411 return NO_ERROR;
412 }
413 }
414
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800415 // Toggle the device state: UNAVAILABLE -> AVAILABLE
416 // This will force reading again the device configuration
417 status = setDeviceConnectionState(device,
418 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
419 device_address, device_name);
420 if (status != NO_ERROR) {
421 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
422 status);
423 return status;
424 }
425
426 status = setDeviceConnectionState(device,
427 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
428 device_address, device_name);
429 if (status != NO_ERROR) {
430 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
431 status);
432 return status;
433 }
434
435 return NO_ERROR;
436}
437
Eric Laurentdc462862016-07-19 12:29:53 -0700438uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700439{
440 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700441 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442
Andy Hunga76c7de2016-12-13 19:14:31 -0800443 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700444 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700445 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800446 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700447 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
448
449 // release existing RX patch if any
450 if (mCallRxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
452 mCallRxPatch.clear();
453 }
454 // release TX patch if any
455 if (mCallTxPatch != 0) {
456 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
457 mCallTxPatch.clear();
458 }
459
460 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
461 // via setOutputDevice() on primary output.
462 // Otherwise, create two audio patches for TX and RX path.
463 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700464 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700465 // If the TX device is also on the primary HW module, setOutputDevice() will take care
466 // of it due to legacy implementation. If not, create a patch.
467 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
468 == AUDIO_DEVICE_NONE) {
469 createTxPatch = true;
470 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700471 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700473 createTxPatch = true;
474 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700475 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
477 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700478
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 return muteWaitMs;
480}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700481
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
483 bool isRx, audio_devices_t device, uint32_t delayMs) {
484 struct audio_patch patch;
485 patch.num_sources = 1;
486 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700487
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 sp<DeviceDescriptor> txSourceDeviceDesc;
489 if (isRx) {
490 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
491 fillAudioPortConfigForDevice(
492 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
493 } else {
494 txSourceDeviceDesc = fillAudioPortConfigForDevice(
495 mAvailableInputDevices, device, &patch.sources[0]);
496 fillAudioPortConfigForDevice(
497 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
498 }
499
500 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
501 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
502 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
503 // request to reuse existing output stream if one is already opened to reach the target device
504 if (output != AUDIO_IO_HANDLE_NONE) {
505 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
506 ALOG_ASSERT(!outputDesc->isDuplicated(),
507 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
508 outputDesc->toAudioPortConfig(&patch.sources[1]);
509 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
510 patch.num_sources = 2;
511 }
512
513 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700514 // terminate active capture if on the same HW module as the call TX source device
515 // FIXME: would be better to refine to only inputs whose profile connects to the
516 // call TX device but this information is not in the audio patch and logic here must be
517 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800518 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800519 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
520 AudioSessionCollection activeSessions =
521 activeDesc->getAudioSessions(true /*activeOnly*/);
522 for (size_t j = 0; j < activeSessions.size(); j++) {
523 audio_session_t activeSession = activeSessions.keyAt(j);
524 stopInput(activeDesc->mIoHandle, activeSession);
525 releaseInput(activeDesc->mIoHandle, activeSession);
526 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700527 }
528 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700529 }
Eric Laurentdc462862016-07-19 12:29:53 -0700530
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800531 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
532 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
533 ALOGW_IF(status != NO_ERROR,
534 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
535 sp<AudioPatch> audioPatch;
536 if (status == NO_ERROR) {
537 audioPatch = new AudioPatch(&patch, mUidCached);
538 audioPatch->mAfPatchHandle = afPatchHandle;
539 audioPatch->mUid = mUidCached;
540 }
541 return audioPatch;
542}
543
544sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
545 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
546 DeviceVector deviceList = devices.getDevicesFromType(device);
547 ALOG_ASSERT(!deviceList.isEmpty(),
548 "%s() selected device type %#x is not in devices list", __func__, device);
549 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
550 deviceDesc->toAudioPortConfig(config);
551 return deviceDesc;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700552}
553
Eric Laurente0720872014-03-11 09:30:41 -0700554void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700555{
556 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100557 // store previous phone state for management of sonification strategy below
558 int oldState = mEngine->getPhoneState();
559
560 if (mEngine->setPhoneState(state) != NO_ERROR) {
561 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700562 return;
563 }
François Gaffie2110e042015-03-24 08:41:51 +0100564 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700565 // if leaving call state, handle special case of active streams
566 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700567 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700568 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800569 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700570 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800572
Eric Laurent63dea1d2015-07-02 17:10:28 -0700573 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800574 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
576
François Gaffie2110e042015-03-24 08:41:51 +0100577 /**
578 * Switching to or from incall state or switching between telephony and VoIP lead to force
579 * routing command.
580 */
581 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
582 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700583
584 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700585 checkA2dpSuspend();
586 checkOutputForAllStrategies();
587 updateDevicesAndOutputs();
588
Eric Laurente552edb2014-03-10 17:42:56 -0700589 int delayMs = 0;
590 if (isStateInCall(state)) {
591 nsecs_t sysTime = systemTime();
592 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700593 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700594 // mute media and sonification strategies and delay device switch by the largest
595 // latency of any output where either strategy is active.
596 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100597 if ((isStrategyActive(desc, STRATEGY_MEDIA,
598 SONIFICATION_HEADSET_MUSIC_DELAY,
599 sysTime) ||
600 isStrategyActive(desc, STRATEGY_SONIFICATION,
601 SONIFICATION_HEADSET_MUSIC_DELAY,
602 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700603 (delayMs < (int)desc->latency()*2)) {
604 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700605 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700606 setStrategyMute(STRATEGY_MEDIA, true, desc);
607 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700608 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700609 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
610 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700611 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
612 }
613 }
614
Eric Laurent87ffa392015-05-22 10:32:38 -0700615 if (hasPrimaryOutput()) {
616 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
617 // the device returned is not necessarily reachable via this output
618 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
619 // force routing command to audio hardware when ending call
620 // even if no device change is needed
621 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
622 rxDevice = mPrimaryOutput->device();
623 }
Eric Laurente552edb2014-03-10 17:42:56 -0700624
Eric Laurent87ffa392015-05-22 10:32:38 -0700625 if (state == AUDIO_MODE_IN_CALL) {
626 updateCallRouting(rxDevice, delayMs);
627 } else if (oldState == AUDIO_MODE_IN_CALL) {
628 if (mCallRxPatch != 0) {
629 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
630 mCallRxPatch.clear();
631 }
632 if (mCallTxPatch != 0) {
633 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
634 mCallTxPatch.clear();
635 }
636 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
637 } else {
638 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700639 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700640 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700641
642 // reevaluate routing on all outputs in case tracks have been started during the call
643 for (size_t i = 0; i < mOutputs.size(); i++) {
644 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
645 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
646 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800647 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700648 }
649 }
650
Eric Laurente552edb2014-03-10 17:42:56 -0700651 // if entering in call state, handle special case of active streams
652 // pertaining to sonification strategy see handleIncallSonification()
653 if (isStateInCall(state)) {
654 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800655 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700656 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700657 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700658
659 // force reevaluating accessibility routing when call starts
660 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700661 }
662
663 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700664 if (state == AUDIO_MODE_RINGTONE &&
665 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700666 mLimitRingtoneVolume = true;
667 } else {
668 mLimitRingtoneVolume = false;
669 }
670}
671
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700672audio_mode_t AudioPolicyManager::getPhoneState() {
673 return mEngine->getPhoneState();
674}
675
Eric Laurente0720872014-03-11 09:30:41 -0700676void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700677 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700678{
François Gaffie2110e042015-03-24 08:41:51 +0100679 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700680 if (config == mEngine->getForceUse(usage)) {
681 return;
682 }
Eric Laurente552edb2014-03-10 17:42:56 -0700683
François Gaffie2110e042015-03-24 08:41:51 +0100684 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
685 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
686 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
François Gaffie2110e042015-03-24 08:41:51 +0100688 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
689 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
690 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700691
692 // check for device and output changes triggered by new force usage
693 checkA2dpSuspend();
694 checkOutputForAllStrategies();
695 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800696
Eric Laurentdc462862016-07-19 12:29:53 -0700697 //FIXME: workaround for truncated touch sounds
698 // to be removed when the problem is handled by system UI
699 uint32_t delayMs = 0;
700 uint32_t waitMs = 0;
701 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
702 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
703 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700704 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700705 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700706 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700709 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
710 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
711 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700712 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
713 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700714 }
Eric Laurente552edb2014-03-10 17:42:56 -0700715 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700716 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700717 }
718 }
719
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800720 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800721 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700722 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800723 if (activeDesc->mProfile->getSupportedDevices().types() &
724 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
725 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700726 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800727 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700728 }
Eric Laurente552edb2014-03-10 17:42:56 -0700729 }
Eric Laurente552edb2014-03-10 17:42:56 -0700730}
731
Eric Laurente0720872014-03-11 09:30:41 -0700732void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700733{
734 ALOGV("setSystemProperty() property %s, value %s", property, value);
735}
736
737// Find a direct output profile compatible with the parameters passed, even if the input flags do
738// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800739sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700740 audio_devices_t device,
741 uint32_t samplingRate,
742 audio_format_t format,
743 audio_channel_mask_t channelMask,
744 audio_output_flags_t flags)
745{
Eric Laurent861a6282015-05-18 15:40:16 -0700746 // only retain flags that will drive the direct output profile selection
747 // if explicitly requested
748 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700749 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
750 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700751 flags =
752 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
753
754 sp<IOProfile> profile;
755
Mikhail Naganovd4120142017-12-06 15:49:22 -0800756 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800757 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700758 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700759 samplingRate, NULL /*updatedSamplingRate*/,
760 format, NULL /*updatedFormat*/,
761 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700762 flags)) {
763 continue;
764 }
765 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100766 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700767 continue;
768 }
769 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100770 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700771 continue;
772 }
773 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100774 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700775 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700776 }
Eric Laurente552edb2014-03-10 17:42:56 -0700777 }
778 }
Eric Laurent861a6282015-05-18 15:40:16 -0700779 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700780}
781
Eric Laurentf4e63452017-11-06 19:31:46 +0000782audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700783{
Eric Laurent3b73df72014-03-11 09:06:29 -0700784 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700785 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800786
787 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
788 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
789 // format, flags, etc. This may result in some discrepancy for functions that utilize
790 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
791 // and AudioSystem::getOutputSamplingRate().
792
Eric Laurentf4e63452017-11-06 19:31:46 +0000793 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
794 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700795
Eric Laurentf4e63452017-11-06 19:31:46 +0000796 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
797 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700798}
799
Eric Laurente83b55d2014-11-14 10:06:21 -0800800status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
801 audio_io_handle_t *output,
802 audio_session_t session,
803 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700804 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800805 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200806 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700807 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800808 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700809{
Eric Laurente83b55d2014-11-14 10:06:21 -0800810 audio_attributes_t attributes;
811 if (attr != NULL) {
812 if (!isValidAttributes(attr)) {
813 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
814 attr->usage, attr->content_type, attr->flags,
815 attr->tags);
816 return BAD_VALUE;
817 }
818 attributes = *attr;
819 } else {
820 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
821 ALOGE("getOutputForAttr(): invalid stream type");
822 return BAD_VALUE;
823 }
824 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800826
827 // TODO: check for existing client for this port ID
828 if (*portId == AUDIO_PORT_HANDLE_NONE) {
829 *portId = AudioPort::getNextUniqueId();
830 }
831
Eric Laurentc75307b2015-03-17 15:29:32 -0700832 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800833 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100834 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800835 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100836 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800837 }
François Gaffie036e1e92015-03-19 10:16:24 +0100838 *stream = streamTypefromAttributesInt(&attributes);
839 *output = desc->mIoHandle;
840 ALOGV("getOutputForAttr() returns output %d", *output);
841 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800842 }
843 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
844 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
845 return BAD_VALUE;
846 }
847
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700848 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
849 " session %d selectedDeviceId %d",
850 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700851 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700852
853 *stream = streamTypefromAttributesInt(&attributes);
854
855 // Explicit routing?
856 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700857 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800858 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700859 }
860 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700861
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700864
Eric Laurente83b55d2014-11-14 10:06:21 -0800865 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200866 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700867 }
868
Nadav Bar0d143ae2018-07-18 13:01:53 +0300869 // Set incall music only if device was explicitly set, and fallback to the device which is
870 // chosen by the engine if not.
871 // FIXME: provide a more generic approach which is not device specific and move this back
872 // to getOutputForDevice.
873 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
874 *stream == AUDIO_STREAM_MUSIC &&
875 audio_is_linear_pcm(config->format) &&
876 isInCall()) {
877 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
878 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
879 } else {
880 device = mEngine->getDeviceForStrategy(strategy);
881 }
882 }
883
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800884 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
885 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200886 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700887
Andy Hungc88b0642018-04-27 15:42:35 -0700888 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800889 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700890 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800891 return INVALID_OPERATION;
892 }
Paul McLeanaa981192015-03-21 09:55:15 -0700893
Eric Laurent2ac76942017-06-22 17:17:09 -0700894 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
895 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
896 : AUDIO_PORT_HANDLE_NONE;
897
898 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
899
Eric Laurente83b55d2014-11-14 10:06:21 -0800900 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700901}
902
903audio_io_handle_t AudioPolicyManager::getOutputForDevice(
904 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800905 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700906 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800907 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200908 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700909{
Andy Hungc88b0642018-04-27 15:42:35 -0700910 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912
Eric Laurente552edb2014-03-10 17:42:56 -0700913 // open a direct output if required by specified parameters
914 //force direct flag if offload flag is set: offloading implies a direct output stream
915 // and all common behaviors are driven by checking only the direct flag
916 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200917 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
918 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Nadav Bar766fb022018-01-07 12:18:03 +0200920 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
921 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700922 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800923 // only allow deep buffering for music stream type
924 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700926 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200927 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700928 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
929 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200930 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800931 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700932 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200933 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700934 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800935 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200936 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700937 AUDIO_OUTPUT_FLAG_DIRECT);
938 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700939 }
Eric Laurente552edb2014-03-10 17:42:56 -0700940
Nadav Bar766fb022018-01-07 12:18:03 +0200941
Eric Laurentb732cf52014-09-24 19:08:21 -0700942 sp<IOProfile> profile;
943
944 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700945 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200946 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800947 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
948 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700949 goto non_direct_output;
950 }
951
Andy Hung2ddee192015-12-18 17:34:44 -0800952 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
953 // This prevents creating an offloaded track and tearing it down immediately after start
954 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700955 // FIXME: We should check the audio session here but we do not have it in this context.
956 // This may prevent offloading in rare situations where effects are left active by apps
957 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700958
Nadav Bar766fb022018-01-07 12:18:03 +0200959 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800960 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700961 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800962 config->sample_rate,
963 config->format,
964 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200965 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700966 }
967
Eric Laurent1c333e22014-05-20 10:48:17 -0700968 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700969 // exclusive outputs for MMAP and Offload are enforced by different session ids.
970 for (size_t i = 0; i < mOutputs.size(); i++) {
971 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
972 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
973 // reuse direct output if currently open by the same client
974 // and configured with same parameters
975 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700976 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700977 (config->channel_mask == desc->mChannelMask) &&
978 (session == desc->mDirectClientSession)) {
979 desc->mDirectOpenCount++;
980 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
981 mOutputs.keyAt(i), session);
982 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700983 }
984 }
985 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800986
987 if (!profile->canOpenNewIo()) {
988 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
Eric Laurent861a6282015-05-18 15:40:16 -0700990
Eric Laurent3974e3b2017-12-07 17:58:43 -0800991 sp<SwAudioOutputDescriptor> outputDesc =
992 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800993
994 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
995 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
996 : String8("");
997
Nadav Bar766fb022018-01-07 12:18:03 +0200998 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700999
1000 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001001 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001002 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001003 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001004 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1005 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1006 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1007 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1008 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001009 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001010 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001011 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001012 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001013 if (audio_is_linear_pcm(config->format) &&
1014 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001015 goto non_direct_output;
1016 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001017 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001018 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 outputDesc->mRefCount[stream] = 0;
1020 outputDesc->mStopTime[stream] = 0;
1021 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001022 outputDesc->mDirectClientSession = session;
1023
Eric Laurente552edb2014-03-10 17:42:56 -07001024 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001025 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001026 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001027 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001028 return output;
1029 }
1030
Eric Laurentb732cf52014-09-24 19:08:21 -07001031non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001032
1033 // A request for HW A/V sync cannot fallback to a mixed output because time
1034 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001035 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001036 return AUDIO_IO_HANDLE_NONE;
1037 }
1038
Eric Laurente552edb2014-03-10 17:42:56 -07001039 // ignoring channel mask due to downmix capability in mixer
1040
1041 // open a non direct output
1042
1043 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001044 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001045 // get which output is suitable for the specified stream. The actual
1046 // routing change will happen when startOutput() will be called
1047 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1048
Eric Laurent8838a382014-09-08 16:44:28 -07001049 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001050 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1051 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001053 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001054 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001055 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001056
Eric Laurente552edb2014-03-10 17:42:56 -07001057 return output;
1058}
1059
Eric Laurente0720872014-03-11 09:30:41 -07001060audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001061 audio_output_flags_t flags,
1062 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001063{
1064 // select one output among several that provide a path to a particular device or set of
1065 // devices (the list was previously build by getOutputsForDevice()).
1066 // The priority is as follows:
1067 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001068 // 2: the output with the bit depth the closest to the requested one
1069 // 3: the primary output
1070 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001071
1072 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001073 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001074 }
1075 if (outputs.size() == 1) {
1076 return outputs[0];
1077 }
1078
1079 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001080 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1081 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1082 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001083 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1084 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001085
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001086 for (audio_io_handle_t output : outputs) {
1087 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001088 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001089 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1090 continue;
1091 }
Eric Laurent8838a382014-09-08 16:44:28 -07001092 // if a valid format is specified, skip output if not compatible
1093 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001094 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001095 continue;
1096 }
Eric Laurente6930022016-02-11 10:20:40 -08001097 if (AudioPort::isBetterFormatMatch(
1098 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001099 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001100 bestFormat = outputDesc->mFormat;
1101 }
Eric Laurent8838a382014-09-08 16:44:28 -07001102 }
1103
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001104 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001105 if (commonFlags >= maxCommonFlags) {
1106 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001107 if (format != AUDIO_FORMAT_INVALID
1108 && AudioPort::isBetterFormatMatch(
1109 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001110 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001111 bestFormatForFlags = outputDesc->mFormat;
1112 }
1113 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001114 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001115 maxCommonFlags = commonFlags;
1116 bestFormatForFlags = outputDesc->mFormat;
1117 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001118 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001119 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001120 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001121 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001122 }
1123 }
1124 }
1125
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001126 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001127 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001128 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001129 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001130 return outputForFormat;
1131 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001132 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001133 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
1135
1136 return outputs[0];
1137}
1138
Eric Laurente0720872014-03-11 09:30:41 -07001139status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001140 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001141 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001142{
Paul McLeanaa981192015-03-21 09:55:15 -07001143 ALOGV("startOutput() output %d, stream %d, session %d",
1144 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001145 ssize_t index = mOutputs.indexOfKey(output);
1146 if (index < 0) {
1147 ALOGW("startOutput() unknown output %d", output);
1148 return BAD_VALUE;
1149 }
1150
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1152
Eric Laurent733ce942017-12-07 12:18:25 -08001153 status_t status = outputDesc->start();
1154 if (status != NO_ERROR) {
1155 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001156 }
1157
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001158 // Routing?
1159 mOutputRoutes.incRouteActivity(session);
1160
Eric Laurentc75307b2015-03-17 15:29:32 -07001161 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001162 AudioMix *policyMix = NULL;
1163 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001164 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001165 policyMix = outputDesc->mPolicyMix;
1166 address = policyMix->mDeviceAddress.string();
1167 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1168 newDevice = policyMix->mDeviceType;
1169 } else {
1170 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1171 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001172 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001173 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001174 if (newDevice != outputDesc->device()) {
1175 checkStrategyRoute(getStrategy(stream), output);
1176 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001177 } else {
1178 newDevice = AUDIO_DEVICE_NONE;
1179 }
1180
1181 uint32_t delayMs = 0;
1182
Eric Laurent733ce942017-12-07 12:18:25 -08001183 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001184
1185 if (status != NO_ERROR) {
1186 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001187 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001188 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001189 }
1190 // Automatically enable the remote submix input when output is started on a re routing mix
1191 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001192 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1193 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1195 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001196 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001197 "remote-submix");
1198 }
1199
1200 if (delayMs != 0) {
1201 usleep(delayMs * 1000);
1202 }
1203
1204 return status;
1205}
1206
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001207status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001208 audio_stream_type_t stream,
1209 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001210 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001211 uint32_t *delayMs)
1212{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001213 // cannot start playback of STREAM_TTS if any other output is being used
1214 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001215
1216 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001217 if (stream == AUDIO_STREAM_TTS) {
1218 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001219 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001220 return INVALID_OPERATION;
1221 } else {
1222 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1223 }
1224 } else {
1225 // some playback other than beacon starts
1226 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1227 }
1228
Eric Laurent77305a62016-07-25 16:39:22 -07001229 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001230 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001231 bool force = !outputDesc->isActive() &&
1232 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001233
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001234 // requiresMuteCheck is false when we can bypass mute strategy.
1235 // It covers a common case when there is no materially active audio
1236 // and muting would result in unnecessary delay and dropped audio.
1237 const uint32_t outputLatencyMs = outputDesc->latency();
1238 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1239
Eric Laurente552edb2014-03-10 17:42:56 -07001240 // increment usage count for this stream on the requested output:
1241 // NOTE that the usage count is the same for duplicated output and hardware output which is
1242 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1243 outputDesc->changeRefCount(stream, 1);
1244
Eric Laurent36829f92017-04-07 19:04:42 -07001245 if (stream == AUDIO_STREAM_MUSIC) {
1246 selectOutputForMusicEffects();
1247 }
1248
Eric Laurent493404d2015-04-21 15:07:36 -07001249 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001250 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001251 if (device == AUDIO_DEVICE_NONE) {
1252 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001253 }
Eric Laurent36829f92017-04-07 19:04:42 -07001254
Eric Laurente552edb2014-03-10 17:42:56 -07001255 routing_strategy strategy = getStrategy(stream);
1256 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001257 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1258 (beaconMuteLatency > 0);
1259 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001260 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001261 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001262 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001263 // An output has a shared device if
1264 // - managed by the same hw module
1265 // - supports the currently selected device
1266 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1267 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1268
Eric Laurent77305a62016-07-25 16:39:22 -07001269 // force a device change if any other output is:
1270 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001271 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001272 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001273 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001274 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001275 // change the device currently selected by the other output.
1276 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001277 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001278 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001279 force = true;
1280 }
1281 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001282 // a notification so that audio focus effect can propagate, or that a mute/unmute
1283 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001284 const uint32_t latencyMs = desc->latency();
1285 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1286
1287 if (shouldWait && isActive && (waitMs < latencyMs)) {
1288 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001289 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001290
1291 // Require mute check if another output is on a shared device
1292 // and currently active to have proper drain and avoid pops.
1293 // Note restoring AudioTracks onto this output needs to invoke
1294 // a volume ramp if there is no mute.
1295 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
1297 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001298
1299 const uint32_t muteWaitMs =
1300 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001301
1302 // handle special case for sonification while in call
1303 if (isInCall()) {
1304 handleIncallSonification(stream, true, false);
1305 }
1306
1307 // apply volume rules for current stream and device if necessary
1308 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001309 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001310 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001311 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001312
1313 // update the outputs if starting an output with a stream that can affect notification
1314 // routing
1315 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001316
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001317 // force reevaluating accessibility routing when ringtone or alarm starts
1318 if (strategy == STRATEGY_SONIFICATION) {
1319 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1320 }
Eric Laurentdc462862016-07-19 12:29:53 -07001321
1322 if (waitMs > muteWaitMs) {
1323 *delayMs = waitMs - muteWaitMs;
1324 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001325
1326 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1327 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1328 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1329 // change occurs after the MixerThread starts and causes a stream volume
1330 // glitch.
1331 //
1332 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001333 }
Eric Laurentdc462862016-07-19 12:29:53 -07001334
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001335 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1336 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1337 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1338 }
1339
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001340 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1341 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1342 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1343 }
1344
Eric Laurente552edb2014-03-10 17:42:56 -07001345 return NO_ERROR;
1346}
1347
1348
Eric Laurente0720872014-03-11 09:30:41 -07001349status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001350 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001351 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001352{
1353 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1354 ssize_t index = mOutputs.indexOfKey(output);
1355 if (index < 0) {
1356 ALOGW("stopOutput() unknown output %d", output);
1357 return BAD_VALUE;
1358 }
1359
Eric Laurentc75307b2015-03-17 15:29:32 -07001360 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001361
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 if (outputDesc->mRefCount[stream] == 1) {
1363 // Automatically disable the remote submix input when output is stopped on a
1364 // re routing mix of type MIX_TYPE_RECORDERS
1365 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1366 outputDesc->mPolicyMix != NULL &&
1367 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1368 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1369 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001370 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 "remote-submix");
1372 }
1373 }
1374
1375 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001376 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001377 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001378 int activityCount = mOutputRoutes.decRouteActivity(session);
1379 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1380
1381 if (forceDeviceUpdate) {
1382 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1383 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001384 }
1385
Eric Laurent3974e3b2017-12-07 17:58:43 -08001386 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1387
Eric Laurent733ce942017-12-07 12:18:25 -08001388 if (status == NO_ERROR ) {
1389 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001390 }
1391 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001392}
1393
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001394status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001395 audio_stream_type_t stream,
1396 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001397{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001398 // always handle stream stop, check which stream type is stopping
1399 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1400
Eric Laurente552edb2014-03-10 17:42:56 -07001401 // handle special case for sonification while in call
1402 if (isInCall()) {
1403 handleIncallSonification(stream, false, false);
1404 }
1405
1406 if (outputDesc->mRefCount[stream] > 0) {
1407 // decrement usage count of this stream on the output
1408 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001409
Eric Laurente552edb2014-03-10 17:42:56 -07001410 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001411 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001412 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001413 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001414 // delay the device switch by twice the latency because stopOutput() is executed when
1415 // the track stop() command is received and at that time the audio track buffer can
1416 // still contain data that needs to be drained. The latency only covers the audio HAL
1417 // and kernel buffers. Also the latency does not always include additional delay in the
1418 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001419 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001420
1421 // force restoring the device selection on other active outputs if it differs from the
1422 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001423 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001424 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001426 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001427 desc->isActive() &&
1428 outputDesc->sharesHwModuleWith(desc) &&
1429 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001430 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1431 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001432
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001434 newDevice2,
1435 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001436 delayMs);
1437 // re-apply device specific volume if not done by setOutputDevice()
1438 if (!force) {
1439 applyStreamVolumes(desc, newDevice2, delayMs);
1440 }
Eric Laurente552edb2014-03-10 17:42:56 -07001441 }
1442 }
1443 // update the outputs if stopping one with a stream that can affect notification routing
1444 handleNotificationRoutingForStream(stream);
1445 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001446
1447 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1448 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1449 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1450 }
1451
Eric Laurent36829f92017-04-07 19:04:42 -07001452 if (stream == AUDIO_STREAM_MUSIC) {
1453 selectOutputForMusicEffects();
1454 }
Eric Laurente552edb2014-03-10 17:42:56 -07001455 return NO_ERROR;
1456 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001457 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001458 return INVALID_OPERATION;
1459 }
1460}
1461
Eric Laurente83b55d2014-11-14 10:06:21 -08001462void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001463 audio_stream_type_t stream __unused,
1464 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001465{
1466 ALOGV("releaseOutput() %d", output);
1467 ssize_t index = mOutputs.indexOfKey(output);
1468 if (index < 0) {
1469 ALOGW("releaseOutput() releasing unknown output %d", output);
1470 return;
1471 }
1472
Paul McLeanaa981192015-03-21 09:55:15 -07001473 // Routing
1474 mOutputRoutes.removeRoute(session);
1475
Eric Laurentc75307b2015-03-17 15:29:32 -07001476 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001477 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001478 if (desc->mDirectOpenCount <= 0) {
1479 ALOGW("releaseOutput() invalid open count %d for output %d",
1480 desc->mDirectOpenCount, output);
1481 return;
1482 }
1483 if (--desc->mDirectOpenCount == 0) {
1484 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001485 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
1487 }
1488}
1489
1490
Eric Laurentcaf7f482014-11-25 17:50:47 -08001491status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1492 audio_io_handle_t *input,
1493 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001494 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001496 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001497 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001498 input_type_t *inputType,
1499 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001500{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001501 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001502 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001503 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001504
Eric Laurentad2e7b92017-09-14 20:06:42 -07001505 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001506 // handle legacy remote submix case where the address was not always specified
1507 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001508 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001509 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001510 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001511 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001512
Eric Laurentfe231122017-11-17 17:48:06 -08001513 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1514 inputSource = AUDIO_SOURCE_MIC;
1515 }
1516
Paul McLean466dc8e2015-04-17 13:15:36 -06001517 // Explicit routing?
1518 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001519 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001520 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001521 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001522 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001523
Eric Laurentad2e7b92017-09-14 20:06:42 -07001524 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1525 // possible
1526 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1527 *input != AUDIO_IO_HANDLE_NONE) {
1528 ssize_t index = mInputs.indexOfKey(*input);
1529 if (index < 0) {
1530 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1531 status = BAD_VALUE;
1532 goto error;
1533 }
1534 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1535 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1536 if (audioSession == 0) {
1537 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1538 status = BAD_VALUE;
1539 goto error;
1540 }
1541 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1542 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001543 // corresponds to a new client and is only permitted from the same UID.
1544 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001545 if (audioSession->openCount() == 1) {
1546 audioSession->setUid(uid);
1547 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001548 if (!audioSession->isSilenced()) {
1549 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1550 uid, session, audioSession->uid());
1551 status = INVALID_OPERATION;
1552 goto error;
1553 }
1554 audioSession->setUid(uid);
1555 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001556 }
1557 audioSession->changeOpenCount(1);
1558 *inputType = API_INPUT_LEGACY;
1559 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1560 *portId = AudioPort::getNextUniqueId();
1561 }
1562 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1563 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1564 : AUDIO_PORT_HANDLE_NONE;
1565 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1566
1567 return NO_ERROR;
1568 }
1569
1570 *input = AUDIO_IO_HANDLE_NONE;
1571 *inputType = API_INPUT_INVALID;
1572
Eric Laurentad2e7b92017-09-14 20:06:42 -07001573 halInputSource = inputSource;
1574
1575 // TODO: check for existing client for this port ID
1576 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1577 *portId = AudioPort::getNextUniqueId();
1578 }
1579
1580 audio_devices_t device;
1581
Eric Laurentc447ded2015-01-06 08:47:05 -08001582 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001583 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001584 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1585 if (status != NO_ERROR) {
1586 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001587 }
1588 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001589 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1590 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001591 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001592 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001593 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001594 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001595 status = BAD_VALUE;
1596 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001597 }
Eric Laurentc722f302014-12-10 11:21:49 -08001598 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001599 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001600 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1601 // there is an external policy, but this input is attached to a mix of recorders,
1602 // meaning it receives audio injected into the framework, so the recorder doesn't
1603 // know about it and is therefore considered "legacy"
1604 *inputType = API_INPUT_LEGACY;
1605 } else {
1606 // recording a mix of players defined by an external policy, we're rerouting for
1607 // an external policy
1608 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1609 }
Eric Laurentc722f302014-12-10 11:21:49 -08001610 } else if (audio_is_remote_submix_device(device)) {
1611 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001612 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001613 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1614 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001615 } else {
1616 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001617 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001618
Eric Laurent599c7582015-12-07 18:05:55 -08001619 }
1620
1621 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001622 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001623 policyMix);
1624 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001625 status = INVALID_OPERATION;
1626 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001627 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001628
Eric Laurentad2e7b92017-09-14 20:06:42 -07001629 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001630 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1631 : AUDIO_PORT_HANDLE_NONE;
1632
1633 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1634 *input, *inputType, *selectedDeviceId);
1635
Eric Laurent599c7582015-12-07 18:05:55 -08001636 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001637
1638error:
1639 mInputRoutes.removeRoute(session);
1640 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001641}
1642
1643
1644audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1645 String8 address,
1646 audio_session_t session,
1647 uid_t uid,
1648 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001649 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001650 audio_input_flags_t flags,
1651 AudioMix *policyMix)
1652{
1653 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1654 audio_source_t halInputSource = inputSource;
1655 bool isSoundTrigger = false;
1656
1657 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1658 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1659 if (index >= 0) {
1660 input = mSoundTriggerSessions.valueFor(session);
1661 isSoundTrigger = true;
1662 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1663 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1664 } else {
1665 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001666 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001667 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001668 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001669 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001670 }
1671
Andy Hungf129b032015-04-07 13:45:50 -07001672 // find a compatible input profile (not necessarily identical in parameters)
1673 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001674 // sampling rate and flags may be updated by getInputProfile
1675 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1676 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001677 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001678 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001679 audio_input_flags_t profileFlags = flags;
1680 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001681 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001682 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001683 profileSamplingRate, profileFormat, profileChannelMask,
1684 profileFlags);
1685 if (profile != 0) {
1686 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001687 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1688 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001689 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1690 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1691 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001692 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001693 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1694 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001695 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001696 }
Eric Laurente552edb2014-03-10 17:42:56 -07001697 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001698 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001699 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001700 if (samplingRate == 0) {
1701 samplingRate = profileSamplingRate;
1702 }
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Eric Laurent322b4d22015-04-03 15:57:54 -07001704 if (profile->getModuleHandle() == 0) {
1705 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001706 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001707 }
1708
Eric Laurent599c7582015-12-07 18:05:55 -08001709 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001710 inputSource,
1711 config->format,
1712 samplingRate,
1713 config->channel_mask,
1714 flags,
1715 uid,
1716 isSoundTrigger,
1717 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001718
Eric Laurent74708e72017-04-07 17:13:42 -07001719// FIXME: disable concurrent capture until UI is ready
1720#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001721 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001722 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001723 for (size_t i = 0; i < mInputs.size(); i++) {
1724 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001725 // reuse input if:
1726 // - it shares the same profile
1727 // AND
1728 // - it is not a reroute submix input
1729 // AND
1730 // - it is: not used for sound trigger
1731 // OR
1732 // used for sound trigger and all clients use the same session ID
1733 //
1734 if ((profile == desc->mProfile) &&
1735 (isSoundTrigger == desc->isSoundTrigger()) &&
1736 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001737
1738 sp<AudioSession> as = desc->getAudioSession(session);
1739 if (as != 0) {
1740 // do not allow unmatching properties on same session
1741 if (as->matches(audioSession)) {
1742 as->changeOpenCount(1);
1743 } else {
1744 ALOGW("getInputForDevice() record with different attributes"
1745 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001746 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001747 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001748 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001749 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001750 }
Eric Laurentbb948092017-01-23 18:33:30 -08001751
Eric Laurent555530a2017-02-07 18:17:24 -08001752 // Reuse the already opened input stream on this profile if:
1753 // - the new capture source is background OR
1754 // - the path requested configurations match OR
1755 // - the new source priority is less than the highest source priority on this input
1756 // If the input stream cannot be reused, close it before opening a new stream
1757 // on the same profile for the new client so that the requested path configuration
1758 // can be selected.
1759 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001760 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001761 desc->mChannelMask != config->channel_mask ||
1762 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001763 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001764 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001765 reusedInputDesc = desc;
1766 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001767 } else {
1768 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001769 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1770 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001771 }
Eric Laurent599c7582015-12-07 18:05:55 -08001772 }
1773 }
Eric Laurent599c7582015-12-07 18:05:55 -08001774
Eric Laurent555530a2017-02-07 18:17:24 -08001775 if (reusedInputDesc != 0) {
1776 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1777 for (size_t j = 0; j < sessions.size(); j++) {
1778 audio_session_t currentSession = sessions.keyAt(j);
1779 stopInput(reusedInputDesc->mIoHandle, currentSession);
1780 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1781 }
1782 }
Eric Laurent74708e72017-04-07 17:13:42 -07001783#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001784
Eric Laurent3974e3b2017-12-07 17:58:43 -08001785 if (!profile->canOpenNewIo()) {
1786 return AUDIO_IO_HANDLE_NONE;
1787 }
1788
Eric Laurentfe231122017-11-17 17:48:06 -08001789 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001790
Eric Laurentfe231122017-11-17 17:48:06 -08001791 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1792 lConfig.sample_rate = profileSamplingRate;
1793 lConfig.channel_mask = profileChannelMask;
1794 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001795
Eric Laurent53b810e2017-12-10 17:25:10 -08001796 if (address == "") {
1797 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1798 // the inputs vector must be of size >= 1, but we don't want to crash here
1799 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1800 }
1801
Eric Laurentfe231122017-11-17 17:48:06 -08001802 status_t status = inputDesc->open(&lConfig, device, address,
1803 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001804
1805 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001806 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001807 (profileSamplingRate != lConfig.sample_rate) ||
1808 !audio_formats_match(profileFormat, lConfig.format) ||
1809 (profileChannelMask != lConfig.channel_mask)) {
1810 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001811 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001812 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001813 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001814 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001815 }
Eric Laurent599c7582015-12-07 18:05:55 -08001816 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001817 }
1818
Eric Laurentc722f302014-12-10 11:21:49 -08001819 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001820 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001821
Eric Laurent599c7582015-12-07 18:05:55 -08001822 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001823 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001824
Eric Laurent599c7582015-12-07 18:05:55 -08001825 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001826}
1827
Eric Laurentbb948092017-01-23 18:33:30 -08001828//static
1829bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1830{
1831 return (source == AUDIO_SOURCE_HOTWORD) ||
1832 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1833 (source == AUDIO_SOURCE_FM_TUNER);
1834}
1835
Eric Laurentfb66dd92016-01-28 18:32:03 -08001836bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1837 const sp<AudioSession>& audioSession)
1838{
1839 // Do not allow capture if an active voice call is using a software patch and
1840 // the call TX source device is on the same HW module.
1841 // FIXME: would be better to refine to only inputs whose profile connects to the
1842 // call TX device but this information is not in the audio patch
1843 if (mCallTxPatch != 0 &&
1844 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1845 return false;
1846 }
1847
1848 // starting concurrent capture is enabled if:
1849 // 1) capturing for re-routing
1850 // 2) capturing for HOTWORD source
1851 // 3) capturing for FM TUNER source
1852 // 3) All other active captures are either for re-routing or HOTWORD
1853
1854 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001855 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001856 return true;
1857 }
1858
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001859 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001860 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001861 !is_virtual_input_device(activeInput->mDevice)) {
1862 return false;
1863 }
1864 }
1865
1866 return true;
1867}
1868
Chris Thornton2b864642017-06-27 21:26:07 -07001869// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1870bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1871 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1872 bool soundTriggerSupportsConcurrentCapture = false;
1873 unsigned int numModules = 0;
1874 struct sound_trigger_module_descriptor* nModules = NULL;
1875
1876 status_t status = SoundTrigger::listModules(nModules, &numModules);
1877 if (status == NO_ERROR && numModules != 0) {
1878 nModules = (struct sound_trigger_module_descriptor*) calloc(
1879 numModules, sizeof(struct sound_trigger_module_descriptor));
1880 if (nModules == NULL) {
1881 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1882 // ram the next time this function is called.
1883 ALOGE("Failed to allocate buffer for module descriptors");
1884 return false;
1885 }
1886
1887 status = SoundTrigger::listModules(nModules, &numModules);
1888 if (status == NO_ERROR) {
1889 soundTriggerSupportsConcurrentCapture = true;
1890 for (size_t i = 0; i < numModules; ++i) {
1891 soundTriggerSupportsConcurrentCapture &=
1892 nModules[i].properties.concurrent_capture;
1893 }
1894 }
1895 free(nModules);
1896 }
1897 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1898 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1899 }
1900 return mSoundTriggerSupportsConcurrentCapture;
1901}
1902
Eric Laurentfb66dd92016-01-28 18:32:03 -08001903
Eric Laurent4dc68062014-07-28 17:26:49 -07001904status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001905 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001906 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001907 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001909
1910 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1911 input, session, silenced, *concurrency);
1912
Eric Laurentfb66dd92016-01-28 18:32:03 -08001913 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001914
Eric Laurente552edb2014-03-10 17:42:56 -07001915 ssize_t index = mInputs.indexOfKey(input);
1916 if (index < 0) {
1917 ALOGW("startInput() unknown input %d", input);
1918 return BAD_VALUE;
1919 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001920 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001921
Eric Laurent599c7582015-12-07 18:05:55 -08001922 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1923 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001924 ALOGW("startInput() unknown session %d on input %d", session, input);
1925 return BAD_VALUE;
1926 }
1927
Eric Laurent74708e72017-04-07 17:13:42 -07001928// FIXME: disable concurrent capture until UI is ready
1929#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001930 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1931 ALOGW("startInput(%d) failed: other input already started", input);
1932 return INVALID_OPERATION;
1933 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001934
Eric Laurentfb66dd92016-01-28 18:32:03 -08001935 if (isInCall()) {
1936 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1937 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001938 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001939 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001940 }
Eric Laurent74708e72017-04-07 17:13:42 -07001941#else
1942 if (!is_virtual_input_device(inputDesc->mDevice)) {
1943 if (mCallTxPatch != 0 &&
1944 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1945 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001946 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001947 return INVALID_OPERATION;
1948 }
1949
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001950 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001951
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001952 // If a UID is idle and records silence and another not silenced recording starts
1953 // from another UID (idle or active) we stop the current idle UID recording in
1954 // favor of the new one - "There can be only one" TM
1955 if (!silenced) {
1956 for (const auto& activeDesc : activeInputs) {
1957 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1958 activeDesc->getId() == inputDesc->getId()) {
1959 continue;
1960 }
1961
1962 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1963 true /*activeOnly*/);
1964 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1965 if (activeSession->isSilenced()) {
1966 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1967 audio_session_t activeSessionId = activeSession->session();
1968 stopInput(activeInput, activeSessionId);
1969 releaseInput(activeInput, activeSessionId);
1970 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1971 activeInputs = mInputs.getActiveInputs();
1972 }
1973 }
1974 }
1975
1976 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001977 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1978 activeDesc->getId() == inputDesc->getId()) {
1979 continue;
1980 }
1981
Eric Laurent74708e72017-04-07 17:13:42 -07001982 audio_source_t activeSource = activeDesc->inputSource(true);
1983 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1984 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1985 if (activeDesc->hasPreemptedSession(session)) {
1986 ALOGW("startInput(%d) failed for HOTWORD: "
1987 "other input %d already started for HOTWORD",
1988 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001989 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001990 return INVALID_OPERATION;
1991 }
1992 } else {
1993 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1994 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001995 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001996 return INVALID_OPERATION;
1997 }
1998 } else {
1999 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2000 ALOGW("startInput(%d) failed: other input %d already started",
2001 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002002 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002003 return INVALID_OPERATION;
2004 }
2005 }
2006 }
2007
Chris Thornton2b864642017-06-27 21:26:07 -07002008 // We only need to check if the sound trigger session supports concurrent capture if the
2009 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2010 // that's running.
2011 const bool allowConcurrentWithSoundTrigger =
2012 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2013
Eric Laurent74708e72017-04-07 17:13:42 -07002014 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002015 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002016 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2017 continue;
2018 }
2019
Eric Laurent74708e72017-04-07 17:13:42 -07002020 audio_source_t activeSource = activeDesc->inputSource(true);
2021 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2022 AudioSessionCollection activeSessions =
2023 activeDesc->getAudioSessions(true /*activeOnly*/);
2024 audio_session_t activeSession = activeSessions.keyAt(0);
2025 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2026 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002027 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002028 sessions.add(activeSession);
2029 inputDesc->setPreemptedSessions(sessions);
2030 stopInput(activeHandle, activeSession);
2031 releaseInput(activeHandle, activeSession);
2032 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2033 input, activeDesc->mIoHandle);
2034 }
2035 }
2036 }
2037#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002038
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002039 // Make sure we start with the correct silence state
2040 audioSession->setSilenced(silenced);
2041
Eric Laurent313d1e72016-01-29 09:56:57 -08002042 // increment activity count before calling getNewInputDevice() below as only active sessions
2043 // are considered for device selection
2044 audioSession->changeActiveCount(1);
2045
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002046 // Routing?
2047 mInputRoutes.incRouteActivity(session);
2048
Eric Laurent2157f5b2018-04-25 18:33:02 -07002049 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002050 // indicate active capture to sound trigger service if starting capture from a mic on
2051 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002052 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002053 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002054
Eric Laurent733ce942017-12-07 12:18:25 -08002055 status_t status = inputDesc->start();
2056 if (status != NO_ERROR) {
2057 mInputRoutes.decRouteActivity(session);
2058 audioSession->changeActiveCount(-1);
2059 return status;
2060 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002061
Eric Laurent733ce942017-12-07 12:18:25 -08002062 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002063 // if input maps to a dynamic policy with an activity listener, notify of state change
2064 if ((inputDesc->mPolicyMix != NULL)
2065 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2066 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2067 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002068 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002069
Eric Laurentf7c50102016-09-30 15:19:43 -07002070 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2071 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002072 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002073 SoundTrigger::setCaptureState(true);
2074 }
2075
2076 // automatically enable the remote submix output when input is started if not
2077 // used by a policy mix of type MIX_TYPE_RECORDERS
2078 // For remote submix (a virtual device), we open only one input per capture request.
2079 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2080 String8 address = String8("");
2081 if (inputDesc->mPolicyMix == NULL) {
2082 address = String8("0");
2083 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2084 address = inputDesc->mPolicyMix->mDeviceAddress;
2085 }
2086 if (address != "") {
2087 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2088 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2089 address, "remote-submix");
2090 }
Eric Laurentc722f302014-12-10 11:21:49 -08002091 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002092 }
Eric Laurente552edb2014-03-10 17:42:56 -07002093 }
2094
Eric Laurent599c7582015-12-07 18:05:55 -08002095 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002096
Eric Laurente552edb2014-03-10 17:42:56 -07002097 return NO_ERROR;
2098}
2099
Eric Laurent4dc68062014-07-28 17:26:49 -07002100status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2101 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002102{
2103 ALOGV("stopInput() input %d", input);
2104 ssize_t index = mInputs.indexOfKey(input);
2105 if (index < 0) {
2106 ALOGW("stopInput() unknown input %d", input);
2107 return BAD_VALUE;
2108 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002109 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002110
Eric Laurent599c7582015-12-07 18:05:55 -08002111 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002112 if (index < 0) {
2113 ALOGW("stopInput() unknown session %d on input %d", session, input);
2114 return BAD_VALUE;
2115 }
2116
Eric Laurent599c7582015-12-07 18:05:55 -08002117 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002118 ALOGW("stopInput() input %d already stopped", input);
2119 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002120 }
2121
Eric Laurent599c7582015-12-07 18:05:55 -08002122 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002123
2124 // Routing?
2125 mInputRoutes.decRouteActivity(session);
2126
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002127 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002128 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002129 if (inputDesc->isActive()) {
2130 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2131 } else {
2132 // if input maps to a dynamic policy with an activity listener, notify of state change
2133 if ((inputDesc->mPolicyMix != NULL)
2134 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2135 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2136 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002137 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002138
2139 // automatically disable the remote submix output when input is stopped if not
2140 // used by a policy mix of type MIX_TYPE_RECORDERS
2141 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2142 String8 address = String8("");
2143 if (inputDesc->mPolicyMix == NULL) {
2144 address = String8("0");
2145 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2146 address = inputDesc->mPolicyMix->mDeviceAddress;
2147 }
2148 if (address != "") {
2149 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2150 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2151 address, "remote-submix");
2152 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002153 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002154
Eric Laurentf7c50102016-09-30 15:19:43 -07002155 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002156 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002157
Eric Laurentf7c50102016-09-30 15:19:43 -07002158 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2159 // primary HW module
2160 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2161 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2162 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002163 SoundTrigger::setCaptureState(false);
2164 }
2165 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002166 }
Eric Laurente552edb2014-03-10 17:42:56 -07002167 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002168 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002169}
2170
Eric Laurent4dc68062014-07-28 17:26:49 -07002171void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2172 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002173{
2174 ALOGV("releaseInput() %d", input);
2175 ssize_t index = mInputs.indexOfKey(input);
2176 if (index < 0) {
2177 ALOGW("releaseInput() releasing unknown input %d", input);
2178 return;
2179 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002180
2181 // Routing
2182 mInputRoutes.removeRoute(session);
2183
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002184 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2185 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002186
Eric Laurent599c7582015-12-07 18:05:55 -08002187 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002188 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002189 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2190 return;
2191 }
Eric Laurent599c7582015-12-07 18:05:55 -08002192
2193 if (audioSession->openCount() == 0) {
2194 ALOGW("releaseInput() invalid open count %d on session %d",
2195 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002196 return;
2197 }
Eric Laurent599c7582015-12-07 18:05:55 -08002198
2199 if (audioSession->changeOpenCount(-1) == 0) {
2200 inputDesc->removeAudioSession(session);
2201 }
2202
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002203 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002204 ALOGV("releaseInput() exit > 0");
2205 return;
2206 }
2207
Eric Laurent05b90f82014-08-27 15:32:29 -07002208 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002209 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002210 ALOGV("releaseInput() exit");
2211}
2212
Eric Laurentd4692962014-05-05 18:13:44 -07002213void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002214 bool patchRemoved = false;
2215
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002216 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002217 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002218 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002219 if (patch_index >= 0) {
2220 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002221 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002222 mAudioPatches.removeItemsAt(patch_index);
2223 patchRemoved = true;
2224 }
Eric Laurentfe231122017-11-17 17:48:06 -08002225 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002226 }
jiabin829a00b2018-04-04 16:28:32 -07002227 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002228 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002229 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002230 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002231
2232 if (patchRemoved) {
2233 mpClientInterface->onAudioPatchListUpdate();
2234 }
Eric Laurentd4692962014-05-05 18:13:44 -07002235}
2236
Eric Laurente0720872014-03-11 09:30:41 -07002237void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002238 int indexMin,
2239 int indexMax)
2240{
2241 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002242 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002243
2244 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002245 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2246 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002247 continue;
2248 }
2249 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002250 }
Eric Laurente552edb2014-03-10 17:42:56 -07002251}
2252
Eric Laurente0720872014-03-11 09:30:41 -07002253status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002254 int index,
2255 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002256{
2257
Nadav Bar7c605f62017-12-25 00:01:52 +02002258 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2259 // app that has MODIFY_PHONE_STATE permission.
2260 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2261 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002262 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002263 return BAD_VALUE;
2264 }
2265 if (!audio_is_output_device(device)) {
2266 return BAD_VALUE;
2267 }
2268
2269 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002270 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002271
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002273 stream, device, index);
2274
Eric Laurent28d09f02016-03-08 10:43:05 -08002275 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002276 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2277 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 continue;
2279 }
2280 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282
Eric Laurent1fd372e2016-04-06 14:23:53 -07002283 // update volume on all outputs and streams matching the following:
2284 // - The requested stream (or a stream matching for volume control) is active on the output
2285 // - The device (or devices) selected by the strategy corresponding to this stream includes
2286 // the requested device
2287 // - For non default requested device, currently selected device on the output is either the
2288 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002289 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2290 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002291 status_t status = NO_ERROR;
2292 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002293 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002294 audio_devices_t curDevice = desc->device();
Eric Laurent794fde22016-03-11 09:50:45 -08002295 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2296 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002297 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002298 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002299 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2300 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002301 continue;
2302 }
Eric Laurent794fde22016-03-11 09:50:45 -08002303 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002304 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2305 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002306 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2307 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002308 continue;
2309 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002310 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002311 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002312 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002313 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002314 } else {
2315 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002316 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002317 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002318
Eric Laurente76f29c2016-09-14 17:17:53 -07002319 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002320 //FIXME: workaround for truncated touch sounds
2321 // delayed volume change for system stream to be removed when the problem is
2322 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002323 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002324 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2325 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002326 if (volStatus != NO_ERROR) {
2327 status = volStatus;
2328 }
2329 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002330 }
Eric Laurente552edb2014-03-10 17:42:56 -07002331 }
2332 return status;
2333}
2334
Eric Laurente0720872014-03-11 09:30:41 -07002335status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002336 int *index,
2337 audio_devices_t device)
2338{
2339 if (index == NULL) {
2340 return BAD_VALUE;
2341 }
2342 if (!audio_is_output_device(device)) {
2343 return BAD_VALUE;
2344 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002345 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002346 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002347 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002348 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2349 }
François Gaffiedfd74092015-03-19 12:10:59 +01002350 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002351
François Gaffied1ab2bd2015-12-02 18:20:06 +01002352 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002353 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2354 return NO_ERROR;
2355}
2356
Eric Laurent36829f92017-04-07 19:04:42 -07002357audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002358{
2359 // select one output among several suitable for global effects.
2360 // The priority is as follows:
2361 // 1: An offloaded output. If the effect ends up not being offloadable,
2362 // AudioFlinger will invalidate the track and the offloaded output
2363 // will be closed causing the effect to be moved to a PCM output.
2364 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002365 // 3: The primary output
2366 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002367
Eric Laurent3b73df72014-03-11 09:06:29 -07002368 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002369 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002370 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002371
Eric Laurent36829f92017-04-07 19:04:42 -07002372 if (outputs.size() == 0) {
2373 return AUDIO_IO_HANDLE_NONE;
2374 }
Eric Laurente552edb2014-03-10 17:42:56 -07002375
Eric Laurent36829f92017-04-07 19:04:42 -07002376 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2377 bool activeOnly = true;
2378
2379 while (output == AUDIO_IO_HANDLE_NONE) {
2380 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2381 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2382 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2383
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002384 for (audio_io_handle_t output : outputs) {
2385 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002386 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2387 continue;
2388 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002389 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2390 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002391 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002392 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002393 }
2394 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002395 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002396 }
2397 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002398 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002399 }
2400 }
2401 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2402 output = outputOffloaded;
2403 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2404 output = outputDeepBuffer;
2405 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2406 output = outputPrimary;
2407 } else {
2408 output = outputs[0];
2409 }
2410 activeOnly = false;
2411 }
2412
2413 if (output != mMusicEffectOutput) {
2414 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2415 mMusicEffectOutput = output;
2416 }
2417
2418 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002419 return output;
2420}
2421
Eric Laurent36829f92017-04-07 19:04:42 -07002422audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2423{
2424 return selectOutputForMusicEffects();
2425}
2426
Eric Laurente0720872014-03-11 09:30:41 -07002427status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002428 audio_io_handle_t io,
2429 uint32_t strategy,
2430 int session,
2431 int id)
2432{
2433 ssize_t index = mOutputs.indexOfKey(io);
2434 if (index < 0) {
2435 index = mInputs.indexOfKey(io);
2436 if (index < 0) {
2437 ALOGW("registerEffect() unknown io %d", io);
2438 return INVALID_OPERATION;
2439 }
2440 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002441 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002442}
2443
Eric Laurentc75307b2015-03-17 15:29:32 -07002444bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2445{
Eric Laurent28d09f02016-03-08 10:43:05 -08002446 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002447 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2448 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002449 continue;
2450 }
2451 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2452 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002453 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002454}
2455
2456bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2457{
2458 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2459}
2460
Eric Laurente0720872014-03-11 09:30:41 -07002461bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002462{
2463 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002464 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002465 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002466 return true;
2467 }
2468 }
2469 return false;
2470}
2471
Eric Laurent275e8e92014-11-30 15:14:47 -08002472// Register a list of custom mixes with their attributes and format.
2473// When a mix is registered, corresponding input and output profiles are
2474// added to the remote submix hw module. The profile contains only the
2475// parameters (sampling rate, format...) specified by the mix.
2476// The corresponding input remote submix device is also connected.
2477//
2478// When a remote submix device is connected, the address is checked to select the
2479// appropriate profile and the corresponding input or output stream is opened.
2480//
2481// When capture starts, getInputForAttr() will:
2482// - 1 look for a mix matching the address passed in attribtutes tags if any
2483// - 2 if none found, getDeviceForInputSource() will:
2484// - 2.1 look for a mix matching the attributes source
2485// - 2.2 if none found, default to device selection by policy rules
2486// At this time, the corresponding output remote submix device is also connected
2487// and active playback use cases can be transferred to this mix if needed when reconnecting
2488// after AudioTracks are invalidated
2489//
2490// When playback starts, getOutputForAttr() will:
2491// - 1 look for a mix matching the address passed in attribtutes tags if any
2492// - 2 if none found, look for a mix matching the attributes usage
2493// - 3 if none found, default to device and output selection by policy rules.
2494
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002495status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002496{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2498 status_t res = NO_ERROR;
2499
2500 sp<HwModule> rSubmixModule;
2501 // examine each mix's route type
2502 for (size_t i = 0; i < mixes.size(); i++) {
2503 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2504 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2505 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002506 break;
2507 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002509 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002511 rSubmixModule = mHwModules.getModuleFromName(
2512 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2513 if (rSubmixModule == 0) {
2514 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2515 i);
2516 res = INVALID_OPERATION;
2517 break;
2518 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002520
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002522
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002524 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 res = INVALID_OPERATION;
2526 break;
2527 }
2528 audio_config_t outputConfig = mixes[i].mFormat;
2529 audio_config_t inputConfig = mixes[i].mFormat;
2530 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2531 // stereo and let audio flinger do the channel conversion if needed.
2532 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2533 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2534 rSubmixModule->addOutputProfile(address, &outputConfig,
2535 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2536 rSubmixModule->addInputProfile(address, &inputConfig,
2537 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002538
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2540 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2541 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2542 address.string(), "remote-submix");
2543 } else {
2544 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2545 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2546 address.string(), "remote-submix");
2547 }
2548 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002550 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002551 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2552 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002554 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2556 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2557 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2558 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2559 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2560 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002561 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2562 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002563 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2564 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002565 } else {
2566 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002567 }
2568 break;
2569 }
2570 }
2571
2572 if (res != NO_ERROR) {
2573 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002574 i, device, address.string());
2575 res = INVALID_OPERATION;
2576 break;
2577 } else if (!foundOutput) {
2578 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2579 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002580 res = INVALID_OPERATION;
2581 break;
2582 }
Eric Laurentc722f302014-12-10 11:21:49 -08002583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002584 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002585 if (res != NO_ERROR) {
2586 unregisterPolicyMixes(mixes);
2587 }
2588 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002589}
2590
2591status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2592{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002593 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 status_t res = NO_ERROR;
2595 sp<HwModule> rSubmixModule;
2596 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002597 for (const auto& mix : mixes) {
2598 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002599
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002601 rSubmixModule = mHwModules.getModuleFromName(
2602 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2603 if (rSubmixModule == 0) {
2604 res = INVALID_OPERATION;
2605 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002606 }
2607 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002608
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002609 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002610
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002611 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2612 res = INVALID_OPERATION;
2613 continue;
2614 }
2615
2616 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2617 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2618 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2619 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2620 address.string(), "remote-submix");
2621 }
2622 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2623 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2624 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2625 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2626 address.string(), "remote-submix");
2627 }
2628 rSubmixModule->removeOutputProfile(address);
2629 rSubmixModule->removeInputProfile(address);
2630
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002631 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2632 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002633 res = INVALID_OPERATION;
2634 continue;
2635 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002636 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002637 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002638 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002639}
2640
Eric Laurente552edb2014-03-10 17:42:56 -07002641
Eric Laurente0720872014-03-11 09:30:41 -07002642status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002643{
2644 const size_t SIZE = 256;
2645 char buffer[SIZE];
2646 String8 result;
2647
2648 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2649 result.append(buffer);
2650
Eric Laurent87ffa392015-05-22 10:32:38 -07002651 snprintf(buffer, SIZE, " Primary Output: %d\n",
2652 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002653 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002654 std::string stateLiteral;
2655 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2656 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002657 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002658 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002659 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002660 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002661 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002662 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002663 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002664 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002665 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002666 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002667 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002668 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002669 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002670 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002671 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002672 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2673 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2674 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002675 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2676 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002677 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2678 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002679
François Gaffie2110e042015-03-24 08:41:51 +01002680 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002681
François Gaffie112b0af2015-11-19 16:13:25 +01002682 mAvailableOutputDevices.dump(fd, String8("Available output"));
2683 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002684 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002685 mOutputs.dump(fd);
2686 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002687 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002688 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002689 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002690 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002691
2692 return NO_ERROR;
2693}
2694
2695// This function checks for the parameters which can be offloaded.
2696// This can be enhanced depending on the capability of the DSP and policy
2697// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002698bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002699{
2700 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002701 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002702 offloadInfo.sample_rate, offloadInfo.channel_mask,
2703 offloadInfo.format,
2704 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2705 offloadInfo.has_video);
2706
Andy Hung2ddee192015-12-18 17:34:44 -08002707 if (mMasterMono) {
2708 return false; // no offloading if mono is set.
2709 }
2710
Eric Laurente552edb2014-03-10 17:42:56 -07002711 // Check if offload has been disabled
2712 char propValue[PROPERTY_VALUE_MAX];
2713 if (property_get("audio.offload.disable", propValue, "0")) {
2714 if (atoi(propValue) != 0) {
2715 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2716 return false;
2717 }
2718 }
2719
2720 // Check if stream type is music, then only allow offload as of now.
2721 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2722 {
2723 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2724 return false;
2725 }
2726
2727 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002728 const bool allowOffloadWithVideo =
2729 property_get_bool("audio.offload.video", false /* default_value */);
2730 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002731 ALOGV("isOffloadSupported: has_video == true, returning false");
2732 return false;
2733 }
2734
2735 //If duration is less than minimum value defined in property, return false
2736 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2737 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2738 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2739 return false;
2740 }
2741 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2742 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2743 return false;
2744 }
2745
2746 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2747 // creating an offloaded track and tearing it down immediately after start when audioflinger
2748 // detects there is an active non offloadable effect.
2749 // FIXME: We should check the audio session here but we do not have it in this context.
2750 // This may prevent offloading in rare situations where effects are left active by apps
2751 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002752 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002753 return false;
2754 }
2755
2756 // See if there is a profile to support this.
2757 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002758 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002759 offloadInfo.sample_rate,
2760 offloadInfo.format,
2761 offloadInfo.channel_mask,
2762 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002763 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2764 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002765}
2766
Eric Laurent6a94d692014-05-20 11:18:06 -07002767status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2768 audio_port_type_t type,
2769 unsigned int *num_ports,
2770 struct audio_port *ports,
2771 unsigned int *generation)
2772{
2773 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2774 generation == NULL) {
2775 return BAD_VALUE;
2776 }
2777 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2778 if (ports == NULL) {
2779 *num_ports = 0;
2780 }
2781
2782 size_t portsWritten = 0;
2783 size_t portsMax = *num_ports;
2784 *num_ports = 0;
2785 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002786 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2787 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002788 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002789 for (const auto& dev : mAvailableOutputDevices) {
2790 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002791 continue;
2792 }
2793 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002794 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002795 }
2796 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002797 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 }
2799 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002800 for (const auto& dev : mAvailableInputDevices) {
2801 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002802 continue;
2803 }
2804 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002805 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002806 }
2807 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002809 }
2810 }
2811 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2812 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2813 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2814 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2815 }
2816 *num_ports += mInputs.size();
2817 }
2818 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002819 size_t numOutputs = 0;
2820 for (size_t i = 0; i < mOutputs.size(); i++) {
2821 if (!mOutputs[i]->isDuplicated()) {
2822 numOutputs++;
2823 if (portsWritten < portsMax) {
2824 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2825 }
2826 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002827 }
Eric Laurent84c70242014-06-23 08:46:27 -07002828 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 }
2830 }
2831 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002832 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 return NO_ERROR;
2834}
2835
Eric Laurent99fcae42018-05-17 16:59:18 -07002836status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002837{
Eric Laurent99fcae42018-05-17 16:59:18 -07002838 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2839 return BAD_VALUE;
2840 }
2841 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2842 if (dev != 0) {
2843 dev->toAudioPort(port);
2844 return NO_ERROR;
2845 }
2846 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2847 if (dev != 0) {
2848 dev->toAudioPort(port);
2849 return NO_ERROR;
2850 }
2851 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2852 if (out != 0) {
2853 out->toAudioPort(port);
2854 return NO_ERROR;
2855 }
2856 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2857 if (in != 0) {
2858 in->toAudioPort(port);
2859 return NO_ERROR;
2860 }
2861 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002862}
2863
Eric Laurent6a94d692014-05-20 11:18:06 -07002864status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2865 audio_patch_handle_t *handle,
2866 uid_t uid)
2867{
2868 ALOGV("createAudioPatch()");
2869
2870 if (handle == NULL || patch == NULL) {
2871 return BAD_VALUE;
2872 }
2873 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2874
Eric Laurent874c42872014-08-08 15:13:39 -07002875 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2876 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2877 return BAD_VALUE;
2878 }
2879 // only one source per audio patch supported for now
2880 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 return INVALID_OPERATION;
2882 }
Eric Laurent874c42872014-08-08 15:13:39 -07002883
2884 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002885 return INVALID_OPERATION;
2886 }
Eric Laurent874c42872014-08-08 15:13:39 -07002887 for (size_t i = 0; i < patch->num_sinks; i++) {
2888 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2889 return INVALID_OPERATION;
2890 }
2891 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002892
2893 sp<AudioPatch> patchDesc;
2894 ssize_t index = mAudioPatches.indexOfKey(*handle);
2895
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2897 patch->sources[0].role,
2898 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002899#if LOG_NDEBUG == 0
2900 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002901 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002902 patch->sinks[i].role,
2903 patch->sinks[i].type);
2904 }
2905#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002906
2907 if (index >= 0) {
2908 patchDesc = mAudioPatches.valueAt(index);
2909 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2910 mUidCached, patchDesc->mUid, uid);
2911 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2912 return INVALID_OPERATION;
2913 }
2914 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002915 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002916 }
2917
2918 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002919 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002920 if (outputDesc == NULL) {
2921 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2922 return BAD_VALUE;
2923 }
Eric Laurent84c70242014-06-23 08:46:27 -07002924 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2925 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002926 if (patchDesc != 0) {
2927 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2928 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2929 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2930 return BAD_VALUE;
2931 }
2932 }
Eric Laurent874c42872014-08-08 15:13:39 -07002933 DeviceVector devices;
2934 for (size_t i = 0; i < patch->num_sinks; i++) {
2935 // Only support mix to devices connection
2936 // TODO add support for mix to mix connection
2937 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2938 ALOGV("createAudioPatch() source mix but sink is not a device");
2939 return INVALID_OPERATION;
2940 }
2941 sp<DeviceDescriptor> devDesc =
2942 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2943 if (devDesc == 0) {
2944 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2945 return BAD_VALUE;
2946 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002947
François Gaffie53615e22015-03-19 09:24:12 +01002948 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002949 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002950 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002951 NULL, // updatedSamplingRate
2952 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002953 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002954 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002955 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002956 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002957 ALOGV("createAudioPatch() profile not supported for device %08x",
2958 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002959 return INVALID_OPERATION;
2960 }
2961 devices.add(devDesc);
2962 }
2963 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 return INVALID_OPERATION;
2965 }
Eric Laurent874c42872014-08-08 15:13:39 -07002966
Eric Laurent6a94d692014-05-20 11:18:06 -07002967 // TODO: reconfigure output format and channels here
2968 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002969 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002970 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 index = mAudioPatches.indexOfKey(*handle);
2972 if (index >= 0) {
2973 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2974 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2975 }
2976 patchDesc = mAudioPatches.valueAt(index);
2977 patchDesc->mUid = uid;
2978 ALOGV("createAudioPatch() success");
2979 } else {
2980 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2981 return INVALID_OPERATION;
2982 }
2983 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2984 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2985 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002986 // only one sink supported when connecting an input device to a mix
2987 if (patch->num_sinks > 1) {
2988 return INVALID_OPERATION;
2989 }
François Gaffie53615e22015-03-19 09:24:12 +01002990 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002991 if (inputDesc == NULL) {
2992 return BAD_VALUE;
2993 }
2994 if (patchDesc != 0) {
2995 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2996 return BAD_VALUE;
2997 }
2998 }
2999 sp<DeviceDescriptor> devDesc =
3000 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3001 if (devDesc == 0) {
3002 return BAD_VALUE;
3003 }
3004
François Gaffie53615e22015-03-19 09:24:12 +01003005 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003006 devDesc->mAddress,
3007 patch->sinks[0].sample_rate,
3008 NULL, /*updatedSampleRate*/
3009 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003010 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003011 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003012 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003013 // FIXME for the parameter type,
3014 // and the NONE
3015 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003016 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003017 return INVALID_OPERATION;
3018 }
3019 // TODO: reconfigure output format and channels here
3020 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003021 devDesc->type(), inputDesc->mIoHandle);
3022 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003023 index = mAudioPatches.indexOfKey(*handle);
3024 if (index >= 0) {
3025 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3026 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3027 }
3028 patchDesc = mAudioPatches.valueAt(index);
3029 patchDesc->mUid = uid;
3030 ALOGV("createAudioPatch() success");
3031 } else {
3032 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3033 return INVALID_OPERATION;
3034 }
3035 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3036 // device to device connection
3037 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003038 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003039 return BAD_VALUE;
3040 }
3041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003042 sp<DeviceDescriptor> srcDeviceDesc =
3043 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003044 if (srcDeviceDesc == 0) {
3045 return BAD_VALUE;
3046 }
Eric Laurent874c42872014-08-08 15:13:39 -07003047
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 //update source and sink with our own data as the data passed in the patch may
3049 // be incomplete.
3050 struct audio_patch newPatch = *patch;
3051 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003052
Eric Laurent874c42872014-08-08 15:13:39 -07003053 for (size_t i = 0; i < patch->num_sinks; i++) {
3054 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3055 ALOGV("createAudioPatch() source device but one sink is not a device");
3056 return INVALID_OPERATION;
3057 }
3058
3059 sp<DeviceDescriptor> sinkDeviceDesc =
3060 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3061 if (sinkDeviceDesc == 0) {
3062 return BAD_VALUE;
3063 }
3064 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3065
Eric Laurent3bcf8592015-04-03 12:13:24 -07003066 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003067 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003068 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003069 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003070 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003071 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003072 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003073 return INVALID_OPERATION;
3074 }
Eric Laurent874c42872014-08-08 15:13:39 -07003075 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003076 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003077 // if the sink device is reachable via an opened output stream, request to go via
3078 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003079 audio_io_handle_t output = selectOutput(outputs,
3080 AUDIO_OUTPUT_FLAG_NONE,
3081 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003082 if (output != AUDIO_IO_HANDLE_NONE) {
3083 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3084 if (outputDesc->isDuplicated()) {
3085 return INVALID_OPERATION;
3086 }
3087 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003088 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003089 newPatch.num_sources = 2;
3090 }
Eric Laurent83b88082014-06-20 18:31:16 -07003091 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 }
3093 // TODO: check from routing capabilities in config file and other conflicting patches
3094
3095 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3096 if (index >= 0) {
3097 afPatchHandle = patchDesc->mAfPatchHandle;
3098 }
3099
3100 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3101 &afPatchHandle,
3102 0);
3103 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3104 status, afPatchHandle);
3105 if (status == NO_ERROR) {
3106 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003107 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003108 addAudioPatch(patchDesc->mHandle, patchDesc);
3109 } else {
3110 patchDesc->mPatch = newPatch;
3111 }
3112 patchDesc->mAfPatchHandle = afPatchHandle;
3113 *handle = patchDesc->mHandle;
3114 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003115 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003116 } else {
3117 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3118 status);
3119 return INVALID_OPERATION;
3120 }
3121 } else {
3122 return BAD_VALUE;
3123 }
3124 } else {
3125 return BAD_VALUE;
3126 }
3127 return NO_ERROR;
3128}
3129
3130status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3131 uid_t uid)
3132{
3133 ALOGV("releaseAudioPatch() patch %d", handle);
3134
3135 ssize_t index = mAudioPatches.indexOfKey(handle);
3136
3137 if (index < 0) {
3138 return BAD_VALUE;
3139 }
3140 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3141 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3142 mUidCached, patchDesc->mUid, uid);
3143 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3144 return INVALID_OPERATION;
3145 }
3146
3147 struct audio_patch *patch = &patchDesc->mPatch;
3148 patchDesc->mUid = mUidCached;
3149 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003150 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003151 if (outputDesc == NULL) {
3152 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3153 return BAD_VALUE;
3154 }
3155
Eric Laurentc75307b2015-03-17 15:29:32 -07003156 setOutputDevice(outputDesc,
3157 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003158 true,
3159 0,
3160 NULL);
3161 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3162 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003163 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003164 if (inputDesc == NULL) {
3165 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3166 return BAD_VALUE;
3167 }
3168 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003169 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003170 true,
3171 NULL);
3172 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003173 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3174 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3175 status, patchDesc->mAfPatchHandle);
3176 removeAudioPatch(patchDesc->mHandle);
3177 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003178 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003179 } else {
3180 return BAD_VALUE;
3181 }
3182 } else {
3183 return BAD_VALUE;
3184 }
3185 return NO_ERROR;
3186}
3187
3188status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3189 struct audio_patch *patches,
3190 unsigned int *generation)
3191{
François Gaffie53615e22015-03-19 09:24:12 +01003192 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003193 return BAD_VALUE;
3194 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003195 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003196 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003197}
3198
Eric Laurente1715a42014-05-20 11:30:42 -07003199status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003200{
Eric Laurente1715a42014-05-20 11:30:42 -07003201 ALOGV("setAudioPortConfig()");
3202
3203 if (config == NULL) {
3204 return BAD_VALUE;
3205 }
3206 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3207 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003208 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3209 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003210 }
3211
Eric Laurenta121f902014-06-03 13:32:54 -07003212 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003213 if (config->type == AUDIO_PORT_TYPE_MIX) {
3214 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003215 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003216 if (outputDesc == NULL) {
3217 return BAD_VALUE;
3218 }
Eric Laurent84c70242014-06-23 08:46:27 -07003219 ALOG_ASSERT(!outputDesc->isDuplicated(),
3220 "setAudioPortConfig() called on duplicated output %d",
3221 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003222 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003223 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003224 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003225 if (inputDesc == NULL) {
3226 return BAD_VALUE;
3227 }
Eric Laurenta121f902014-06-03 13:32:54 -07003228 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003229 } else {
3230 return BAD_VALUE;
3231 }
3232 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3233 sp<DeviceDescriptor> deviceDesc;
3234 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3235 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3236 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3237 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3238 } else {
3239 return BAD_VALUE;
3240 }
3241 if (deviceDesc == NULL) {
3242 return BAD_VALUE;
3243 }
Eric Laurenta121f902014-06-03 13:32:54 -07003244 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003245 } else {
3246 return BAD_VALUE;
3247 }
3248
Eric Laurenta121f902014-06-03 13:32:54 -07003249 struct audio_port_config backupConfig;
3250 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3251 if (status == NO_ERROR) {
3252 struct audio_port_config newConfig;
3253 audioPortConfig->toAudioPortConfig(&newConfig, config);
3254 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003255 }
Eric Laurenta121f902014-06-03 13:32:54 -07003256 if (status != NO_ERROR) {
3257 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003258 }
Eric Laurente1715a42014-05-20 11:30:42 -07003259
3260 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003261}
3262
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003263void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3264{
Eric Laurentd60560a2015-04-10 11:31:20 -07003265 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003266 clearAudioPatches(uid);
3267 clearSessionRoutes(uid);
3268}
3269
Eric Laurent6a94d692014-05-20 11:18:06 -07003270void AudioPolicyManager::clearAudioPatches(uid_t uid)
3271{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003272 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003273 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3274 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003275 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003276 }
3277 }
3278}
3279
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003280void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3281 audio_io_handle_t ouptutToSkip)
3282{
3283 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3284 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3285 for (size_t j = 0; j < mOutputs.size(); j++) {
3286 if (mOutputs.keyAt(j) == ouptutToSkip) {
3287 continue;
3288 }
3289 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3290 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3291 continue;
3292 }
3293 // If the default device for this strategy is on another output mix,
3294 // invalidate all tracks in this strategy to force re connection.
3295 // Otherwise select new device on the output mix.
3296 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003297 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003298 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3299 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3300 }
3301 }
3302 } else {
3303 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3304 setOutputDevice(outputDesc, newDevice, false);
3305 }
3306 }
3307}
3308
3309void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3310{
3311 // remove output routes associated with this uid
3312 SortedVector<routing_strategy> affectedStrategies;
3313 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3314 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3315 if (route->mUid == uid) {
3316 mOutputRoutes.removeItemsAt(i);
3317 if (route->mDeviceDescriptor != 0) {
3318 affectedStrategies.add(getStrategy(route->mStreamType));
3319 }
3320 }
3321 }
3322 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003323 for (const auto& strategy : affectedStrategies) {
3324 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003325 }
3326
3327 // remove input routes associated with this uid
3328 SortedVector<audio_source_t> affectedSources;
3329 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3330 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3331 if (route->mUid == uid) {
3332 mInputRoutes.removeItemsAt(i);
3333 if (route->mDeviceDescriptor != 0) {
3334 affectedSources.add(route->mSource);
3335 }
3336 }
3337 }
3338 // reroute inputs if necessary
3339 SortedVector<audio_io_handle_t> inputsToClose;
3340 for (size_t i = 0; i < mInputs.size(); i++) {
3341 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003342 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003343 inputsToClose.add(inputDesc->mIoHandle);
3344 }
3345 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003346 for (const auto& input : inputsToClose) {
3347 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003348 }
3349}
3350
Eric Laurentd60560a2015-04-10 11:31:20 -07003351void AudioPolicyManager::clearAudioSources(uid_t uid)
3352{
3353 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3354 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3355 if (sourceDesc->mUid == uid) {
3356 stopAudioSource(mAudioSources.keyAt(i));
3357 }
3358 }
3359}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003360
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003361status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3362 audio_io_handle_t *ioHandle,
3363 audio_devices_t *device)
3364{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003365 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3366 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003367 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003368
François Gaffiedf372692015-03-19 10:43:27 +01003369 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003370}
3371
Eric Laurentd60560a2015-04-10 11:31:20 -07003372status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3373 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003374 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003375 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003376{
Eric Laurentd60560a2015-04-10 11:31:20 -07003377 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3378 if (source == NULL || attributes == NULL || handle == NULL) {
3379 return BAD_VALUE;
3380 }
3381
Glenn Kasten559d4392016-03-29 13:42:57 -07003382 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003383
3384 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3385 source->type != AUDIO_PORT_TYPE_DEVICE) {
3386 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3387 return INVALID_OPERATION;
3388 }
3389
3390 sp<DeviceDescriptor> srcDeviceDesc =
3391 mAvailableInputDevices.getDevice(source->ext.device.type,
3392 String8(source->ext.device.address));
3393 if (srcDeviceDesc == 0) {
3394 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3395 return BAD_VALUE;
3396 }
3397 sp<AudioSourceDescriptor> sourceDesc =
3398 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3399
3400 struct audio_patch dummyPatch;
3401 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3402 sourceDesc->mPatchDesc = patchDesc;
3403
3404 status_t status = connectAudioSource(sourceDesc);
3405 if (status == NO_ERROR) {
3406 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3407 *handle = sourceDesc->getHandle();
3408 }
3409 return status;
3410}
3411
3412status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3413{
3414 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3415
3416 // make sure we only have one patch per source.
3417 disconnectAudioSource(sourceDesc);
3418
3419 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003420 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003421 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3422
3423 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3424 sp<DeviceDescriptor> sinkDeviceDesc =
3425 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3426
3427 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3428 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3429
3430 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3431 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003432 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003433 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3434 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3435 // create patch between src device and output device
3436 // create Hwoutput and add to mHwOutputs
3437 } else {
3438 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3439 audio_io_handle_t output =
3440 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3441 if (output == AUDIO_IO_HANDLE_NONE) {
3442 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3443 return INVALID_OPERATION;
3444 }
3445 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3446 if (outputDesc->isDuplicated()) {
3447 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3448 return INVALID_OPERATION;
3449 }
Eric Laurent733ce942017-12-07 12:18:25 -08003450 status_t status = outputDesc->start();
3451 if (status != NO_ERROR) {
3452 return status;
3453 }
3454
Eric Laurentd60560a2015-04-10 11:31:20 -07003455 // create a special patch with no sink and two sources:
3456 // - the second source indicates to PatchPanel through which output mix this patch should
3457 // be connected as well as the stream type for volume control
3458 // - the sink is defined by whatever output device is currently selected for the output
3459 // though which this patch is routed.
3460 patch->num_sinks = 0;
3461 patch->num_sources = 2;
3462 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3463 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3464 patch->sources[1].ext.mix.usecase.stream = stream;
Eric Laurent733ce942017-12-07 12:18:25 -08003465 status = mpClientInterface->createAudioPatch(patch,
Eric Laurentd60560a2015-04-10 11:31:20 -07003466 &afPatchHandle,
3467 0);
3468 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3469 status, afPatchHandle);
3470 if (status != NO_ERROR) {
3471 ALOGW("%s patch panel could not connect device patch, error %d",
3472 __FUNCTION__, status);
3473 return INVALID_OPERATION;
3474 }
3475 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003476 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003477
3478 if (status != NO_ERROR) {
3479 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3480 return status;
3481 }
3482 sourceDesc->mSwOutput = outputDesc;
3483 if (delayMs != 0) {
3484 usleep(delayMs * 1000);
3485 }
3486 }
3487
3488 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3489 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3490
3491 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003492}
3493
Glenn Kasten559d4392016-03-29 13:42:57 -07003494status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003495{
Eric Laurentd60560a2015-04-10 11:31:20 -07003496 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3497 ALOGV("%s handle %d", __FUNCTION__, handle);
3498 if (sourceDesc == 0) {
3499 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3500 return BAD_VALUE;
3501 }
3502 status_t status = disconnectAudioSource(sourceDesc);
3503
3504 mAudioSources.removeItem(handle);
3505 return status;
3506}
3507
Andy Hung2ddee192015-12-18 17:34:44 -08003508status_t AudioPolicyManager::setMasterMono(bool mono)
3509{
3510 if (mMasterMono == mono) {
3511 return NO_ERROR;
3512 }
3513 mMasterMono = mono;
3514 // if enabling mono we close all offloaded devices, which will invalidate the
3515 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3516 // for recreating the new AudioTrack as non-offloaded PCM.
3517 //
3518 // If disabling mono, we leave all tracks as is: we don't know which clients
3519 // and tracks are able to be recreated as offloaded. The next "song" should
3520 // play back offloaded.
3521 if (mMasterMono) {
3522 Vector<audio_io_handle_t> offloaded;
3523 for (size_t i = 0; i < mOutputs.size(); ++i) {
3524 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3525 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3526 offloaded.push(desc->mIoHandle);
3527 }
3528 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003529 for (const auto& handle : offloaded) {
3530 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003531 }
3532 }
3533 // update master mono for all remaining outputs
3534 for (size_t i = 0; i < mOutputs.size(); ++i) {
3535 updateMono(mOutputs.keyAt(i));
3536 }
3537 return NO_ERROR;
3538}
3539
3540status_t AudioPolicyManager::getMasterMono(bool *mono)
3541{
3542 *mono = mMasterMono;
3543 return NO_ERROR;
3544}
3545
Eric Laurentac9cef52017-06-09 15:46:26 -07003546float AudioPolicyManager::getStreamVolumeDB(
3547 audio_stream_type_t stream, int index, audio_devices_t device)
3548{
3549 return computeVolume(stream, index, device);
3550}
3551
jiabin81772902018-04-02 17:52:27 -07003552status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3553 FormatVector& formats) {
3554 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3555 return BAD_VALUE;
3556 }
3557 String8 reply;
3558 reply = mpClientInterface->getParameters(
3559 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3560 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3561 AudioParameter repliedParameters(reply);
3562 if (repliedParameters.get(
3563 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3564 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3565 return BAD_VALUE;
3566 }
3567 for (auto format : formatsFromString(reply.string())) {
3568 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3569 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3570 if (format == AAC_FORMATS[i]) {
3571 format = AUDIO_FORMAT_AAC_LC;
3572 break;
3573 }
3574 }
3575 bool exist = false;
3576 for (size_t i = 0; i < formats.size(); i++) {
3577 if (format == formats[i]) {
3578 exist = true;
3579 break;
3580 }
3581 }
3582 bool isSurroundFormat = false;
3583 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3584 if (SURROUND_FORMATS[i] == format) {
3585 isSurroundFormat = true;
3586 break;
3587 }
3588 }
3589 if (!exist && isSurroundFormat) {
3590 formats.add(format);
3591 }
3592 }
3593 return NO_ERROR;
3594}
3595
3596status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3597 audio_format_t *surroundFormats,
3598 bool *surroundFormatsEnabled,
3599 bool reported)
3600{
3601 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3602 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3603 return BAD_VALUE;
3604 }
3605 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3606 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3607
3608 // Only return value if there is HDMI output.
3609 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3610 return INVALID_OPERATION;
3611 }
3612
3613 size_t formatsWritten = 0;
3614 size_t formatsMax = *numSurroundFormats;
3615 *numSurroundFormats = 0;
3616 FormatVector formats;
3617 if (reported) {
3618 // Only get surround formats which are reported by device.
3619 // First list already open outputs that can be routed to this device
3620 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3621 SortedVector<audio_io_handle_t> outputs;
3622 bool reportedFormatFound = false;
3623 status_t status;
3624 sp<SwAudioOutputDescriptor> desc;
3625 for (size_t i = 0; i < mOutputs.size(); i++) {
3626 desc = mOutputs.valueAt(i);
3627 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3628 outputs.add(mOutputs.keyAt(i));
3629 }
3630 }
3631 // Open an output to query dynamic parameters.
3632 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3633 AUDIO_DEVICE_OUT_HDMI);
3634 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3635 String8 address = hdmiOutputDevices[i]->mAddress;
3636 for (const auto& hwModule : mHwModules) {
3637 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3638 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3639 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3640 profile->supportDeviceAddress(address)) {
3641 size_t j;
3642 for (j = 0; j < outputs.size(); j++) {
3643 desc = mOutputs.valueFor(outputs.itemAt(j));
3644 if (!desc->isDuplicated() && desc->mProfile == profile) {
3645 break;
3646 }
3647 }
3648 if (j != outputs.size()) {
3649 status = getSupportedFormats(outputs.itemAt(j), formats);
3650 reportedFormatFound |= (status == NO_ERROR);
3651 continue;
3652 }
3653
3654 if (!profile->canOpenNewIo()) {
3655 ALOGW("Max Output number %u already opened for this profile %s",
3656 profile->maxOpenCount, profile->getTagName().c_str());
3657 continue;
3658 }
3659
3660 ALOGV("opening output for device %08x with params %s profile %p name %s",
3661 device, address.string(), profile.get(), profile->getName().string());
3662 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3663 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3664 status_t status = desc->open(nullptr, device, address,
3665 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3666 &output);
3667
3668 if (status == NO_ERROR) {
3669 status = getSupportedFormats(output, formats);
3670 reportedFormatFound |= (status == NO_ERROR);
3671 desc->close();
3672 output = AUDIO_IO_HANDLE_NONE;
3673 }
3674 }
3675 }
3676 }
3677 }
3678
3679 if (!reportedFormatFound) {
3680 return UNKNOWN_ERROR;
3681 }
3682 } else {
3683 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3684 formats.add(SURROUND_FORMATS[i]);
3685 }
3686 }
3687 for (size_t i = 0; i < formats.size(); i++) {
3688 if (formatsWritten < formatsMax) {
3689 surroundFormats[formatsWritten] = formats[i];
3690 bool formatEnabled = false;
3691 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3692 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3693 formatEnabled =
3694 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3695 break;
3696 }
3697 } else {
3698 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3699 }
3700 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3701 }
3702 (*numSurroundFormats)++;
3703 }
3704 return NO_ERROR;
3705}
3706
3707status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3708{
3709 // Check if audio format is a surround formats.
3710 bool isSurroundFormat = false;
3711 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3712 if (audioFormat == SURROUND_FORMATS[i]) {
3713 isSurroundFormat = true;
3714 break;
3715 }
3716 }
3717 if (!isSurroundFormat) {
3718 return BAD_VALUE;
3719 }
3720
3721 // Should only be called when MANUAL.
3722 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3723 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3724 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3725 return INVALID_OPERATION;
3726 }
3727
3728 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3729 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3730 return NO_ERROR;
3731 }
3732
3733 // The operation is valid only when there is HDMI output available.
3734 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3735 return INVALID_OPERATION;
3736 }
3737
3738 if (enabled) {
3739 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3740 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3741 mSurroundFormats.insert(AAC_FORMATS[i]);
3742 }
3743 } else {
3744 mSurroundFormats.insert(audioFormat);
3745 }
3746 } else {
3747 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3748 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3749 mSurroundFormats.erase(AAC_FORMATS[i]);
3750 }
3751 } else {
3752 mSurroundFormats.erase(audioFormat);
3753 }
3754 }
3755
3756 sp<SwAudioOutputDescriptor> outputDesc;
3757 bool profileUpdated = false;
3758 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3759 AUDIO_DEVICE_OUT_HDMI);
3760 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3761 // Simulate reconnection to update enabled surround sound formats.
3762 String8 address = hdmiOutputDevices[i]->mAddress;
3763 String8 name = hdmiOutputDevices[i]->getName();
3764 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3765 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3766 address.c_str(),
3767 name.c_str());
3768 if (status != NO_ERROR) {
3769 continue;
3770 }
3771 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3773 address.c_str(),
3774 name.c_str());
3775 profileUpdated |= (status == NO_ERROR);
3776 }
3777 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3778 AUDIO_DEVICE_IN_HDMI);
3779 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3780 // Simulate reconnection to update enabled surround sound formats.
3781 String8 address = hdmiInputDevices[i]->mAddress;
3782 String8 name = hdmiInputDevices[i]->getName();
3783 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3784 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3785 address.c_str(),
3786 name.c_str());
3787 if (status != NO_ERROR) {
3788 continue;
3789 }
3790 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3791 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3792 address.c_str(),
3793 name.c_str());
3794 profileUpdated |= (status == NO_ERROR);
3795 }
3796
3797 // Undo the surround formats change due to no audio profiles updated.
3798 if (!profileUpdated) {
3799 if (enabled) {
3800 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3801 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3802 mSurroundFormats.erase(AAC_FORMATS[i]);
3803 }
3804 } else {
3805 mSurroundFormats.erase(audioFormat);
3806 }
3807 } else {
3808 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3809 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3810 mSurroundFormats.insert(AAC_FORMATS[i]);
3811 }
3812 } else {
3813 mSurroundFormats.insert(audioFormat);
3814 }
3815 }
3816 }
3817
3818 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3819}
3820
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003821void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3822{
3823 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3824
3825 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3826 for (size_t i = 0; i < activeInputs.size(); i++) {
3827 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3828 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3829 for (size_t j = 0; j < activeSessions.size(); j++) {
3830 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3831 if (activeSession->uid() == uid) {
3832 activeSession->setSilenced(silenced);
3833 }
3834 }
3835 }
3836}
3837
Eric Laurentd60560a2015-04-10 11:31:20 -07003838status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3839{
3840 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3841
3842 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3843 if (patchDesc == 0) {
3844 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3845 sourceDesc->mPatchDesc->mHandle);
3846 return BAD_VALUE;
3847 }
3848 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3849
Eric Laurent28d09f02016-03-08 10:43:05 -08003850 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003851 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3852 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003853 status_t status = stopSource(swOutputDesc, stream, false);
3854 if (status == NO_ERROR) {
3855 swOutputDesc->stop();
3856 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003857 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3858 } else {
3859 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3860 if (hwOutputDesc != 0) {
3861 // release patch between src device and output device
3862 // close Hwoutput and remove from mHwOutputs
3863 } else {
3864 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3865 }
3866 }
3867 return NO_ERROR;
3868}
3869
3870sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3871 audio_io_handle_t output, routing_strategy strategy)
3872{
3873 sp<AudioSourceDescriptor> source;
3874 for (size_t i = 0; i < mAudioSources.size(); i++) {
3875 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3876 routing_strategy sourceStrategy =
3877 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3878 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3879 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3880 source = sourceDesc;
3881 break;
3882 }
3883 }
3884 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003885}
3886
Eric Laurente552edb2014-03-10 17:42:56 -07003887// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003888// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003889// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003890uint32_t AudioPolicyManager::nextAudioPortGeneration()
3891{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003892 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003893}
3894
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003895#ifdef USE_XML_AUDIO_POLICY_CONF
3896// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3897static const char *kConfigLocationList[] =
3898 {"/odm/etc", "/vendor/etc", "/system/etc"};
3899static const int kConfigLocationListSize =
3900 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3901
3902static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3903 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003904 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003905 status_t ret;
3906
Petri Gyntherf497f292018-04-17 18:46:10 -07003907 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3908 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3909 // A2DP offload supported but disabled: try to use special XML file
3910 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3911 }
3912 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3913
3914 for (const char* fileName : fileNames) {
3915 for (int i = 0; i < kConfigLocationListSize; i++) {
3916 PolicySerializer serializer;
3917 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3918 "%s/%s", kConfigLocationList[i], fileName);
3919 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3920 if (ret == NO_ERROR) {
3921 return ret;
3922 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003923 }
3924 }
3925 return ret;
3926}
3927#endif
3928
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003929AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3930 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003931 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003932 mUidCached(getuid()),
3933 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003934 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003936#ifdef USE_XML_AUDIO_POLICY_CONF
3937 mVolumeCurves(new VolumeCurvesCollection()),
3938 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003939 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003940#else
3941 mVolumeCurves(new StreamDescriptorCollection()),
3942 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3943 mDefaultOutputDevice),
3944#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003945 mAudioPortGeneration(1),
3946 mBeaconMuteRefCount(0),
3947 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003948 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003949 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003950 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003951 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3952 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003953{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003954}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003955
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003956AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3957 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3958{
3959 loadConfig();
3960 initialize();
3961}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003962
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003963void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003964#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003965 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003966#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003967 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3968 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003969#endif
3970 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003971 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003972 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003973}
3974
3975status_t AudioPolicyManager::initialize() {
3976 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003977
3978 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003979 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3980 if (!engineInstance) {
3981 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003982 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003983 }
3984 // Retrieve the Policy Manager Interface
3985 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3986 if (mEngine == NULL) {
3987 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003988 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003989 }
3990 mEngine->setObserver(this);
3991 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003992 if (status != NO_ERROR) {
3993 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3994 return status;
3995 }
François Gaffie2110e042015-03-24 08:41:51 +01003996
Eric Laurent3a4311c2014-03-17 12:00:47 -07003997 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003998 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003999 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4000 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004001 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004002 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004003 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4004 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004005 continue;
4006 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004007 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004008 // open all output streams needed to access attached devices
4009 // except for direct output streams that are only opened when they are actually
4010 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004011 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004012 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004013 if (!outProfile->canOpenNewIo()) {
4014 ALOGE("Invalid Output profile max open count %u for profile %s",
4015 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4016 continue;
4017 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004019 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004020 continue;
4021 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004022 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004023 mTtsOutputAvailable = true;
4024 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004025
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004026 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004027 continue;
4028 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004029 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004030 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4031 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004032 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004033 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004034 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004035 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004036 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004037 if ((profileType & outputDeviceTypes) == 0) {
4038 continue;
4039 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004040 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4041 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004042 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4043 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
4044 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4045 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004046 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004047 status_t status = outputDesc->open(nullptr, profileType, address,
4048 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004049
4050 if (status != NO_ERROR) {
4051 ALOGW("Cannot open output stream for device %08x on hw module %s",
4052 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004053 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004054 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004055 for (const auto& dev : supportedDevices) {
4056 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004057 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004058 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004059 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004060 }
4061 }
4062 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004063 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004064 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004065 }
4066 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004067 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004068 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004069 true,
4070 0,
4071 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004072 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004073 }
Eric Laurente552edb2014-03-10 17:42:56 -07004074 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004075 // open input streams needed to access attached devices to validate
4076 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004077 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004078 if (!inProfile->canOpenNewIo()) {
4079 ALOGE("Invalid Input profile max open count %u for profile %s",
4080 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4081 continue;
4082 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004083 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004084 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 continue;
4086 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004087 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004088 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004089 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4090
Eric Laurentd78f1532014-09-16 16:38:20 -07004091 if ((profileType & inputDeviceTypes) == 0) {
4092 continue;
4093 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004094 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004095 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004096
Eric Laurent53b810e2017-12-10 17:25:10 -08004097 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4098 // the inputs vector must be of size >= 1, but we don't want to crash here
4099 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4100 : String8("");
4101 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4102 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4103
Eric Laurentd78f1532014-09-16 16:38:20 -07004104 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004105 status_t status = inputDesc->open(nullptr,
4106 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004107 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004108 AUDIO_SOURCE_MIC,
4109 AUDIO_INPUT_FLAG_NONE,
4110 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004111
4112 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004113 for (const auto& dev : inProfile->getSupportedDevices()) {
4114 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004115 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004116 if (index >= 0) {
4117 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4118 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004119 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004120 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004121 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004122 }
4123 }
Eric Laurentfe231122017-11-17 17:48:06 -08004124 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004125 } else {
4126 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004127 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004128 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004129 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004130 }
4131 }
4132 // make sure all attached devices have been allocated a unique ID
4133 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004134 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004135 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004136 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4137 continue;
4138 }
François Gaffie2110e042015-03-24 08:41:51 +01004139 // The device is now validated and can be appended to the available devices of the engine
4140 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4141 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004142 i++;
4143 }
4144 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004145 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004146 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004147 mAvailableInputDevices.remove(mAvailableInputDevices[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(mAvailableInputDevices[i],
4152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004153 i++;
4154 }
4155 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004156 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004157 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004158 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004159 }
jiabin9ff780e2018-03-19 18:19:52 -07004160 // If microphones address is empty, set it according to device type
4161 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4162 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4163 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4164 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4165 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4166 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4167 }
4168 }
4169 }
Eric Laurente552edb2014-03-10 17:42:56 -07004170
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004171 if (mPrimaryOutput == 0) {
4172 ALOGE("Failed to open primary output");
4173 status = NO_INIT;
4174 }
Eric Laurente552edb2014-03-10 17:42:56 -07004175
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004176 // Silence ALOGV statements
4177 property_set("log.tag." LOG_TAG, "D");
4178
Eric Laurente552edb2014-03-10 17:42:56 -07004179 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004180 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004181}
4182
Eric Laurente0720872014-03-11 09:30:41 -07004183AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004184{
Eric Laurente552edb2014-03-10 17:42:56 -07004185 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004186 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004187 }
4188 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004189 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004190 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004191 mAvailableOutputDevices.clear();
4192 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004193 mOutputs.clear();
4194 mInputs.clear();
4195 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004196 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004197 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004198}
4199
Eric Laurente0720872014-03-11 09:30:41 -07004200status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004201{
Eric Laurent87ffa392015-05-22 10:32:38 -07004202 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004203}
4204
Eric Laurente552edb2014-03-10 17:42:56 -07004205// ---
4206
Eric Laurent98e38192018-02-15 18:31:53 -08004207void AudioPolicyManager::addOutput(audio_io_handle_t output,
4208 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004209{
Eric Laurent1c333e22014-05-20 10:48:17 -07004210 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004211 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004212 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004213 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004215}
4216
François Gaffie53615e22015-03-19 09:24:12 +01004217void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4218{
4219 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004220 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004221}
4222
Eric Laurent98e38192018-02-15 18:31:53 -08004223void AudioPolicyManager::addInput(audio_io_handle_t input,
4224 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004225{
Eric Laurent1c333e22014-05-20 10:48:17 -07004226 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004227 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004228}
Eric Laurente552edb2014-03-10 17:42:56 -07004229
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004230void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004231 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004232 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004233 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004234 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004235 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004236 if (devDesc != 0) {
4237 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4238 desc->mIoHandle, address.string());
4239 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004240 }
4241}
4242
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004243status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004244 audio_policy_dev_state_t state,
4245 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004246 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004247{
François Gaffie53615e22015-03-19 09:24:12 +01004248 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004249 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004250
4251 if (audio_device_is_digital(device)) {
4252 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004253 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004254 }
Eric Laurente552edb2014-03-10 17:42:56 -07004255
Eric Laurent3b73df72014-03-11 09:06:29 -07004256 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004257 // first list already open outputs that can be routed to this device
4258 for (size_t i = 0; i < mOutputs.size(); i++) {
4259 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004260 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004261 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004262 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4263 outputs.add(mOutputs.keyAt(i));
4264 } else {
4265 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004266 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004267 }
Eric Laurente552edb2014-03-10 17:42:56 -07004268 }
4269 }
4270 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004271 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004272 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004273 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4274 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004275 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004276 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004277 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004278 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004279 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4280 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004281 }
Eric Laurente552edb2014-03-10 17:42:56 -07004282 }
4283 }
4284 }
4285
Eric Laurent7b279bb2015-12-14 10:18:23 -08004286 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004287
Eric Laurente552edb2014-03-10 17:42:56 -07004288 if (profiles.isEmpty() && outputs.isEmpty()) {
4289 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4290 return BAD_VALUE;
4291 }
4292
4293 // open outputs for matching profiles if needed. Direct outputs are also opened to
4294 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4295 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004296 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004297
4298 // nothing to do if one output is already opened for this profile
4299 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004300 for (j = 0; j < outputs.size(); j++) {
4301 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004302 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004303 // matching profile: save the sample rates, format and channel masks supported
4304 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004305 if (audio_device_is_digital(device)) {
4306 devDesc->importAudioPort(profile);
4307 }
Eric Laurente552edb2014-03-10 17:42:56 -07004308 break;
4309 }
4310 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004311 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004312 continue;
4313 }
4314
Eric Laurent3974e3b2017-12-07 17:58:43 -08004315 if (!profile->canOpenNewIo()) {
4316 ALOGW("Max Output number %u already opened for this profile %s",
4317 profile->maxOpenCount, profile->getTagName().c_str());
4318 continue;
4319 }
4320
Eric Laurent83efe1c2017-07-09 16:51:08 -07004321 ALOGV("opening output for device %08x with params %s profile %p name %s",
4322 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004323 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004324 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004325 status_t status = desc->open(nullptr, device, address,
4326 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004327
Eric Laurentfe231122017-11-17 17:48:06 -08004328 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004329 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004330 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004331 char *param = audio_device_address_to_parameter(device, address);
4332 mpClientInterface->setParameters(output, String8(param));
4333 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004334 }
Phil Burk00eeb322016-03-31 12:41:00 -07004335 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004336 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004337 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004338 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004339 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004340 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004341 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004342 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004343 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4344 profile->pickAudioProfile(
4345 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004346 config.offload_info.sample_rate = config.sample_rate;
4347 config.offload_info.channel_mask = config.channel_mask;
4348 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004349
4350 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4351 AUDIO_OUTPUT_FLAG_NONE, &output);
4352 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004353 output = AUDIO_IO_HANDLE_NONE;
4354 }
Eric Laurentd4692962014-05-05 18:13:44 -07004355 }
4356
Eric Laurentcf2c0212014-07-25 16:20:43 -07004357 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004359 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004360 sp<AudioPolicyMix> policyMix;
4361 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004362 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4363 address.string());
4364 }
François Gaffie036e1e92015-03-19 10:16:24 +01004365 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004366 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004367
Eric Laurent87ffa392015-05-22 10:32:38 -07004368 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4369 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004370 // no duplicated output for direct outputs and
4371 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004372 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004373
Eric Laurentd4692962014-05-05 18:13:44 -07004374 //TODO: configure audio effect output stage here
4375
4376 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004377 sp<SwAudioOutputDescriptor> dupOutputDesc =
4378 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4379 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4380 &duplicatedOutput);
4381 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004382 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004383 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004384 } else {
4385 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004386 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004387 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004388 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004389 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004390 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004391 }
Eric Laurente552edb2014-03-10 17:42:56 -07004392 }
4393 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004394 } else {
4395 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004396 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004397 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004398 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004399 profiles.removeAt(profile_index);
4400 profile_index--;
4401 } else {
4402 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004403 // Load digital format info only for digital devices
4404 if (audio_device_is_digital(device)) {
4405 devDesc->importAudioPort(profile);
4406 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004407
François Gaffie53615e22015-03-19 09:24:12 +01004408 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004409 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4410 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004411 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004412 NULL/*patch handle*/, address.string());
4413 }
Eric Laurente552edb2014-03-10 17:42:56 -07004414 ALOGV("checkOutputsForDevice(): adding output %d", output);
4415 }
4416 }
4417
4418 if (profiles.isEmpty()) {
4419 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4420 return BAD_VALUE;
4421 }
Eric Laurentd4692962014-05-05 18:13:44 -07004422 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004423 // check if one opened output is not needed any more after disconnecting one device
4424 for (size_t i = 0; i < mOutputs.size(); i++) {
4425 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004426 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004427 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004428 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004429 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004430 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004431 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004432 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4433 mOutputs.keyAt(i));
4434 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004435 }
Eric Laurente552edb2014-03-10 17:42:56 -07004436 }
4437 }
Eric Laurentd4692962014-05-05 18:13:44 -07004438 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004439 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004440 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4441 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004442 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004443 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004444 "clearing direct output profile %zu on module %s",
4445 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004446 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004447 }
4448 }
4449 }
4450 }
4451 return NO_ERROR;
4452}
4453
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004454status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004455 audio_policy_dev_state_t state,
4456 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004457 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004458{
Paul McLean9080a4c2015-06-18 08:24:02 -07004459 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004460 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004461
4462 if (audio_device_is_digital(device)) {
4463 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004464 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004465 }
4466
Eric Laurentd4692962014-05-05 18:13:44 -07004467 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4468 // first list already open inputs that can be routed to this device
4469 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4470 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004471 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004472 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4473 inputs.add(mInputs.keyAt(input_index));
4474 }
4475 }
4476
4477 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004478 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004479 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004480 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004481 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004482 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004483 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004484
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004485 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004486 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004487 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004488 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004489 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4490 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004491 }
Eric Laurentd4692962014-05-05 18:13:44 -07004492 }
4493 }
4494 }
4495
4496 if (profiles.isEmpty() && inputs.isEmpty()) {
4497 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4498 return BAD_VALUE;
4499 }
4500
4501 // open inputs for matching profiles if needed. Direct inputs are also opened to
4502 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4503 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4504
Eric Laurent1c333e22014-05-20 10:48:17 -07004505 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004506
Eric Laurentd4692962014-05-05 18:13:44 -07004507 // nothing to do if one input is already opened for this profile
4508 size_t input_index;
4509 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4510 desc = mInputs.valueAt(input_index);
4511 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004512 if (audio_device_is_digital(device)) {
4513 devDesc->importAudioPort(profile);
4514 }
Eric Laurentd4692962014-05-05 18:13:44 -07004515 break;
4516 }
4517 }
4518 if (input_index != mInputs.size()) {
4519 continue;
4520 }
4521
Eric Laurent3974e3b2017-12-07 17:58:43 -08004522 if (!profile->canOpenNewIo()) {
4523 ALOGW("Max Input number %u already opened for this profile %s",
4524 profile->maxOpenCount, profile->getTagName().c_str());
4525 continue;
4526 }
4527
Eric Laurentfe231122017-11-17 17:48:06 -08004528 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004529 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004530 status_t status = desc->open(nullptr,
4531 device,
4532 address,
4533 AUDIO_SOURCE_MIC,
4534 AUDIO_INPUT_FLAG_NONE,
4535 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004536
Eric Laurentcf2c0212014-07-25 16:20:43 -07004537 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004538 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004539 char *param = audio_device_address_to_parameter(device, address);
4540 mpClientInterface->setParameters(input, String8(param));
4541 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004542 }
Phil Burk00eeb322016-03-31 12:41:00 -07004543 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004544 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004545 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004546 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004547 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004548 }
4549
4550 if (input != 0) {
4551 addInput(input, desc);
4552 }
4553 } // endif input != 0
4554
Eric Laurentcf2c0212014-07-25 16:20:43 -07004555 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004556 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004557 profiles.removeAt(profile_index);
4558 profile_index--;
4559 } else {
4560 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004561 if (audio_device_is_digital(device)) {
4562 devDesc->importAudioPort(profile);
4563 }
Eric Laurentd4692962014-05-05 18:13:44 -07004564 ALOGV("checkInputsForDevice(): adding input %d", input);
4565 }
4566 } // end scan profiles
4567
4568 if (profiles.isEmpty()) {
4569 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4570 return BAD_VALUE;
4571 }
4572 } else {
4573 // Disconnect
4574 // check if one opened input is not needed any more after disconnecting one device
4575 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4576 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004577 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004578 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4579 mInputs.keyAt(input_index));
4580 inputs.add(mInputs.keyAt(input_index));
4581 }
4582 }
4583 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004584 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004585 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004586 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004587 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004588 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004589 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004590 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4591 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004592 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004593 }
4594 }
4595 }
4596 } // end disconnect
4597
4598 return NO_ERROR;
4599}
4600
4601
Eric Laurente0720872014-03-11 09:30:41 -07004602void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004603{
4604 ALOGV("closeOutput(%d)", output);
4605
Eric Laurentc75307b2015-03-17 15:29:32 -07004606 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004607 if (outputDesc == NULL) {
4608 ALOGW("closeOutput() unknown output %d", output);
4609 return;
4610 }
François Gaffie036e1e92015-03-19 10:16:24 +01004611 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004612
Eric Laurente552edb2014-03-10 17:42:56 -07004613 // look for duplicated outputs connected to the output being removed.
4614 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004615 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004616 if (dupOutputDesc->isDuplicated() &&
4617 (dupOutputDesc->mOutput1 == outputDesc ||
4618 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004619 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004620 if (dupOutputDesc->mOutput1 == outputDesc) {
4621 outputDesc2 = dupOutputDesc->mOutput2;
4622 } else {
4623 outputDesc2 = dupOutputDesc->mOutput1;
4624 }
4625 // As all active tracks on duplicated output will be deleted,
4626 // and as they were also referenced on the other output, the reference
4627 // count for their stream type must be adjusted accordingly on
4628 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004629 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004630 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004631 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004632 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004633 }
Eric Laurent733ce942017-12-07 12:18:25 -08004634 // stop() will be a no op if the output is still active but is needed in case all
4635 // active streams refcounts where cleared above
4636 if (wasActive) {
4637 outputDesc2->stop();
4638 }
Eric Laurente552edb2014-03-10 17:42:56 -07004639 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4640 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4641
4642 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004643 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004644 }
4645 }
4646
Eric Laurent05b90f82014-08-27 15:32:29 -07004647 nextAudioPortGeneration();
4648
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004649 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004650 if (index >= 0) {
4651 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004652 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004653 mAudioPatches.removeItemsAt(index);
4654 mpClientInterface->onAudioPatchListUpdate();
4655 }
4656
Eric Laurentfe231122017-11-17 17:48:06 -08004657 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004658
François Gaffie53615e22015-03-19 09:24:12 +01004659 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004660 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004661}
4662
4663void AudioPolicyManager::closeInput(audio_io_handle_t input)
4664{
4665 ALOGV("closeInput(%d)", input);
4666
4667 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4668 if (inputDesc == NULL) {
4669 ALOGW("closeInput() unknown input %d", input);
4670 return;
4671 }
4672
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004674
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004675 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004676 if (index >= 0) {
4677 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004678 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004679 mAudioPatches.removeItemsAt(index);
4680 mpClientInterface->onAudioPatchListUpdate();
4681 }
4682
Eric Laurentfe231122017-11-17 17:48:06 -08004683 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004684 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004685}
4686
Eric Laurentc75307b2015-03-17 15:29:32 -07004687SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4688 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004689 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004690{
4691 SortedVector<audio_io_handle_t> outputs;
4692
4693 ALOGVV("getOutputsForDevice() device %04x", device);
4694 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004695 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004696 i, openOutputs.valueAt(i)->isDuplicated(),
4697 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004698 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4699 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4700 outputs.add(openOutputs.keyAt(i));
4701 }
4702 }
4703 return outputs;
4704}
4705
Eric Laurente0720872014-03-11 09:30:41 -07004706bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004707 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004708{
4709 if (outputs1.size() != outputs2.size()) {
4710 return false;
4711 }
4712 for (size_t i = 0; i < outputs1.size(); i++) {
4713 if (outputs1[i] != outputs2[i]) {
4714 return false;
4715 }
4716 }
4717 return true;
4718}
4719
Eric Laurente0720872014-03-11 09:30:41 -07004720void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004721{
4722 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4723 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4724 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4725 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4726
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004727 // also take into account external policy-related changes: add all outputs which are
4728 // associated with policies in the "before" and "after" output vectors
4729 ALOGVV("checkOutputForStrategy(): policy related outputs");
4730 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004731 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004732 if (desc != 0 && desc->mPolicyMix != NULL) {
4733 srcOutputs.add(desc->mIoHandle);
4734 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4735 }
4736 }
4737 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004738 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004739 if (desc != 0 && desc->mPolicyMix != NULL) {
4740 dstOutputs.add(desc->mIoHandle);
4741 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4742 }
4743 }
4744
Eric Laurente552edb2014-03-10 17:42:56 -07004745 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004746 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4747 // audio from invalidated tracks will be rendered when unmuting
4748 uint32_t maxLatency = 0;
4749 for (audio_io_handle_t srcOut : srcOutputs) {
4750 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4751 if (desc != 0 && maxLatency < desc->latency()) {
4752 maxLatency = desc->latency();
4753 }
4754 }
Eric Laurente552edb2014-03-10 17:42:56 -07004755 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4756 strategy, srcOutputs[0], dstOutputs[0]);
4757 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004758 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004759 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4760 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004761 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004762 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004763 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004764 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004765 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004766 if (source != 0){
4767 connectAudioSource(source);
4768 }
Eric Laurente552edb2014-03-10 17:42:56 -07004769 }
4770
4771 // Move effects associated to this strategy from previous output to new output
4772 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004773 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004774 }
4775 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004776 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004777 if (getStrategy((audio_stream_type_t)i) == strategy) {
4778 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004779 }
4780 }
4781 }
4782}
4783
Eric Laurente0720872014-03-11 09:30:41 -07004784void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004785{
François Gaffie2110e042015-03-24 08:41:51 +01004786 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004787 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004788 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004789 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004790 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004791 checkOutputForStrategy(STRATEGY_SONIFICATION);
4792 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004793 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004794 checkOutputForStrategy(STRATEGY_MEDIA);
4795 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004796 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004797}
4798
Eric Laurente0720872014-03-11 09:30:41 -07004799void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004800{
François Gaffie53615e22015-03-19 09:24:12 +01004801 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004802 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004803 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004804 return;
4805 }
4806
Eric Laurent3a4311c2014-03-17 12:00:47 -07004807 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004808 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4809 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4810 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004811
4812 // if suspended, restore A2DP output if:
4813 // ((SCO device is NOT connected) ||
4814 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4815 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004816 //
Eric Laurentf732e072016-08-03 19:30:28 -07004817 // if not suspended, suspend A2DP output if:
4818 // (SCO device is connected) &&
4819 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4820 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004821 //
4822 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004823 if (!isScoConnected ||
4824 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4825 AUDIO_POLICY_FORCE_BT_SCO) &&
4826 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4827 AUDIO_POLICY_FORCE_BT_SCO) &&
4828 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004829 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004830
4831 mpClientInterface->restoreOutput(a2dpOutput);
4832 mA2dpSuspended = false;
4833 }
4834 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004835 if (isScoConnected &&
4836 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4837 AUDIO_POLICY_FORCE_BT_SCO) ||
4838 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4839 AUDIO_POLICY_FORCE_BT_SCO) ||
4840 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004841 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004842
4843 mpClientInterface->suspendOutput(a2dpOutput);
4844 mA2dpSuspended = true;
4845 }
4846 }
4847}
4848
Eric Laurentc75307b2015-03-17 15:29:32 -07004849audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4850 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004851{
4852 audio_devices_t device = AUDIO_DEVICE_NONE;
4853
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004854 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004855 if (index >= 0) {
4856 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4857 if (patchDesc->mUid != mUidCached) {
4858 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004859 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 return outputDesc->device();
4861 }
4862 }
4863
Eric Laurentf3a5a602018-05-22 18:42:55 -07004864 // Check if an explicit routing request exists for an active stream on this output and
4865 // use it in priority before any other rule
4866 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4867 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4868 audio_devices_t forcedDevice =
4869 mOutputRoutes.getActiveDeviceForStream(
4870 (audio_stream_type_t)stream, mAvailableOutputDevices);
4871
4872 if (forcedDevice != AUDIO_DEVICE_NONE) {
4873 return forcedDevice;
4874 }
4875 }
4876 }
4877
Eric Laurente552edb2014-03-10 17:42:56 -07004878 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004879 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004880 // use device for strategy enforced audible
4881 // 2: we are in call or the strategy phone is active on the output:
4882 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004883 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004884 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004885 // 4: the strategy for enforced audible is active but not enforced on the output:
4886 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004887 // 5: the strategy accessibility is active on the output:
4888 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004889 // 6: the strategy "respectful" sonification is active on the output:
4890 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004891 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004892 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004893 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004894 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004895 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004896 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004897
4898 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4899 // with a refined rule considering mutually exclusive devices (using same backend)
4900 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004901 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004902 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004903 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4904 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004905 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004906 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004907 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004908 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004909 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4910 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004911 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4912 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004913 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004914 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004915 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004916 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004917 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004918 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004919 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004920 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004921 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004922 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004923 }
4924
Eric Laurent1c333e22014-05-20 10:48:17 -07004925 ALOGV("getNewOutputDevice() selected device %x", device);
4926 return device;
4927}
4928
Eric Laurentfb66dd92016-01-28 18:32:03 -08004929audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004930{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004931 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004932
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004933 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004934 if (index >= 0) {
4935 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4936 if (patchDesc->mUid != mUidCached) {
4937 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004938 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 return inputDesc->mDevice;
4940 }
4941 }
4942
Eric Laurentdc95a252018-04-12 12:46:56 -07004943 // If we are not in call and no client is active on this input, this methods returns
4944 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004945 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004946 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4947 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4948 }
4949 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004950 device = getDeviceAndMixForInputSource(source);
4951 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004952
Eric Laurente552edb2014-03-10 17:42:56 -07004953 return device;
4954}
4955
Eric Laurent794fde22016-03-11 09:50:45 -08004956bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4957 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004958 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004959}
4960
Eric Laurente0720872014-03-11 09:30:41 -07004961uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004962 return (uint32_t)getStrategy(stream);
4963}
4964
Eric Laurente0720872014-03-11 09:30:41 -07004965audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004966 // By checking the range of stream before calling getStrategy, we avoid
4967 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4968 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004969 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 return AUDIO_DEVICE_NONE;
4971 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004972 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004973 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4974 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004975 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 }
Eric Laurent794fde22016-03-11 09:50:45 -08004977 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004978 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004979 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004980 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4981 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004982 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004983 curDevices |= outputDesc->device();
4984 }
4985 }
4986 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004987 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004988
4989 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4990 and doesn't really need to.*/
4991 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4992 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4993 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4994 }
Eric Laurente552edb2014-03-10 17:42:56 -07004995 return devices;
4996}
4997
François Gaffie2110e042015-03-24 08:41:51 +01004998routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4999{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005000 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005001 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005002}
5003
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005004uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5005 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005006 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5007 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5008 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005009 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5010 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5011 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005012 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005013 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005014}
5015
Eric Laurente0720872014-03-11 09:30:41 -07005016void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005017 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005018 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005019 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5020 updateDevicesAndOutputs();
5021 break;
5022 default:
5023 break;
5024 }
5025}
5026
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005027uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005028
5029 // skip beacon mute management if a dedicated TTS output is available
5030 if (mTtsOutputAvailable) {
5031 return 0;
5032 }
5033
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005034 switch(event) {
5035 case STARTING_OUTPUT:
5036 mBeaconMuteRefCount++;
5037 break;
5038 case STOPPING_OUTPUT:
5039 if (mBeaconMuteRefCount > 0) {
5040 mBeaconMuteRefCount--;
5041 }
5042 break;
5043 case STARTING_BEACON:
5044 mBeaconPlayingRefCount++;
5045 break;
5046 case STOPPING_BEACON:
5047 if (mBeaconPlayingRefCount > 0) {
5048 mBeaconPlayingRefCount--;
5049 }
5050 break;
5051 }
5052
5053 if (mBeaconMuteRefCount > 0) {
5054 // any playback causes beacon to be muted
5055 return setBeaconMute(true);
5056 } else {
5057 // no other playback: unmute when beacon starts playing, mute when it stops
5058 return setBeaconMute(mBeaconPlayingRefCount == 0);
5059 }
5060}
5061
5062uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5063 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5064 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5065 // keep track of muted state to avoid repeating mute/unmute operations
5066 if (mBeaconMuted != mute) {
5067 // mute/unmute AUDIO_STREAM_TTS on all outputs
5068 ALOGV("\t muting %d", mute);
5069 uint32_t maxLatency = 0;
5070 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005071 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005072 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005073 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005074 0 /*delay*/, AUDIO_DEVICE_NONE);
5075 const uint32_t latency = desc->latency() * 2;
5076 if (latency > maxLatency) {
5077 maxLatency = latency;
5078 }
5079 }
5080 mBeaconMuted = mute;
5081 return maxLatency;
5082 }
5083 return 0;
5084}
5085
Eric Laurente0720872014-03-11 09:30:41 -07005086audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005087 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005088{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005089 // Check if an explicit routing request exists for a stream type corresponding to the
5090 // specified strategy and use it in priority over default routing rules.
5091 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5092 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5093 audio_devices_t forcedDevice =
5094 mOutputRoutes.getActiveDeviceForStream(
5095 (audio_stream_type_t)stream, mAvailableOutputDevices);
5096 if (forcedDevice != AUDIO_DEVICE_NONE) {
5097 return forcedDevice;
5098 }
Paul McLeanaa981192015-03-21 09:55:15 -07005099 }
5100 }
5101
Eric Laurente552edb2014-03-10 17:42:56 -07005102 if (fromCache) {
5103 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5104 strategy, mDeviceForStrategy[strategy]);
5105 return mDeviceForStrategy[strategy];
5106 }
François Gaffie2110e042015-03-24 08:41:51 +01005107 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005108}
5109
Eric Laurente0720872014-03-11 09:30:41 -07005110void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005111{
5112 for (int i = 0; i < NUM_STRATEGIES; i++) {
5113 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5114 }
5115 mPreviousOutputs = mOutputs;
5116}
5117
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005118uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005119 audio_devices_t prevDevice,
5120 uint32_t delayMs)
5121{
5122 // mute/unmute strategies using an incompatible device combination
5123 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5124 // if unmuting, unmute only after the specified delay
5125 if (outputDesc->isDuplicated()) {
5126 return 0;
5127 }
5128
5129 uint32_t muteWaitMs = 0;
5130 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005131 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005132
5133 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5134 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005135 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005136 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5137 bool doMute = false;
5138
5139 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5140 doMute = true;
5141 outputDesc->mStrategyMutedByDevice[i] = true;
5142 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5143 doMute = true;
5144 outputDesc->mStrategyMutedByDevice[i] = false;
5145 }
Eric Laurent99401132014-05-07 19:48:15 -07005146 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005147 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005148 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005149 // skip output if it does not share any device with current output
5150 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5151 == AUDIO_DEVICE_NONE) {
5152 continue;
5153 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005154 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005155 mute ? "muting" : "unmuting", i, curDevice);
5156 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005157 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005158 if (mute) {
5159 // FIXME: should not need to double latency if volume could be applied
5160 // immediately by the audioflinger mixer. We must account for the delay
5161 // between now and the next time the audioflinger thread for this output
5162 // will process a buffer (which corresponds to one buffer size,
5163 // usually 1/2 or 1/4 of the latency).
5164 if (muteWaitMs < desc->latency() * 2) {
5165 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005166 }
5167 }
5168 }
5169 }
5170 }
5171 }
5172
Eric Laurent99401132014-05-07 19:48:15 -07005173 // temporary mute output if device selection changes to avoid volume bursts due to
5174 // different per device volumes
5175 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005176 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5177 // temporary mute duration is conservatively set to 4 times the reported latency
5178 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5179 if (muteWaitMs < tempMuteWaitMs) {
5180 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005181 }
Eric Laurentdc462862016-07-19 12:29:53 -07005182
Eric Laurent99401132014-05-07 19:48:15 -07005183 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005184 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005185 // make sure that we do not start the temporary mute period too early in case of
5186 // delayed device change
5187 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005189 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005190 }
5191 }
5192 }
5193
Eric Laurente552edb2014-03-10 17:42:56 -07005194 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5195 if (muteWaitMs > delayMs) {
5196 muteWaitMs -= delayMs;
5197 usleep(muteWaitMs * 1000);
5198 return muteWaitMs;
5199 }
5200 return 0;
5201}
5202
Eric Laurentc75307b2015-03-17 15:29:32 -07005203uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005204 audio_devices_t device,
5205 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005207 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005208 const char *address,
5209 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005210{
Eric Laurentc75307b2015-03-17 15:29:32 -07005211 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005212 AudioParameter param;
5213 uint32_t muteWaitMs;
5214
5215 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005216 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5217 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5218 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5219 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005220 return muteWaitMs;
5221 }
5222 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5223 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005224 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005225 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005226 return 0;
5227 }
5228
5229 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005231
5232 audio_devices_t prevDevice = outputDesc->mDevice;
5233
Paul McLeanaa981192015-03-21 09:55:15 -07005234 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005235
5236 if (device != AUDIO_DEVICE_NONE) {
5237 outputDesc->mDevice = device;
5238 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005239
5240 // if the outputs are not materially active, there is no need to mute.
5241 if (requiresMuteCheck) {
5242 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5243 } else {
5244 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5245 muteWaitMs = 0;
5246 }
Eric Laurente552edb2014-03-10 17:42:56 -07005247
5248 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005249 // the requested device is AUDIO_DEVICE_NONE
5250 // OR the requested device is the same as current device
5251 // AND force is not specified
5252 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005253 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005254 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5255 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005256 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005257 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005258 return muteWaitMs;
5259 }
5260
5261 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005262
Eric Laurente552edb2014-03-10 17:42:56 -07005263 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005265 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005266 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005267 DeviceVector deviceList;
5268 if ((address == NULL) || (strlen(address) == 0)) {
5269 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5270 } else {
5271 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5272 }
5273
Eric Laurent1c333e22014-05-20 10:48:17 -07005274 if (!deviceList.isEmpty()) {
5275 struct audio_patch patch;
5276 outputDesc->toAudioPortConfig(&patch.sources[0]);
5277 patch.num_sources = 1;
5278 patch.num_sinks = 0;
5279 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5280 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005281 patch.num_sinks++;
5282 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 ssize_t index;
5284 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5285 index = mAudioPatches.indexOfKey(*patchHandle);
5286 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005287 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 }
5289 sp< AudioPatch> patchDesc;
5290 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5291 if (index >= 0) {
5292 patchDesc = mAudioPatches.valueAt(index);
5293 afPatchHandle = patchDesc->mAfPatchHandle;
5294 }
5295
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 &afPatchHandle,
5298 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005299 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5300 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005302 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005304 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 addAudioPatch(patchDesc->mHandle, patchDesc);
5306 } else {
5307 patchDesc->mPatch = patch;
5308 }
5309 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 if (patchHandle) {
5311 *patchHandle = patchDesc->mHandle;
5312 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005313 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005315 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005316 }
5317 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005318
5319 // inform all input as well
5320 for (size_t i = 0; i < mInputs.size(); i++) {
5321 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005322 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005323 AudioParameter inputCmd = AudioParameter();
5324 ALOGV("%s: inform input %d of device:%d", __func__,
5325 inputDescriptor->mIoHandle, device);
5326 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5327 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5328 inputCmd.toString(),
5329 delayMs);
5330 }
5331 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 }
Eric Laurente552edb2014-03-10 17:42:56 -07005333
5334 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005335 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005336
5337 return muteWaitMs;
5338}
5339
Eric Laurentc75307b2015-03-17 15:29:32 -07005340status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 int delayMs,
5342 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005343{
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 ssize_t index;
5345 if (patchHandle) {
5346 index = mAudioPatches.indexOfKey(*patchHandle);
5347 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005348 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 }
5350 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005351 return INVALID_OPERATION;
5352 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005353 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5354 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005355 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005356 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005357 removeAudioPatch(patchDesc->mHandle);
5358 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005359 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005360 return status;
5361}
5362
5363status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5364 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005365 bool force,
5366 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005367{
5368 status_t status = NO_ERROR;
5369
Eric Laurent1f2f2232014-06-02 12:01:23 -07005370 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5372 inputDesc->mDevice = device;
5373
5374 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5375 if (!deviceList.isEmpty()) {
5376 struct audio_patch patch;
5377 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005378 // AUDIO_SOURCE_HOTWORD is for internal use only:
5379 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005380 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005381 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005382 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5383 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005384 patch.num_sinks = 1;
5385 //only one input device for now
5386 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005387 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 ssize_t index;
5389 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5390 index = mAudioPatches.indexOfKey(*patchHandle);
5391 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005392 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005393 }
5394 sp< AudioPatch> patchDesc;
5395 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5396 if (index >= 0) {
5397 patchDesc = mAudioPatches.valueAt(index);
5398 afPatchHandle = patchDesc->mAfPatchHandle;
5399 }
5400
Eric Laurent1c333e22014-05-20 10:48:17 -07005401 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005402 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005403 0);
5404 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005406 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005407 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005408 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 addAudioPatch(patchDesc->mHandle, patchDesc);
5410 } else {
5411 patchDesc->mPatch = patch;
5412 }
5413 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 if (patchHandle) {
5415 *patchHandle = patchDesc->mHandle;
5416 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005417 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005419 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005420 }
5421 }
5422 }
5423 return status;
5424}
5425
Eric Laurent6a94d692014-05-20 11:18:06 -07005426status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5427 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005428{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005429 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 ssize_t index;
5431 if (patchHandle) {
5432 index = mAudioPatches.indexOfKey(*patchHandle);
5433 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005434 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005435 }
5436 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005437 return INVALID_OPERATION;
5438 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5440 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005441 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005442 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005443 removeAudioPatch(patchDesc->mHandle);
5444 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005445 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005446 return status;
5447}
5448
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005449sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005450 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005451 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005452 audio_format_t& format,
5453 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005454 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005455{
5456 // Choose an input profile based on the requested capture parameters: select the first available
5457 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005458 //
5459 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5460 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005461
Glenn Kasten730b9262018-03-29 15:01:26 -07005462 sp<IOProfile> firstInexact;
5463 uint32_t updatedSamplingRate = 0;
5464 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5465 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005466 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005467 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005468 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005469 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005470 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005471 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005472 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005473 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005474 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005475 &channelMask /*updatedChannelMask*/,
5476 // FIXME ugly cast
5477 (audio_output_flags_t) flags,
5478 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005479 return profile;
5480 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005481 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5482 samplingRate,
5483 &updatedSamplingRate,
5484 format,
5485 &updatedFormat,
5486 channelMask,
5487 &updatedChannelMask,
5488 // FIXME ugly cast
5489 (audio_output_flags_t) flags,
5490 false /*exactMatchRequiredForInputFlags*/)) {
5491 firstInexact = profile;
5492 }
5493
Eric Laurente552edb2014-03-10 17:42:56 -07005494 }
5495 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005496 if (firstInexact != nullptr) {
5497 samplingRate = updatedSamplingRate;
5498 format = updatedFormat;
5499 channelMask = updatedChannelMask;
5500 return firstInexact;
5501 }
Eric Laurente552edb2014-03-10 17:42:56 -07005502 return NULL;
5503}
5504
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005505
5506audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005507 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005508{
François Gaffie036e1e92015-03-19 10:16:24 +01005509 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5510 audio_devices_t selectedDeviceFromMix =
5511 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005512
François Gaffie036e1e92015-03-19 10:16:24 +01005513 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5514 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005515 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005516 return getDeviceForInputSource(inputSource);
5517}
5518
5519audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5520{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005521 // Routing
5522 // Scan the whole RouteMap to see if we have an explicit route:
5523 // if the input source in the RouteMap is the same as the argument above,
5524 // and activity count is non-zero and the device in the route descriptor is available
5525 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005526 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5527 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005528 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005529 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005530 return route->mDeviceDescriptor->type();
5531 }
5532 }
5533
5534 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005535}
5536
Eric Laurente0720872014-03-11 09:30:41 -07005537float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005538 int index,
5539 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005540{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005541 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005542
5543 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5544 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5545 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5546 // the ringtone volume
5547 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5548 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5549 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5550 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5551 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5552 }
5553
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005554 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005555 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5556 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005557 switch (stream) {
5558 case AUDIO_STREAM_SYSTEM:
5559 case AUDIO_STREAM_RING:
5560 case AUDIO_STREAM_MUSIC:
5561 case AUDIO_STREAM_ALARM:
5562 case AUDIO_STREAM_NOTIFICATION:
5563 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5564 case AUDIO_STREAM_DTMF:
5565 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005566 int voiceVolumeIndex =
5567 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5568 const float maxVoiceVolDb =
5569 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5570 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005571 if (volumeDB > maxVoiceVolDb) {
5572 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5573 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5574 volumeDB = maxVoiceVolDb;
5575 }
5576 } break;
5577 default:
5578 break;
5579 }
5580 }
5581
Eric Laurente552edb2014-03-10 17:42:56 -07005582 // if a headset is connected, apply the following rules to ring tones and notifications
5583 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005584 // - always attenuate notifications volume by 6dB
5585 // - attenuate ring tones volume by 6dB unless music is not playing and
5586 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005587 // - if music is playing, always limit the volume to current music volume,
5588 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005589 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005590 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5591 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5592 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005593 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005594 AUDIO_DEVICE_OUT_USB_HEADSET |
5595 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005596 ((stream_strategy == STRATEGY_SONIFICATION)
5597 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005598 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005599 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005600 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005601 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005602 // when the phone is ringing we must consider that music could have been paused just before
5603 // by the music application and behave as if music was active if the last music track was
5604 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005605 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005606 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005607 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005608 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005609 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005610 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5611 musicDevice),
5612 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005613 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5614 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005615 if (volumeDB > minVolDB) {
5616 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005617 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005618 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005619 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5620 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5621 // on A2DP, also ensure notification volume is not too low compared to media when
5622 // intended to be played
5623 if ((volumeDB > -96.0f) &&
5624 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5625 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5626 stream, device,
5627 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5628 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5629 }
5630 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005631 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5632 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005633 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005634 }
5635 }
5636
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005637 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005638}
5639
Eric Laurente0720872014-03-11 09:30:41 -07005640status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005641 int index,
5642 const sp<AudioOutputDescriptor>& outputDesc,
5643 audio_devices_t device,
5644 int delayMs,
5645 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005646{
Eric Laurente552edb2014-03-10 17:42:56 -07005647 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005648 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005649 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005650 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005651 return NO_ERROR;
5652 }
François Gaffie2110e042015-03-24 08:41:51 +01005653 audio_policy_forced_cfg_t forceUseForComm =
5654 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005655 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005656 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5657 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005658 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005659 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005660 return INVALID_OPERATION;
5661 }
5662
Eric Laurentc75307b2015-03-17 15:29:32 -07005663 if (device == AUDIO_DEVICE_NONE) {
5664 device = outputDesc->device();
5665 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005666
Eric Laurentffbc80f2015-03-18 18:30:19 -07005667 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005668 if (outputDesc->isFixedVolume(device) ||
5669 // Force VoIP volume to max for bluetooth SCO
5670 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5671 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005672 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005673 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005674
Eric Laurentffbc80f2015-03-18 18:30:19 -07005675 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005676
Eric Laurent3b73df72014-03-11 09:06:29 -07005677 if (stream == AUDIO_STREAM_VOICE_CALL ||
5678 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005679 float voiceVolume;
5680 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005681 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005682 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005683 } else {
5684 voiceVolume = 1.0;
5685 }
5686
Eric Laurent18fba842016-03-31 14:41:26 -07005687 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005688 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5689 mLastVoiceVolume = voiceVolume;
5690 }
5691 }
5692
5693 return NO_ERROR;
5694}
5695
Eric Laurentc75307b2015-03-17 15:29:32 -07005696void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5697 audio_devices_t device,
5698 int delayMs,
5699 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005700{
Eric Laurentc75307b2015-03-17 15:29:32 -07005701 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005702
Eric Laurent794fde22016-03-11 09:50:45 -08005703 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005704 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005705 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005706 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005707 device,
5708 delayMs,
5709 force);
5710 }
5711}
5712
Eric Laurente0720872014-03-11 09:30:41 -07005713void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005714 bool on,
5715 const sp<AudioOutputDescriptor>& outputDesc,
5716 int delayMs,
5717 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005718{
Eric Laurent72249d52015-06-08 11:12:15 -07005719 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5720 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005721 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005722 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005723 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005724 }
5725 }
5726}
5727
Eric Laurente0720872014-03-11 09:30:41 -07005728void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005729 bool on,
5730 const sp<AudioOutputDescriptor>& outputDesc,
5731 int delayMs,
5732 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005733{
Eric Laurente552edb2014-03-10 17:42:56 -07005734 if (device == AUDIO_DEVICE_NONE) {
5735 device = outputDesc->device();
5736 }
5737
Eric Laurentc75307b2015-03-17 15:29:32 -07005738 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5739 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005740
5741 if (on) {
5742 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005743 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005744 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005745 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005746 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005747 }
5748 }
5749 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5750 outputDesc->mMuteCount[stream]++;
5751 } else {
5752 if (outputDesc->mMuteCount[stream] == 0) {
5753 ALOGV("setStreamMute() unmuting non muted stream!");
5754 return;
5755 }
5756 if (--outputDesc->mMuteCount[stream] == 0) {
5757 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005758 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005759 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005760 device,
5761 delayMs);
5762 }
5763 }
5764}
5765
Eric Laurente0720872014-03-11 09:30:41 -07005766void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005767 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005768{
Eric Laurent87ffa392015-05-22 10:32:38 -07005769 if(!hasPrimaryOutput()) {
5770 return;
5771 }
5772
Eric Laurente552edb2014-03-10 17:42:56 -07005773 // if the stream pertains to sonification strategy and we are in call we must
5774 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5775 // in the device used for phone strategy and play the tone if the selected device does not
5776 // interfere with the device used for phone strategy
5777 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5778 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005779 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005780 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5781 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005782 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005783 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5784 stream, starting, outputDesc->mDevice, stateChange);
5785 if (outputDesc->mRefCount[stream]) {
5786 int muteCount = 1;
5787 if (stateChange) {
5788 muteCount = outputDesc->mRefCount[stream];
5789 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005790 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005791 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5792 for (int i = 0; i < muteCount; i++) {
5793 setStreamMute(stream, starting, mPrimaryOutput);
5794 }
5795 } else {
5796 ALOGV("handleIncallSonification() high visibility");
5797 if (outputDesc->device() &
5798 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5799 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5800 for (int i = 0; i < muteCount; i++) {
5801 setStreamMute(stream, starting, mPrimaryOutput);
5802 }
5803 }
5804 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005805 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5806 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005807 } else {
5808 mpClientInterface->stopTone();
5809 }
5810 }
5811 }
5812 }
5813}
5814
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005815audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5816{
5817 // flags to stream type mapping
5818 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5819 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5820 }
5821 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5822 return AUDIO_STREAM_BLUETOOTH_SCO;
5823 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005824 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5825 return AUDIO_STREAM_TTS;
5826 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005827
5828 // usage to stream type mapping
5829 switch (attr->usage) {
5830 case AUDIO_USAGE_MEDIA:
5831 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005832 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005833 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5834 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005835 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5836 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005837 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5838 return AUDIO_STREAM_SYSTEM;
5839 case AUDIO_USAGE_VOICE_COMMUNICATION:
5840 return AUDIO_STREAM_VOICE_CALL;
5841
5842 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5843 return AUDIO_STREAM_DTMF;
5844
5845 case AUDIO_USAGE_ALARM:
5846 return AUDIO_STREAM_ALARM;
5847 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5848 return AUDIO_STREAM_RING;
5849
5850 case AUDIO_USAGE_NOTIFICATION:
5851 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5852 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5853 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5854 case AUDIO_USAGE_NOTIFICATION_EVENT:
5855 return AUDIO_STREAM_NOTIFICATION;
5856
5857 case AUDIO_USAGE_UNKNOWN:
5858 default:
5859 return AUDIO_STREAM_MUSIC;
5860 }
5861}
Eric Laurente83b55d2014-11-14 10:06:21 -08005862
François Gaffie53615e22015-03-19 09:24:12 +01005863bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5864{
Eric Laurente83b55d2014-11-14 10:06:21 -08005865 // has flags that map to a strategy?
5866 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5867 return true;
5868 }
5869
5870 // has known usage?
5871 switch (paa->usage) {
5872 case AUDIO_USAGE_UNKNOWN:
5873 case AUDIO_USAGE_MEDIA:
5874 case AUDIO_USAGE_VOICE_COMMUNICATION:
5875 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5876 case AUDIO_USAGE_ALARM:
5877 case AUDIO_USAGE_NOTIFICATION:
5878 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5879 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5880 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5881 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5882 case AUDIO_USAGE_NOTIFICATION_EVENT:
5883 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5884 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5885 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5886 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005887 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005888 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005889 break;
5890 default:
5891 return false;
5892 }
5893 return true;
5894}
5895
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005896bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005897 routing_strategy strategy, uint32_t inPastMs,
5898 nsecs_t sysTime) const
5899{
5900 if ((sysTime == 0) && (inPastMs != 0)) {
5901 sysTime = systemTime();
5902 }
Eric Laurent794fde22016-03-11 09:50:45 -08005903 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005904 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5905 (NUM_STRATEGIES == strategy)) &&
5906 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5907 return true;
5908 }
5909 }
5910 return false;
5911}
5912
Eric Laurent484e9272018-06-07 17:29:23 -07005913bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5914 routing_strategy strategy, uint32_t inPastMs,
5915 nsecs_t sysTime) const
5916{
5917 for (size_t i = 0; i < mOutputs.size(); i++) {
5918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5919 if (outputDesc->sharesHwModuleWith(desc)
5920 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5921 return true;
5922 }
5923 }
5924 return false;
5925}
5926
François Gaffie2110e042015-03-24 08:41:51 +01005927audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5928{
5929 return mEngine->getForceUse(usage);
5930}
5931
5932bool AudioPolicyManager::isInCall()
5933{
5934 return isStateInCall(mEngine->getPhoneState());
5935}
5936
5937bool AudioPolicyManager::isStateInCall(int state)
5938{
5939 return is_state_in_call(state);
5940}
5941
Eric Laurentd60560a2015-04-10 11:31:20 -07005942void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5943{
5944 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5945 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5946 if (sourceDesc->mDevice->equals(deviceDesc)) {
5947 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5948 stopAudioSource(sourceDesc->getHandle());
5949 }
5950 }
5951
5952 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5953 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5954 bool release = false;
5955 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5956 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5957 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5958 source->ext.device.type == deviceDesc->type()) {
5959 release = true;
5960 }
5961 }
5962 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5963 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5964 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5965 sink->ext.device.type == deviceDesc->type()) {
5966 release = true;
5967 }
5968 }
5969 if (release) {
5970 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5971 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5972 }
5973 }
5974}
5975
Phil Burk09bc4612016-02-24 15:58:15 -08005976// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005977void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5978 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005979 // TODO Set this based on Config properties.
5980 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005981
5982 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5983 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005984 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005985
jiabin81772902018-04-02 17:52:27 -07005986 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5987 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5988 formats.clear();
5989 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5990 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005991 }
jiabin81772902018-04-02 17:52:27 -07005992 // Always enable IEC61937 when in MANUAL mode.
5993 formats.add(AUDIO_FORMAT_IEC61937);
5994 } else { // NEVER, AUTO or ALWAYS
5995 // Analyze original support for various formats.
5996 bool supportsAC3 = false;
5997 bool supportsOtherSurround = false;
5998 bool supportsIEC61937 = false;
5999 mSurroundFormats.clear();
6000 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
6001 audio_format_t format = formats[formatIndex];
6002 switch (format) {
6003 case AUDIO_FORMAT_AC3:
6004 supportsAC3 = true;
6005 break;
6006 case AUDIO_FORMAT_E_AC3:
6007 case AUDIO_FORMAT_DTS:
6008 case AUDIO_FORMAT_DTS_HD:
6009 // If ALWAYS, remove all other surround formats here
6010 // since we will add them later.
6011 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6012 formats.removeAt(formatIndex);
6013 formatIndex--;
6014 }
6015 supportsOtherSurround = true;
6016 break;
6017 case AUDIO_FORMAT_IEC61937:
6018 supportsIEC61937 = true;
6019 break;
6020 default:
6021 break;
6022 }
6023 }
Phil Burk09bc4612016-02-24 15:58:15 -08006024
jiabin81772902018-04-02 17:52:27 -07006025 // Modify formats based on surround preferences.
6026 // If NEVER, remove support for surround formats.
6027 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6028 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
6029 // Remove surround sound related formats.
6030 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
6031 audio_format_t format = formats[formatIndex];
6032 switch(format) {
6033 case AUDIO_FORMAT_AC3:
6034 case AUDIO_FORMAT_E_AC3:
6035 case AUDIO_FORMAT_DTS:
6036 case AUDIO_FORMAT_DTS_HD:
6037 case AUDIO_FORMAT_IEC61937:
6038 formats.removeAt(formatIndex);
6039 break;
6040 default:
6041 formatIndex++; // keep it
6042 break;
6043 }
6044 }
6045 supportsAC3 = false;
6046 supportsOtherSurround = false;
6047 supportsIEC61937 = false;
6048 }
6049 } else { // AUTO or ALWAYS
6050 // Most TVs support AC3 even if they do not report it in the EDID.
6051 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6052 && !supportsAC3) {
6053 formats.add(AUDIO_FORMAT_AC3);
6054 supportsAC3 = true;
6055 }
6056
6057 // If ALWAYS, add support for raw surround formats if all are missing.
6058 // This assumes that if any of these formats are reported by the HAL
6059 // then the report is valid and should not be modified.
6060 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6061 formats.add(AUDIO_FORMAT_E_AC3);
6062 formats.add(AUDIO_FORMAT_DTS);
6063 formats.add(AUDIO_FORMAT_DTS_HD);
6064 supportsOtherSurround = true;
6065 }
6066
6067 // Add support for IEC61937 if any raw surround supported.
6068 // The HAL could do this but add it here, just in case.
6069 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6070 formats.add(AUDIO_FORMAT_IEC61937);
6071 supportsIEC61937 = true;
6072 }
6073
6074 // Add reported surround sound formats to enabled surround formats.
6075 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006076 audio_format_t format = formats[formatIndex];
6077 switch(format) {
6078 case AUDIO_FORMAT_AC3:
6079 case AUDIO_FORMAT_E_AC3:
6080 case AUDIO_FORMAT_DTS:
6081 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006082 case AUDIO_FORMAT_AAC_LC:
6083 case AUDIO_FORMAT_DOLBY_TRUEHD:
6084 case AUDIO_FORMAT_E_AC3_JOC:
6085 mSurroundFormats.insert(format);
Chih-Hung Hsieh39399602018-10-16 14:42:13 -07006086 break;
Phil Burk07ac1142016-03-25 13:39:29 -07006087 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006088 break;
6089 }
Phil Burk09bc4612016-02-24 15:58:15 -08006090 }
Phil Burk07ac1142016-03-25 13:39:29 -07006091 }
Phil Burk09bc4612016-02-24 15:58:15 -08006092 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006093}
6094
6095// Modify the list of channel masks supported.
6096void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6097 ChannelsVector &channelMasks = *channelMasksPtr;
6098 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6099 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6100
6101 // If NEVER, then remove support for channelMasks > stereo.
6102 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6103 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6104 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6105 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6106 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6107 channelMasks.removeAt(maskIndex);
6108 } else {
6109 maskIndex++;
6110 }
6111 }
jiabin81772902018-04-02 17:52:27 -07006112 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6113 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6114 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006115 bool supports5dot1 = false;
6116 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006117 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006118 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6119 supports5dot1 = true;
6120 break;
6121 }
6122 }
6123 // If not then add 5.1 support.
6124 if (!supports5dot1) {
6125 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6126 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6127 }
Phil Burk09bc4612016-02-24 15:58:15 -08006128 }
6129}
6130
Phil Burk00eeb322016-03-31 12:41:00 -07006131void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6132 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006133 AudioProfileVector &profiles)
6134{
6135 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006136
François Gaffie112b0af2015-11-19 16:13:25 +01006137 // Format MUST be checked first to update the list of AudioProfile
6138 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006139 reply = mpClientInterface->getParameters(
6140 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006141 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006142 AudioParameter repliedParameters(reply);
6143 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006144 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006145 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6146 return;
6147 }
Phil Burk09bc4612016-02-24 15:58:15 -08006148 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006149 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006150 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006151 }
Phil Burk09bc4612016-02-24 15:58:15 -08006152 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006153 }
François Gaffie112b0af2015-11-19 16:13:25 +01006154
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006155 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006156 ChannelsVector channelMasks;
6157 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006158 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006159 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006160
6161 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006162 reply = mpClientInterface->getParameters(
6163 ioHandle,
6164 requestedParameters.toString() + ";" +
6165 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006166 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006167 AudioParameter repliedParameters(reply);
6168 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006169 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006170 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006171 }
6172 }
6173 if (profiles.hasDynamicChannelsFor(format)) {
6174 reply = mpClientInterface->getParameters(ioHandle,
6175 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006176 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006177 ALOGV("%s: supported channel masks %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::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006181 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006182 if (device == AUDIO_DEVICE_OUT_HDMI) {
6183 filterSurroundChannelMasks(&channelMasks);
6184 }
François Gaffie112b0af2015-11-19 16:13:25 +01006185 }
6186 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006187 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006188 }
6189}
Eric Laurentd60560a2015-04-10 11:31:20 -07006190
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006191} // namespace android