blob: b740e65afe5b959c7a15f877e9c7875ef4637362 [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()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001089 // if a valid format is specified, skip output if not compatible
1090 if (format != AUDIO_FORMAT_INVALID) {
1091 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001092 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001093 continue;
1094 }
1095 } else if (!audio_is_linear_pcm(format)) {
1096 continue;
1097 }
Eric Laurente6930022016-02-11 10:20:40 -08001098 if (AudioPort::isBetterFormatMatch(
1099 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001100 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001101 bestFormat = outputDesc->mFormat;
1102 }
Eric Laurent8838a382014-09-08 16:44:28 -07001103 }
1104
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001105 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001106 if (commonFlags >= maxCommonFlags) {
1107 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001108 if (format != AUDIO_FORMAT_INVALID
1109 && AudioPort::isBetterFormatMatch(
1110 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001111 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001112 bestFormatForFlags = outputDesc->mFormat;
1113 }
1114 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001115 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001116 maxCommonFlags = commonFlags;
1117 bestFormatForFlags = outputDesc->mFormat;
1118 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001119 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001120 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001121 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001122 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001123 }
1124 }
1125 }
1126
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001127 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001128 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001130 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001131 return outputForFormat;
1132 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001133 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001134 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001135 }
1136
1137 return outputs[0];
1138}
1139
Eric Laurente0720872014-03-11 09:30:41 -07001140status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001141 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001142 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001143{
Paul McLeanaa981192015-03-21 09:55:15 -07001144 ALOGV("startOutput() output %d, stream %d, session %d",
1145 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001146 ssize_t index = mOutputs.indexOfKey(output);
1147 if (index < 0) {
1148 ALOGW("startOutput() unknown output %d", output);
1149 return BAD_VALUE;
1150 }
1151
Eric Laurentc75307b2015-03-17 15:29:32 -07001152 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1153
Eric Laurent733ce942017-12-07 12:18:25 -08001154 status_t status = outputDesc->start();
1155 if (status != NO_ERROR) {
1156 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001157 }
1158
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001159 // Routing?
1160 mOutputRoutes.incRouteActivity(session);
1161
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001163 AudioMix *policyMix = NULL;
1164 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001166 policyMix = outputDesc->mPolicyMix;
1167 address = policyMix->mDeviceAddress.string();
1168 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1169 newDevice = policyMix->mDeviceType;
1170 } else {
1171 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1172 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001173 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001174 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001175 if (newDevice != outputDesc->device()) {
1176 checkStrategyRoute(getStrategy(stream), output);
1177 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001178 } else {
1179 newDevice = AUDIO_DEVICE_NONE;
1180 }
1181
1182 uint32_t delayMs = 0;
1183
Eric Laurent733ce942017-12-07 12:18:25 -08001184 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001185
1186 if (status != NO_ERROR) {
1187 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001188 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001189 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001190 }
1191 // Automatically enable the remote submix input when output is started on a re routing mix
1192 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001193 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1194 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1196 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001197 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001198 "remote-submix");
1199 }
1200
1201 if (delayMs != 0) {
1202 usleep(delayMs * 1000);
1203 }
1204
1205 return status;
1206}
1207
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001208status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001209 audio_stream_type_t stream,
1210 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001211 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001212 uint32_t *delayMs)
1213{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001214 // cannot start playback of STREAM_TTS if any other output is being used
1215 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001216
1217 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001218 if (stream == AUDIO_STREAM_TTS) {
1219 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001220 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001221 return INVALID_OPERATION;
1222 } else {
1223 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1224 }
1225 } else {
1226 // some playback other than beacon starts
1227 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1228 }
1229
Eric Laurent77305a62016-07-25 16:39:22 -07001230 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001231 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001232 bool force = !outputDesc->isActive() &&
1233 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001234
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001235 // requiresMuteCheck is false when we can bypass mute strategy.
1236 // It covers a common case when there is no materially active audio
1237 // and muting would result in unnecessary delay and dropped audio.
1238 const uint32_t outputLatencyMs = outputDesc->latency();
1239 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1240
Eric Laurente552edb2014-03-10 17:42:56 -07001241 // increment usage count for this stream on the requested output:
1242 // NOTE that the usage count is the same for duplicated output and hardware output which is
1243 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1244 outputDesc->changeRefCount(stream, 1);
1245
Eric Laurent36829f92017-04-07 19:04:42 -07001246 if (stream == AUDIO_STREAM_MUSIC) {
1247 selectOutputForMusicEffects();
1248 }
1249
Eric Laurent493404d2015-04-21 15:07:36 -07001250 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001251 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001252 if (device == AUDIO_DEVICE_NONE) {
1253 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001254 }
Eric Laurent36829f92017-04-07 19:04:42 -07001255
Eric Laurente552edb2014-03-10 17:42:56 -07001256 routing_strategy strategy = getStrategy(stream);
1257 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001258 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1259 (beaconMuteLatency > 0);
1260 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001261 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001262 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001263 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001264 // An output has a shared device if
1265 // - managed by the same hw module
1266 // - supports the currently selected device
1267 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1268 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1269
Eric Laurent77305a62016-07-25 16:39:22 -07001270 // force a device change if any other output is:
1271 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001272 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001273 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001274 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001275 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001276 // change the device currently selected by the other output.
1277 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001278 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001279 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001280 force = true;
1281 }
1282 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001283 // a notification so that audio focus effect can propagate, or that a mute/unmute
1284 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001285 const uint32_t latencyMs = desc->latency();
1286 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1287
1288 if (shouldWait && isActive && (waitMs < latencyMs)) {
1289 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001290 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001291
1292 // Require mute check if another output is on a shared device
1293 // and currently active to have proper drain and avoid pops.
1294 // Note restoring AudioTracks onto this output needs to invoke
1295 // a volume ramp if there is no mute.
1296 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001297 }
1298 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001299
1300 const uint32_t muteWaitMs =
1301 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001302
1303 // handle special case for sonification while in call
1304 if (isInCall()) {
1305 handleIncallSonification(stream, true, false);
1306 }
1307
1308 // apply volume rules for current stream and device if necessary
1309 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001310 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001311 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001312 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001313
1314 // update the outputs if starting an output with a stream that can affect notification
1315 // routing
1316 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001317
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001318 // force reevaluating accessibility routing when ringtone or alarm starts
1319 if (strategy == STRATEGY_SONIFICATION) {
1320 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1321 }
Eric Laurentdc462862016-07-19 12:29:53 -07001322
1323 if (waitMs > muteWaitMs) {
1324 *delayMs = waitMs - muteWaitMs;
1325 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001326
1327 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1328 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1329 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1330 // change occurs after the MixerThread starts and causes a stream volume
1331 // glitch.
1332 //
1333 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001334 }
Eric Laurentdc462862016-07-19 12:29:53 -07001335
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001336 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1337 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1338 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1339 }
1340
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001341 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1342 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1343 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1344 }
1345
Eric Laurente552edb2014-03-10 17:42:56 -07001346 return NO_ERROR;
1347}
1348
1349
Eric Laurente0720872014-03-11 09:30:41 -07001350status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001351 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001352 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001353{
1354 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1355 ssize_t index = mOutputs.indexOfKey(output);
1356 if (index < 0) {
1357 ALOGW("stopOutput() unknown output %d", output);
1358 return BAD_VALUE;
1359 }
1360
Eric Laurentc75307b2015-03-17 15:29:32 -07001361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001362
Eric Laurentc75307b2015-03-17 15:29:32 -07001363 if (outputDesc->mRefCount[stream] == 1) {
1364 // Automatically disable the remote submix input when output is stopped on a
1365 // re routing mix of type MIX_TYPE_RECORDERS
1366 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1367 outputDesc->mPolicyMix != NULL &&
1368 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1369 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1370 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001371 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001372 "remote-submix");
1373 }
1374 }
1375
1376 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001377 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001378 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001379 int activityCount = mOutputRoutes.decRouteActivity(session);
1380 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1381
1382 if (forceDeviceUpdate) {
1383 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1384 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 }
1386
Eric Laurent3974e3b2017-12-07 17:58:43 -08001387 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1388
Eric Laurent733ce942017-12-07 12:18:25 -08001389 if (status == NO_ERROR ) {
1390 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001391 }
1392 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001393}
1394
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001395status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001396 audio_stream_type_t stream,
1397 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001398{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001399 // always handle stream stop, check which stream type is stopping
1400 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1401
Eric Laurente552edb2014-03-10 17:42:56 -07001402 // handle special case for sonification while in call
1403 if (isInCall()) {
1404 handleIncallSonification(stream, false, false);
1405 }
1406
1407 if (outputDesc->mRefCount[stream] > 0) {
1408 // decrement usage count of this stream on the output
1409 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001410
Eric Laurente552edb2014-03-10 17:42:56 -07001411 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001412 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001413 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001414 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001415 // delay the device switch by twice the latency because stopOutput() is executed when
1416 // the track stop() command is received and at that time the audio track buffer can
1417 // still contain data that needs to be drained. The latency only covers the audio HAL
1418 // and kernel buffers. Also the latency does not always include additional delay in the
1419 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001420 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001421
1422 // force restoring the device selection on other active outputs if it differs from the
1423 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001424 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001425 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001426 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001427 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001428 desc->isActive() &&
1429 outputDesc->sharesHwModuleWith(desc) &&
1430 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001431 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1432 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001433
Eric Laurentc75307b2015-03-17 15:29:32 -07001434 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001435 newDevice2,
1436 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001437 delayMs);
1438 // re-apply device specific volume if not done by setOutputDevice()
1439 if (!force) {
1440 applyStreamVolumes(desc, newDevice2, delayMs);
1441 }
Eric Laurente552edb2014-03-10 17:42:56 -07001442 }
1443 }
1444 // update the outputs if stopping one with a stream that can affect notification routing
1445 handleNotificationRoutingForStream(stream);
1446 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001447
1448 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1449 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1450 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1451 }
1452
Eric Laurent36829f92017-04-07 19:04:42 -07001453 if (stream == AUDIO_STREAM_MUSIC) {
1454 selectOutputForMusicEffects();
1455 }
Eric Laurente552edb2014-03-10 17:42:56 -07001456 return NO_ERROR;
1457 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001458 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001459 return INVALID_OPERATION;
1460 }
1461}
1462
Eric Laurente83b55d2014-11-14 10:06:21 -08001463void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001464 audio_stream_type_t stream __unused,
1465 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001466{
1467 ALOGV("releaseOutput() %d", output);
1468 ssize_t index = mOutputs.indexOfKey(output);
1469 if (index < 0) {
1470 ALOGW("releaseOutput() releasing unknown output %d", output);
1471 return;
1472 }
1473
Paul McLeanaa981192015-03-21 09:55:15 -07001474 // Routing
1475 mOutputRoutes.removeRoute(session);
1476
Eric Laurentc75307b2015-03-17 15:29:32 -07001477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001478 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001479 if (desc->mDirectOpenCount <= 0) {
1480 ALOGW("releaseOutput() invalid open count %d for output %d",
1481 desc->mDirectOpenCount, output);
1482 return;
1483 }
1484 if (--desc->mDirectOpenCount == 0) {
1485 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001486 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
1488 }
1489}
1490
1491
Eric Laurentcaf7f482014-11-25 17:50:47 -08001492status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1493 audio_io_handle_t *input,
1494 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001495 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001496 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001497 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001498 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001499 input_type_t *inputType,
1500 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001501{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001502 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001503 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001504 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001505
Eric Laurentad2e7b92017-09-14 20:06:42 -07001506 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001507 // handle legacy remote submix case where the address was not always specified
1508 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001509 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001510 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001511 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001512 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001513
Eric Laurentfe231122017-11-17 17:48:06 -08001514 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1515 inputSource = AUDIO_SOURCE_MIC;
1516 }
1517
Paul McLean466dc8e2015-04-17 13:15:36 -06001518 // Explicit routing?
1519 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001520 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001521 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001522 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001523 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001524
Eric Laurentad2e7b92017-09-14 20:06:42 -07001525 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1526 // possible
1527 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1528 *input != AUDIO_IO_HANDLE_NONE) {
1529 ssize_t index = mInputs.indexOfKey(*input);
1530 if (index < 0) {
1531 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1532 status = BAD_VALUE;
1533 goto error;
1534 }
1535 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1536 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1537 if (audioSession == 0) {
1538 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1539 status = BAD_VALUE;
1540 goto error;
1541 }
1542 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1543 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001544 // corresponds to a new client and is only permitted from the same UID.
1545 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001546 if (audioSession->openCount() == 1) {
1547 audioSession->setUid(uid);
1548 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001549 if (!audioSession->isSilenced()) {
1550 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1551 uid, session, audioSession->uid());
1552 status = INVALID_OPERATION;
1553 goto error;
1554 }
1555 audioSession->setUid(uid);
1556 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001557 }
1558 audioSession->changeOpenCount(1);
1559 *inputType = API_INPUT_LEGACY;
1560 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1561 *portId = AudioPort::getNextUniqueId();
1562 }
1563 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1564 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1565 : AUDIO_PORT_HANDLE_NONE;
1566 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1567
1568 return NO_ERROR;
1569 }
1570
1571 *input = AUDIO_IO_HANDLE_NONE;
1572 *inputType = API_INPUT_INVALID;
1573
Eric Laurentad2e7b92017-09-14 20:06:42 -07001574 halInputSource = inputSource;
1575
1576 // TODO: check for existing client for this port ID
1577 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1578 *portId = AudioPort::getNextUniqueId();
1579 }
1580
1581 audio_devices_t device;
1582
Eric Laurentc447ded2015-01-06 08:47:05 -08001583 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001584 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001585 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1586 if (status != NO_ERROR) {
1587 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001588 }
1589 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001590 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1591 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001592 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001593 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001594 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001595 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001596 status = BAD_VALUE;
1597 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001598 }
Eric Laurentc722f302014-12-10 11:21:49 -08001599 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001600 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001601 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1602 // there is an external policy, but this input is attached to a mix of recorders,
1603 // meaning it receives audio injected into the framework, so the recorder doesn't
1604 // know about it and is therefore considered "legacy"
1605 *inputType = API_INPUT_LEGACY;
1606 } else {
1607 // recording a mix of players defined by an external policy, we're rerouting for
1608 // an external policy
1609 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1610 }
Eric Laurentc722f302014-12-10 11:21:49 -08001611 } else if (audio_is_remote_submix_device(device)) {
1612 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001613 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001614 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1615 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001616 } else {
1617 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001618 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001619
Eric Laurent599c7582015-12-07 18:05:55 -08001620 }
1621
1622 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001623 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001624 policyMix);
1625 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001626 status = INVALID_OPERATION;
1627 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001628 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001629
Eric Laurentad2e7b92017-09-14 20:06:42 -07001630 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001631 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1632 : AUDIO_PORT_HANDLE_NONE;
1633
1634 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1635 *input, *inputType, *selectedDeviceId);
1636
Eric Laurent599c7582015-12-07 18:05:55 -08001637 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001638
1639error:
1640 mInputRoutes.removeRoute(session);
1641 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001642}
1643
1644
1645audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1646 String8 address,
1647 audio_session_t session,
1648 uid_t uid,
1649 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001650 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001651 audio_input_flags_t flags,
1652 AudioMix *policyMix)
1653{
1654 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1655 audio_source_t halInputSource = inputSource;
1656 bool isSoundTrigger = false;
1657
1658 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1659 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1660 if (index >= 0) {
1661 input = mSoundTriggerSessions.valueFor(session);
1662 isSoundTrigger = true;
1663 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1664 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1665 } else {
1666 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001667 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001668 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001669 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001670 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001671 }
1672
Andy Hungf129b032015-04-07 13:45:50 -07001673 // find a compatible input profile (not necessarily identical in parameters)
1674 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001675 // sampling rate and flags may be updated by getInputProfile
1676 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1677 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001678 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001679 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001680 audio_input_flags_t profileFlags = flags;
1681 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001682 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001683 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001684 profileSamplingRate, profileFormat, profileChannelMask,
1685 profileFlags);
1686 if (profile != 0) {
1687 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001688 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1689 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001690 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1691 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1692 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001693 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001694 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1695 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001696 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001699 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001700 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001701 if (samplingRate == 0) {
1702 samplingRate = profileSamplingRate;
1703 }
Eric Laurente552edb2014-03-10 17:42:56 -07001704
Eric Laurent322b4d22015-04-03 15:57:54 -07001705 if (profile->getModuleHandle() == 0) {
1706 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001707 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001708 }
1709
Eric Laurent599c7582015-12-07 18:05:55 -08001710 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001711 inputSource,
1712 config->format,
1713 samplingRate,
1714 config->channel_mask,
1715 flags,
1716 uid,
1717 isSoundTrigger,
1718 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001719
Eric Laurent74708e72017-04-07 17:13:42 -07001720// FIXME: disable concurrent capture until UI is ready
1721#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001722 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001723 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001724 for (size_t i = 0; i < mInputs.size(); i++) {
1725 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001726 // reuse input if:
1727 // - it shares the same profile
1728 // AND
1729 // - it is not a reroute submix input
1730 // AND
1731 // - it is: not used for sound trigger
1732 // OR
1733 // used for sound trigger and all clients use the same session ID
1734 //
1735 if ((profile == desc->mProfile) &&
1736 (isSoundTrigger == desc->isSoundTrigger()) &&
1737 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001738
1739 sp<AudioSession> as = desc->getAudioSession(session);
1740 if (as != 0) {
1741 // do not allow unmatching properties on same session
1742 if (as->matches(audioSession)) {
1743 as->changeOpenCount(1);
1744 } else {
1745 ALOGW("getInputForDevice() record with different attributes"
1746 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001747 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001748 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001749 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001750 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001751 }
Eric Laurentbb948092017-01-23 18:33:30 -08001752
Eric Laurent555530a2017-02-07 18:17:24 -08001753 // Reuse the already opened input stream on this profile if:
1754 // - the new capture source is background OR
1755 // - the path requested configurations match OR
1756 // - the new source priority is less than the highest source priority on this input
1757 // If the input stream cannot be reused, close it before opening a new stream
1758 // on the same profile for the new client so that the requested path configuration
1759 // can be selected.
1760 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001761 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001762 desc->mChannelMask != config->channel_mask ||
1763 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001764 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001765 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001766 reusedInputDesc = desc;
1767 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001768 } else {
1769 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001770 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1771 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001772 }
Eric Laurent599c7582015-12-07 18:05:55 -08001773 }
1774 }
Eric Laurent599c7582015-12-07 18:05:55 -08001775
Eric Laurent555530a2017-02-07 18:17:24 -08001776 if (reusedInputDesc != 0) {
1777 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1778 for (size_t j = 0; j < sessions.size(); j++) {
1779 audio_session_t currentSession = sessions.keyAt(j);
1780 stopInput(reusedInputDesc->mIoHandle, currentSession);
1781 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1782 }
1783 }
Eric Laurent74708e72017-04-07 17:13:42 -07001784#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001785
Eric Laurent3974e3b2017-12-07 17:58:43 -08001786 if (!profile->canOpenNewIo()) {
1787 return AUDIO_IO_HANDLE_NONE;
1788 }
1789
Eric Laurentfe231122017-11-17 17:48:06 -08001790 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001791
Eric Laurentfe231122017-11-17 17:48:06 -08001792 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1793 lConfig.sample_rate = profileSamplingRate;
1794 lConfig.channel_mask = profileChannelMask;
1795 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001796
Eric Laurent53b810e2017-12-10 17:25:10 -08001797 if (address == "") {
1798 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1799 // the inputs vector must be of size >= 1, but we don't want to crash here
1800 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1801 }
1802
Eric Laurentfe231122017-11-17 17:48:06 -08001803 status_t status = inputDesc->open(&lConfig, device, address,
1804 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001805
1806 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001807 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001808 (profileSamplingRate != lConfig.sample_rate) ||
1809 !audio_formats_match(profileFormat, lConfig.format) ||
1810 (profileChannelMask != lConfig.channel_mask)) {
1811 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001812 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001813 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001814 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001815 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001816 }
Eric Laurent599c7582015-12-07 18:05:55 -08001817 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001818 }
1819
Eric Laurentc722f302014-12-10 11:21:49 -08001820 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001821 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001822
Eric Laurent599c7582015-12-07 18:05:55 -08001823 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001824 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001825
Eric Laurent599c7582015-12-07 18:05:55 -08001826 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001827}
1828
Eric Laurentbb948092017-01-23 18:33:30 -08001829//static
1830bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1831{
1832 return (source == AUDIO_SOURCE_HOTWORD) ||
1833 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1834 (source == AUDIO_SOURCE_FM_TUNER);
1835}
1836
Eric Laurentfb66dd92016-01-28 18:32:03 -08001837bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1838 const sp<AudioSession>& audioSession)
1839{
1840 // Do not allow capture if an active voice call is using a software patch and
1841 // the call TX source device is on the same HW module.
1842 // FIXME: would be better to refine to only inputs whose profile connects to the
1843 // call TX device but this information is not in the audio patch
1844 if (mCallTxPatch != 0 &&
1845 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1846 return false;
1847 }
1848
1849 // starting concurrent capture is enabled if:
1850 // 1) capturing for re-routing
1851 // 2) capturing for HOTWORD source
1852 // 3) capturing for FM TUNER source
1853 // 3) All other active captures are either for re-routing or HOTWORD
1854
1855 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001856 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001857 return true;
1858 }
1859
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001860 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001861 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001862 !is_virtual_input_device(activeInput->mDevice)) {
1863 return false;
1864 }
1865 }
1866
1867 return true;
1868}
1869
Chris Thornton2b864642017-06-27 21:26:07 -07001870// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1871bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1872 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1873 bool soundTriggerSupportsConcurrentCapture = false;
1874 unsigned int numModules = 0;
1875 struct sound_trigger_module_descriptor* nModules = NULL;
1876
1877 status_t status = SoundTrigger::listModules(nModules, &numModules);
1878 if (status == NO_ERROR && numModules != 0) {
1879 nModules = (struct sound_trigger_module_descriptor*) calloc(
1880 numModules, sizeof(struct sound_trigger_module_descriptor));
1881 if (nModules == NULL) {
1882 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1883 // ram the next time this function is called.
1884 ALOGE("Failed to allocate buffer for module descriptors");
1885 return false;
1886 }
1887
1888 status = SoundTrigger::listModules(nModules, &numModules);
1889 if (status == NO_ERROR) {
1890 soundTriggerSupportsConcurrentCapture = true;
1891 for (size_t i = 0; i < numModules; ++i) {
1892 soundTriggerSupportsConcurrentCapture &=
1893 nModules[i].properties.concurrent_capture;
1894 }
1895 }
1896 free(nModules);
1897 }
1898 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1899 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1900 }
1901 return mSoundTriggerSupportsConcurrentCapture;
1902}
1903
Eric Laurentfb66dd92016-01-28 18:32:03 -08001904
Eric Laurent4dc68062014-07-28 17:26:49 -07001905status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001906 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001907 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001908 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001909{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001910
1911 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1912 input, session, silenced, *concurrency);
1913
Eric Laurentfb66dd92016-01-28 18:32:03 -08001914 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001915
Eric Laurente552edb2014-03-10 17:42:56 -07001916 ssize_t index = mInputs.indexOfKey(input);
1917 if (index < 0) {
1918 ALOGW("startInput() unknown input %d", input);
1919 return BAD_VALUE;
1920 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001921 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001922
Eric Laurent599c7582015-12-07 18:05:55 -08001923 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1924 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001925 ALOGW("startInput() unknown session %d on input %d", session, input);
1926 return BAD_VALUE;
1927 }
1928
Eric Laurent74708e72017-04-07 17:13:42 -07001929// FIXME: disable concurrent capture until UI is ready
1930#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001931 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1932 ALOGW("startInput(%d) failed: other input already started", input);
1933 return INVALID_OPERATION;
1934 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001935
Eric Laurentfb66dd92016-01-28 18:32:03 -08001936 if (isInCall()) {
1937 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1938 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001939 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001940 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001941 }
Eric Laurent74708e72017-04-07 17:13:42 -07001942#else
1943 if (!is_virtual_input_device(inputDesc->mDevice)) {
1944 if (mCallTxPatch != 0 &&
1945 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1946 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001947 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001948 return INVALID_OPERATION;
1949 }
1950
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001951 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001952
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001953 // If a UID is idle and records silence and another not silenced recording starts
1954 // from another UID (idle or active) we stop the current idle UID recording in
1955 // favor of the new one - "There can be only one" TM
1956 if (!silenced) {
1957 for (const auto& activeDesc : activeInputs) {
1958 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1959 activeDesc->getId() == inputDesc->getId()) {
1960 continue;
1961 }
1962
1963 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1964 true /*activeOnly*/);
1965 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1966 if (activeSession->isSilenced()) {
1967 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1968 audio_session_t activeSessionId = activeSession->session();
1969 stopInput(activeInput, activeSessionId);
1970 releaseInput(activeInput, activeSessionId);
1971 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1972 activeInputs = mInputs.getActiveInputs();
1973 }
1974 }
1975 }
1976
1977 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001978 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1979 activeDesc->getId() == inputDesc->getId()) {
1980 continue;
1981 }
1982
Eric Laurent74708e72017-04-07 17:13:42 -07001983 audio_source_t activeSource = activeDesc->inputSource(true);
1984 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1985 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1986 if (activeDesc->hasPreemptedSession(session)) {
1987 ALOGW("startInput(%d) failed for HOTWORD: "
1988 "other input %d already started for HOTWORD",
1989 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001990 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001991 return INVALID_OPERATION;
1992 }
1993 } else {
1994 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1995 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001996 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001997 return INVALID_OPERATION;
1998 }
1999 } else {
2000 if (activeSource != AUDIO_SOURCE_HOTWORD) {
2001 ALOGW("startInput(%d) failed: other input %d already started",
2002 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07002003 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07002004 return INVALID_OPERATION;
2005 }
2006 }
2007 }
2008
Chris Thornton2b864642017-06-27 21:26:07 -07002009 // We only need to check if the sound trigger session supports concurrent capture if the
2010 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
2011 // that's running.
2012 const bool allowConcurrentWithSoundTrigger =
2013 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
2014
Eric Laurent74708e72017-04-07 17:13:42 -07002015 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002016 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07002017 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2018 continue;
2019 }
2020
Eric Laurent74708e72017-04-07 17:13:42 -07002021 audio_source_t activeSource = activeDesc->inputSource(true);
2022 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2023 AudioSessionCollection activeSessions =
2024 activeDesc->getAudioSessions(true /*activeOnly*/);
2025 audio_session_t activeSession = activeSessions.keyAt(0);
2026 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2027 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002028 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002029 sessions.add(activeSession);
2030 inputDesc->setPreemptedSessions(sessions);
2031 stopInput(activeHandle, activeSession);
2032 releaseInput(activeHandle, activeSession);
2033 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2034 input, activeDesc->mIoHandle);
2035 }
2036 }
2037 }
2038#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002039
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002040 // Make sure we start with the correct silence state
2041 audioSession->setSilenced(silenced);
2042
Eric Laurent313d1e72016-01-29 09:56:57 -08002043 // increment activity count before calling getNewInputDevice() below as only active sessions
2044 // are considered for device selection
2045 audioSession->changeActiveCount(1);
2046
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002047 // Routing?
2048 mInputRoutes.incRouteActivity(session);
2049
Eric Laurent2157f5b2018-04-25 18:33:02 -07002050 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002051 // indicate active capture to sound trigger service if starting capture from a mic on
2052 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002053 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002054 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002055
Eric Laurent733ce942017-12-07 12:18:25 -08002056 status_t status = inputDesc->start();
2057 if (status != NO_ERROR) {
2058 mInputRoutes.decRouteActivity(session);
2059 audioSession->changeActiveCount(-1);
2060 return status;
2061 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002062
Eric Laurent733ce942017-12-07 12:18:25 -08002063 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002064 // if input maps to a dynamic policy with an activity listener, notify of state change
2065 if ((inputDesc->mPolicyMix != NULL)
2066 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2067 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2068 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002069 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002070
Eric Laurentf7c50102016-09-30 15:19:43 -07002071 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2072 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002073 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002074 SoundTrigger::setCaptureState(true);
2075 }
2076
2077 // automatically enable the remote submix output when input is started if not
2078 // used by a policy mix of type MIX_TYPE_RECORDERS
2079 // For remote submix (a virtual device), we open only one input per capture request.
2080 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2081 String8 address = String8("");
2082 if (inputDesc->mPolicyMix == NULL) {
2083 address = String8("0");
2084 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2085 address = inputDesc->mPolicyMix->mDeviceAddress;
2086 }
2087 if (address != "") {
2088 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2089 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2090 address, "remote-submix");
2091 }
Eric Laurentc722f302014-12-10 11:21:49 -08002092 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002093 }
Eric Laurente552edb2014-03-10 17:42:56 -07002094 }
2095
Eric Laurent599c7582015-12-07 18:05:55 -08002096 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002097
Eric Laurente552edb2014-03-10 17:42:56 -07002098 return NO_ERROR;
2099}
2100
Eric Laurent4dc68062014-07-28 17:26:49 -07002101status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2102 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002103{
2104 ALOGV("stopInput() input %d", input);
2105 ssize_t index = mInputs.indexOfKey(input);
2106 if (index < 0) {
2107 ALOGW("stopInput() unknown input %d", input);
2108 return BAD_VALUE;
2109 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002110 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002111
Eric Laurent599c7582015-12-07 18:05:55 -08002112 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002113 if (index < 0) {
2114 ALOGW("stopInput() unknown session %d on input %d", session, input);
2115 return BAD_VALUE;
2116 }
2117
Eric Laurent599c7582015-12-07 18:05:55 -08002118 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002119 ALOGW("stopInput() input %d already stopped", input);
2120 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002121 }
2122
Eric Laurent599c7582015-12-07 18:05:55 -08002123 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002124
2125 // Routing?
2126 mInputRoutes.decRouteActivity(session);
2127
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002128 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002129 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002130 if (inputDesc->isActive()) {
2131 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2132 } else {
2133 // if input maps to a dynamic policy with an activity listener, notify of state change
2134 if ((inputDesc->mPolicyMix != NULL)
2135 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2136 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2137 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002138 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002139
2140 // automatically disable the remote submix output when input is stopped if not
2141 // used by a policy mix of type MIX_TYPE_RECORDERS
2142 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2143 String8 address = String8("");
2144 if (inputDesc->mPolicyMix == NULL) {
2145 address = String8("0");
2146 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2147 address = inputDesc->mPolicyMix->mDeviceAddress;
2148 }
2149 if (address != "") {
2150 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2151 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2152 address, "remote-submix");
2153 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002154 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002155
Eric Laurentf7c50102016-09-30 15:19:43 -07002156 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002157 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002158
Eric Laurentf7c50102016-09-30 15:19:43 -07002159 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2160 // primary HW module
2161 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2162 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2163 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002164 SoundTrigger::setCaptureState(false);
2165 }
2166 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002167 }
Eric Laurente552edb2014-03-10 17:42:56 -07002168 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002169 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002170}
2171
Eric Laurent4dc68062014-07-28 17:26:49 -07002172void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2173 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002174{
2175 ALOGV("releaseInput() %d", input);
2176 ssize_t index = mInputs.indexOfKey(input);
2177 if (index < 0) {
2178 ALOGW("releaseInput() releasing unknown input %d", input);
2179 return;
2180 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002181
2182 // Routing
2183 mInputRoutes.removeRoute(session);
2184
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002185 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2186 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002187
Eric Laurent599c7582015-12-07 18:05:55 -08002188 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002189 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002190 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2191 return;
2192 }
Eric Laurent599c7582015-12-07 18:05:55 -08002193
2194 if (audioSession->openCount() == 0) {
2195 ALOGW("releaseInput() invalid open count %d on session %d",
2196 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002197 return;
2198 }
Eric Laurent599c7582015-12-07 18:05:55 -08002199
2200 if (audioSession->changeOpenCount(-1) == 0) {
2201 inputDesc->removeAudioSession(session);
2202 }
2203
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002204 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002205 ALOGV("releaseInput() exit > 0");
2206 return;
2207 }
2208
Eric Laurent05b90f82014-08-27 15:32:29 -07002209 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002210 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002211 ALOGV("releaseInput() exit");
2212}
2213
Eric Laurentd4692962014-05-05 18:13:44 -07002214void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002215 bool patchRemoved = false;
2216
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002217 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002218 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002219 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002220 if (patch_index >= 0) {
2221 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002222 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002223 mAudioPatches.removeItemsAt(patch_index);
2224 patchRemoved = true;
2225 }
Eric Laurentfe231122017-11-17 17:48:06 -08002226 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002227 }
jiabin829a00b2018-04-04 16:28:32 -07002228 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002229 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002230 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002231 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002232
2233 if (patchRemoved) {
2234 mpClientInterface->onAudioPatchListUpdate();
2235 }
Eric Laurentd4692962014-05-05 18:13:44 -07002236}
2237
Eric Laurente0720872014-03-11 09:30:41 -07002238void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002239 int indexMin,
2240 int indexMax)
2241{
2242 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002243 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002244
2245 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002246 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2247 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002248 continue;
2249 }
2250 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002251 }
Eric Laurente552edb2014-03-10 17:42:56 -07002252}
2253
Eric Laurente0720872014-03-11 09:30:41 -07002254status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002255 int index,
2256 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002257{
2258
Nadav Bar7c605f62017-12-25 00:01:52 +02002259 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2260 // app that has MODIFY_PHONE_STATE permission.
2261 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2262 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002263 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002264 return BAD_VALUE;
2265 }
2266 if (!audio_is_output_device(device)) {
2267 return BAD_VALUE;
2268 }
2269
2270 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002271 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002272
Eric Laurent1fd372e2016-04-06 14:23:53 -07002273 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002274 stream, device, index);
2275
Eric Laurent28d09f02016-03-08 10:43:05 -08002276 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002277 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2278 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002279 continue;
2280 }
2281 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2282 }
Eric Laurente552edb2014-03-10 17:42:56 -07002283
Eric Laurent1fd372e2016-04-06 14:23:53 -07002284 // update volume on all outputs and streams matching the following:
2285 // - The requested stream (or a stream matching for volume control) is active on the output
2286 // - The device (or devices) selected by the strategy corresponding to this stream includes
2287 // the requested device
2288 // - For non default requested device, currently selected device on the output is either the
2289 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002290 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2291 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002292 status_t status = NO_ERROR;
2293 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2295 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002296 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2297 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002298 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002299 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002300 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2301 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002302 continue;
2303 }
Eric Laurent794fde22016-03-11 09:50:45 -08002304 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002305 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2306 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002307 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2308 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002309 continue;
2310 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002311 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002312 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002313 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002314 applyVolume = (curDevice & curStreamDevice) != 0;
2315 } else {
2316 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002317 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002318 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002319
Eric Laurente76f29c2016-09-14 17:17:53 -07002320 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002321 //FIXME: workaround for truncated touch sounds
2322 // delayed volume change for system stream to be removed when the problem is
2323 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002324 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002325 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2326 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002327 if (volStatus != NO_ERROR) {
2328 status = volStatus;
2329 }
2330 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002331 }
Eric Laurente552edb2014-03-10 17:42:56 -07002332 }
2333 return status;
2334}
2335
Eric Laurente0720872014-03-11 09:30:41 -07002336status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002337 int *index,
2338 audio_devices_t device)
2339{
2340 if (index == NULL) {
2341 return BAD_VALUE;
2342 }
2343 if (!audio_is_output_device(device)) {
2344 return BAD_VALUE;
2345 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002346 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002347 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002348 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002349 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2350 }
François Gaffiedfd74092015-03-19 12:10:59 +01002351 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002352
François Gaffied1ab2bd2015-12-02 18:20:06 +01002353 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002354 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2355 return NO_ERROR;
2356}
2357
Eric Laurent36829f92017-04-07 19:04:42 -07002358audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002359{
2360 // select one output among several suitable for global effects.
2361 // The priority is as follows:
2362 // 1: An offloaded output. If the effect ends up not being offloadable,
2363 // AudioFlinger will invalidate the track and the offloaded output
2364 // will be closed causing the effect to be moved to a PCM output.
2365 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002366 // 3: The primary output
2367 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002368
Eric Laurent3b73df72014-03-11 09:06:29 -07002369 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002370 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002371 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002372
Eric Laurent36829f92017-04-07 19:04:42 -07002373 if (outputs.size() == 0) {
2374 return AUDIO_IO_HANDLE_NONE;
2375 }
Eric Laurente552edb2014-03-10 17:42:56 -07002376
Eric Laurent36829f92017-04-07 19:04:42 -07002377 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2378 bool activeOnly = true;
2379
2380 while (output == AUDIO_IO_HANDLE_NONE) {
2381 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2382 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2383 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2384
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002385 for (audio_io_handle_t output : outputs) {
2386 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002387 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2388 continue;
2389 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002390 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2391 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002392 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002393 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002394 }
2395 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002396 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002397 }
2398 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002399 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002400 }
2401 }
2402 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2403 output = outputOffloaded;
2404 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2405 output = outputDeepBuffer;
2406 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2407 output = outputPrimary;
2408 } else {
2409 output = outputs[0];
2410 }
2411 activeOnly = false;
2412 }
2413
2414 if (output != mMusicEffectOutput) {
2415 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2416 mMusicEffectOutput = output;
2417 }
2418
2419 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002420 return output;
2421}
2422
Eric Laurent36829f92017-04-07 19:04:42 -07002423audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2424{
2425 return selectOutputForMusicEffects();
2426}
2427
Eric Laurente0720872014-03-11 09:30:41 -07002428status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002429 audio_io_handle_t io,
2430 uint32_t strategy,
2431 int session,
2432 int id)
2433{
2434 ssize_t index = mOutputs.indexOfKey(io);
2435 if (index < 0) {
2436 index = mInputs.indexOfKey(io);
2437 if (index < 0) {
2438 ALOGW("registerEffect() unknown io %d", io);
2439 return INVALID_OPERATION;
2440 }
2441 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002442 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002443}
2444
Eric Laurentc75307b2015-03-17 15:29:32 -07002445bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2446{
Eric Laurent28d09f02016-03-08 10:43:05 -08002447 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002448 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2449 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002450 continue;
2451 }
2452 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2453 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002454 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002455}
2456
2457bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2458{
2459 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2460}
2461
Eric Laurente0720872014-03-11 09:30:41 -07002462bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002463{
2464 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002465 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002466 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002467 return true;
2468 }
2469 }
2470 return false;
2471}
2472
Eric Laurent275e8e92014-11-30 15:14:47 -08002473// Register a list of custom mixes with their attributes and format.
2474// When a mix is registered, corresponding input and output profiles are
2475// added to the remote submix hw module. The profile contains only the
2476// parameters (sampling rate, format...) specified by the mix.
2477// The corresponding input remote submix device is also connected.
2478//
2479// When a remote submix device is connected, the address is checked to select the
2480// appropriate profile and the corresponding input or output stream is opened.
2481//
2482// When capture starts, getInputForAttr() will:
2483// - 1 look for a mix matching the address passed in attribtutes tags if any
2484// - 2 if none found, getDeviceForInputSource() will:
2485// - 2.1 look for a mix matching the attributes source
2486// - 2.2 if none found, default to device selection by policy rules
2487// At this time, the corresponding output remote submix device is also connected
2488// and active playback use cases can be transferred to this mix if needed when reconnecting
2489// after AudioTracks are invalidated
2490//
2491// When playback starts, getOutputForAttr() will:
2492// - 1 look for a mix matching the address passed in attribtutes tags if any
2493// - 2 if none found, look for a mix matching the attributes usage
2494// - 3 if none found, default to device and output selection by policy rules.
2495
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002496status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002497{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002498 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2499 status_t res = NO_ERROR;
2500
2501 sp<HwModule> rSubmixModule;
2502 // examine each mix's route type
2503 for (size_t i = 0; i < mixes.size(); i++) {
2504 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2505 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2506 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002507 break;
2508 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002509 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002511 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002512 rSubmixModule = mHwModules.getModuleFromName(
2513 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2514 if (rSubmixModule == 0) {
2515 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2516 i);
2517 res = INVALID_OPERATION;
2518 break;
2519 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002521
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002523
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002525 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 res = INVALID_OPERATION;
2527 break;
2528 }
2529 audio_config_t outputConfig = mixes[i].mFormat;
2530 audio_config_t inputConfig = mixes[i].mFormat;
2531 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2532 // stereo and let audio flinger do the channel conversion if needed.
2533 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2534 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2535 rSubmixModule->addOutputProfile(address, &outputConfig,
2536 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2537 rSubmixModule->addInputProfile(address, &inputConfig,
2538 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002539
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2541 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2542 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2543 address.string(), "remote-submix");
2544 } else {
2545 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2546 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2547 address.string(), "remote-submix");
2548 }
2549 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002550 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002552 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2553 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002554
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002555 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2558 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2559 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2560 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2561 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002562 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2563 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2565 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002566 } else {
2567 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 }
2569 break;
2570 }
2571 }
2572
2573 if (res != NO_ERROR) {
2574 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002575 i, device, address.string());
2576 res = INVALID_OPERATION;
2577 break;
2578 } else if (!foundOutput) {
2579 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2580 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002581 res = INVALID_OPERATION;
2582 break;
2583 }
Eric Laurentc722f302014-12-10 11:21:49 -08002584 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002585 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002586 if (res != NO_ERROR) {
2587 unregisterPolicyMixes(mixes);
2588 }
2589 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002590}
2591
2592status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2593{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002594 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002595 status_t res = NO_ERROR;
2596 sp<HwModule> rSubmixModule;
2597 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002598 for (const auto& mix : mixes) {
2599 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002600
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002601 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002602 rSubmixModule = mHwModules.getModuleFromName(
2603 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2604 if (rSubmixModule == 0) {
2605 res = INVALID_OPERATION;
2606 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002607 }
2608 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002609
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002610 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002611
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002612 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2613 res = INVALID_OPERATION;
2614 continue;
2615 }
2616
2617 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2618 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2619 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2620 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2621 address.string(), "remote-submix");
2622 }
2623 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2624 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2625 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2626 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2627 address.string(), "remote-submix");
2628 }
2629 rSubmixModule->removeOutputProfile(address);
2630 rSubmixModule->removeInputProfile(address);
2631
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002632 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2633 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002634 res = INVALID_OPERATION;
2635 continue;
2636 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002637 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002638 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002639 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002640}
2641
Eric Laurente552edb2014-03-10 17:42:56 -07002642
Eric Laurente0720872014-03-11 09:30:41 -07002643status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002644{
2645 const size_t SIZE = 256;
2646 char buffer[SIZE];
2647 String8 result;
2648
2649 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2650 result.append(buffer);
2651
Eric Laurent87ffa392015-05-22 10:32:38 -07002652 snprintf(buffer, SIZE, " Primary Output: %d\n",
2653 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002655 std::string stateLiteral;
2656 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2657 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002658 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002659 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002660 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002661 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002662 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002663 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002664 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002665 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002666 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002667 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002668 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002669 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002670 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002671 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002672 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002673 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2674 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2675 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002676 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2677 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002678 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2679 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002680
François Gaffie2110e042015-03-24 08:41:51 +01002681 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002682
François Gaffie112b0af2015-11-19 16:13:25 +01002683 mAvailableOutputDevices.dump(fd, String8("Available output"));
2684 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002685 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002686 mOutputs.dump(fd);
2687 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002688 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002689 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002690 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002691 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002692
2693 return NO_ERROR;
2694}
2695
2696// This function checks for the parameters which can be offloaded.
2697// This can be enhanced depending on the capability of the DSP and policy
2698// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002699bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002700{
2701 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002702 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002703 offloadInfo.sample_rate, offloadInfo.channel_mask,
2704 offloadInfo.format,
2705 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2706 offloadInfo.has_video);
2707
Andy Hung2ddee192015-12-18 17:34:44 -08002708 if (mMasterMono) {
2709 return false; // no offloading if mono is set.
2710 }
2711
Eric Laurente552edb2014-03-10 17:42:56 -07002712 // Check if offload has been disabled
2713 char propValue[PROPERTY_VALUE_MAX];
2714 if (property_get("audio.offload.disable", propValue, "0")) {
2715 if (atoi(propValue) != 0) {
2716 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2717 return false;
2718 }
2719 }
2720
2721 // Check if stream type is music, then only allow offload as of now.
2722 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2723 {
2724 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2725 return false;
2726 }
2727
2728 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002729 const bool allowOffloadWithVideo =
2730 property_get_bool("audio.offload.video", false /* default_value */);
2731 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002732 ALOGV("isOffloadSupported: has_video == true, returning false");
2733 return false;
2734 }
2735
2736 //If duration is less than minimum value defined in property, return false
2737 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2738 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2739 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2740 return false;
2741 }
2742 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2743 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2744 return false;
2745 }
2746
2747 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2748 // creating an offloaded track and tearing it down immediately after start when audioflinger
2749 // detects there is an active non offloadable effect.
2750 // FIXME: We should check the audio session here but we do not have it in this context.
2751 // This may prevent offloading in rare situations where effects are left active by apps
2752 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002753 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002754 return false;
2755 }
2756
2757 // See if there is a profile to support this.
2758 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002759 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002760 offloadInfo.sample_rate,
2761 offloadInfo.format,
2762 offloadInfo.channel_mask,
2763 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002764 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2765 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002766}
2767
Eric Laurent6a94d692014-05-20 11:18:06 -07002768status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2769 audio_port_type_t type,
2770 unsigned int *num_ports,
2771 struct audio_port *ports,
2772 unsigned int *generation)
2773{
2774 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2775 generation == NULL) {
2776 return BAD_VALUE;
2777 }
2778 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2779 if (ports == NULL) {
2780 *num_ports = 0;
2781 }
2782
2783 size_t portsWritten = 0;
2784 size_t portsMax = *num_ports;
2785 *num_ports = 0;
2786 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002787 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2788 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002789 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002790 for (const auto& dev : mAvailableOutputDevices) {
2791 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002792 continue;
2793 }
2794 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002795 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002796 }
2797 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002799 }
2800 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002801 for (const auto& dev : mAvailableInputDevices) {
2802 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002803 continue;
2804 }
2805 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002806 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002807 }
2808 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002809 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 }
2811 }
2812 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2813 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2814 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2815 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2816 }
2817 *num_ports += mInputs.size();
2818 }
2819 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002820 size_t numOutputs = 0;
2821 for (size_t i = 0; i < mOutputs.size(); i++) {
2822 if (!mOutputs[i]->isDuplicated()) {
2823 numOutputs++;
2824 if (portsWritten < portsMax) {
2825 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2826 }
2827 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 }
Eric Laurent84c70242014-06-23 08:46:27 -07002829 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002830 }
2831 }
2832 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002833 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002834 return NO_ERROR;
2835}
2836
Eric Laurent99fcae42018-05-17 16:59:18 -07002837status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002838{
Eric Laurent99fcae42018-05-17 16:59:18 -07002839 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2840 return BAD_VALUE;
2841 }
2842 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2843 if (dev != 0) {
2844 dev->toAudioPort(port);
2845 return NO_ERROR;
2846 }
2847 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2848 if (dev != 0) {
2849 dev->toAudioPort(port);
2850 return NO_ERROR;
2851 }
2852 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2853 if (out != 0) {
2854 out->toAudioPort(port);
2855 return NO_ERROR;
2856 }
2857 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2858 if (in != 0) {
2859 in->toAudioPort(port);
2860 return NO_ERROR;
2861 }
2862 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002863}
2864
Eric Laurent6a94d692014-05-20 11:18:06 -07002865status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2866 audio_patch_handle_t *handle,
2867 uid_t uid)
2868{
2869 ALOGV("createAudioPatch()");
2870
2871 if (handle == NULL || patch == NULL) {
2872 return BAD_VALUE;
2873 }
2874 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2875
Eric Laurent874c42872014-08-08 15:13:39 -07002876 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2877 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2878 return BAD_VALUE;
2879 }
2880 // only one source per audio patch supported for now
2881 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002882 return INVALID_OPERATION;
2883 }
Eric Laurent874c42872014-08-08 15:13:39 -07002884
2885 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002886 return INVALID_OPERATION;
2887 }
Eric Laurent874c42872014-08-08 15:13:39 -07002888 for (size_t i = 0; i < patch->num_sinks; i++) {
2889 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2890 return INVALID_OPERATION;
2891 }
2892 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002893
2894 sp<AudioPatch> patchDesc;
2895 ssize_t index = mAudioPatches.indexOfKey(*handle);
2896
Eric Laurent6a94d692014-05-20 11:18:06 -07002897 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2898 patch->sources[0].role,
2899 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002900#if LOG_NDEBUG == 0
2901 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002902 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002903 patch->sinks[i].role,
2904 patch->sinks[i].type);
2905 }
2906#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002907
2908 if (index >= 0) {
2909 patchDesc = mAudioPatches.valueAt(index);
2910 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2911 mUidCached, patchDesc->mUid, uid);
2912 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2913 return INVALID_OPERATION;
2914 }
2915 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002916 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002917 }
2918
2919 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002920 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 if (outputDesc == NULL) {
2922 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2923 return BAD_VALUE;
2924 }
Eric Laurent84c70242014-06-23 08:46:27 -07002925 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2926 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002927 if (patchDesc != 0) {
2928 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2929 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2930 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2931 return BAD_VALUE;
2932 }
2933 }
Eric Laurent874c42872014-08-08 15:13:39 -07002934 DeviceVector devices;
2935 for (size_t i = 0; i < patch->num_sinks; i++) {
2936 // Only support mix to devices connection
2937 // TODO add support for mix to mix connection
2938 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2939 ALOGV("createAudioPatch() source mix but sink is not a device");
2940 return INVALID_OPERATION;
2941 }
2942 sp<DeviceDescriptor> devDesc =
2943 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2944 if (devDesc == 0) {
2945 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2946 return BAD_VALUE;
2947 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002948
François Gaffie53615e22015-03-19 09:24:12 +01002949 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002950 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002951 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002952 NULL, // updatedSamplingRate
2953 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002954 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002955 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002956 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002957 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002958 ALOGV("createAudioPatch() profile not supported for device %08x",
2959 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002960 return INVALID_OPERATION;
2961 }
2962 devices.add(devDesc);
2963 }
2964 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002965 return INVALID_OPERATION;
2966 }
Eric Laurent874c42872014-08-08 15:13:39 -07002967
Eric Laurent6a94d692014-05-20 11:18:06 -07002968 // TODO: reconfigure output format and channels here
2969 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002970 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002971 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002972 index = mAudioPatches.indexOfKey(*handle);
2973 if (index >= 0) {
2974 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2975 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2976 }
2977 patchDesc = mAudioPatches.valueAt(index);
2978 patchDesc->mUid = uid;
2979 ALOGV("createAudioPatch() success");
2980 } else {
2981 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2982 return INVALID_OPERATION;
2983 }
2984 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2985 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2986 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002987 // only one sink supported when connecting an input device to a mix
2988 if (patch->num_sinks > 1) {
2989 return INVALID_OPERATION;
2990 }
François Gaffie53615e22015-03-19 09:24:12 +01002991 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002992 if (inputDesc == NULL) {
2993 return BAD_VALUE;
2994 }
2995 if (patchDesc != 0) {
2996 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2997 return BAD_VALUE;
2998 }
2999 }
3000 sp<DeviceDescriptor> devDesc =
3001 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3002 if (devDesc == 0) {
3003 return BAD_VALUE;
3004 }
3005
François Gaffie53615e22015-03-19 09:24:12 +01003006 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08003007 devDesc->mAddress,
3008 patch->sinks[0].sample_rate,
3009 NULL, /*updatedSampleRate*/
3010 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003011 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003012 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003013 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003014 // FIXME for the parameter type,
3015 // and the NONE
3016 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003017 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003018 return INVALID_OPERATION;
3019 }
3020 // TODO: reconfigure output format and channels here
3021 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003022 devDesc->type(), inputDesc->mIoHandle);
3023 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003024 index = mAudioPatches.indexOfKey(*handle);
3025 if (index >= 0) {
3026 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3027 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3028 }
3029 patchDesc = mAudioPatches.valueAt(index);
3030 patchDesc->mUid = uid;
3031 ALOGV("createAudioPatch() success");
3032 } else {
3033 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3034 return INVALID_OPERATION;
3035 }
3036 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3037 // device to device connection
3038 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003039 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 return BAD_VALUE;
3041 }
3042 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003043 sp<DeviceDescriptor> srcDeviceDesc =
3044 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003045 if (srcDeviceDesc == 0) {
3046 return BAD_VALUE;
3047 }
Eric Laurent874c42872014-08-08 15:13:39 -07003048
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 //update source and sink with our own data as the data passed in the patch may
3050 // be incomplete.
3051 struct audio_patch newPatch = *patch;
3052 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003053
Eric Laurent874c42872014-08-08 15:13:39 -07003054 for (size_t i = 0; i < patch->num_sinks; i++) {
3055 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3056 ALOGV("createAudioPatch() source device but one sink is not a device");
3057 return INVALID_OPERATION;
3058 }
3059
3060 sp<DeviceDescriptor> sinkDeviceDesc =
3061 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3062 if (sinkDeviceDesc == 0) {
3063 return BAD_VALUE;
3064 }
3065 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3066
Eric Laurent3bcf8592015-04-03 12:13:24 -07003067 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003068 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003069 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003070 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003071 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003072 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003073 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003074 return INVALID_OPERATION;
3075 }
Eric Laurent874c42872014-08-08 15:13:39 -07003076 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003077 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003078 // if the sink device is reachable via an opened output stream, request to go via
3079 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003080 audio_io_handle_t output = selectOutput(outputs,
3081 AUDIO_OUTPUT_FLAG_NONE,
3082 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003083 if (output != AUDIO_IO_HANDLE_NONE) {
3084 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3085 if (outputDesc->isDuplicated()) {
3086 return INVALID_OPERATION;
3087 }
3088 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003089 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003090 newPatch.num_sources = 2;
3091 }
Eric Laurent83b88082014-06-20 18:31:16 -07003092 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003093 }
3094 // TODO: check from routing capabilities in config file and other conflicting patches
3095
3096 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3097 if (index >= 0) {
3098 afPatchHandle = patchDesc->mAfPatchHandle;
3099 }
3100
3101 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3102 &afPatchHandle,
3103 0);
3104 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3105 status, afPatchHandle);
3106 if (status == NO_ERROR) {
3107 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003108 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003109 addAudioPatch(patchDesc->mHandle, patchDesc);
3110 } else {
3111 patchDesc->mPatch = newPatch;
3112 }
3113 patchDesc->mAfPatchHandle = afPatchHandle;
3114 *handle = patchDesc->mHandle;
3115 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003116 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 } else {
3118 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3119 status);
3120 return INVALID_OPERATION;
3121 }
3122 } else {
3123 return BAD_VALUE;
3124 }
3125 } else {
3126 return BAD_VALUE;
3127 }
3128 return NO_ERROR;
3129}
3130
3131status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3132 uid_t uid)
3133{
3134 ALOGV("releaseAudioPatch() patch %d", handle);
3135
3136 ssize_t index = mAudioPatches.indexOfKey(handle);
3137
3138 if (index < 0) {
3139 return BAD_VALUE;
3140 }
3141 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3142 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3143 mUidCached, patchDesc->mUid, uid);
3144 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3145 return INVALID_OPERATION;
3146 }
3147
3148 struct audio_patch *patch = &patchDesc->mPatch;
3149 patchDesc->mUid = mUidCached;
3150 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003151 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003152 if (outputDesc == NULL) {
3153 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3154 return BAD_VALUE;
3155 }
3156
Eric Laurentc75307b2015-03-17 15:29:32 -07003157 setOutputDevice(outputDesc,
3158 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003159 true,
3160 0,
3161 NULL);
3162 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3163 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 if (inputDesc == NULL) {
3166 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3167 return BAD_VALUE;
3168 }
3169 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003170 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003171 true,
3172 NULL);
3173 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003174 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3175 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3176 status, patchDesc->mAfPatchHandle);
3177 removeAudioPatch(patchDesc->mHandle);
3178 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003179 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003180 } else {
3181 return BAD_VALUE;
3182 }
3183 } else {
3184 return BAD_VALUE;
3185 }
3186 return NO_ERROR;
3187}
3188
3189status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3190 struct audio_patch *patches,
3191 unsigned int *generation)
3192{
François Gaffie53615e22015-03-19 09:24:12 +01003193 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003194 return BAD_VALUE;
3195 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003196 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003197 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003198}
3199
Eric Laurente1715a42014-05-20 11:30:42 -07003200status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003201{
Eric Laurente1715a42014-05-20 11:30:42 -07003202 ALOGV("setAudioPortConfig()");
3203
3204 if (config == NULL) {
3205 return BAD_VALUE;
3206 }
3207 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3208 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003209 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3210 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003211 }
3212
Eric Laurenta121f902014-06-03 13:32:54 -07003213 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003214 if (config->type == AUDIO_PORT_TYPE_MIX) {
3215 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003216 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003217 if (outputDesc == NULL) {
3218 return BAD_VALUE;
3219 }
Eric Laurent84c70242014-06-23 08:46:27 -07003220 ALOG_ASSERT(!outputDesc->isDuplicated(),
3221 "setAudioPortConfig() called on duplicated output %d",
3222 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003223 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003224 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003225 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003226 if (inputDesc == NULL) {
3227 return BAD_VALUE;
3228 }
Eric Laurenta121f902014-06-03 13:32:54 -07003229 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003230 } else {
3231 return BAD_VALUE;
3232 }
3233 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3234 sp<DeviceDescriptor> deviceDesc;
3235 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3236 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3237 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3238 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3239 } else {
3240 return BAD_VALUE;
3241 }
3242 if (deviceDesc == NULL) {
3243 return BAD_VALUE;
3244 }
Eric Laurenta121f902014-06-03 13:32:54 -07003245 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003246 } else {
3247 return BAD_VALUE;
3248 }
3249
Eric Laurenta121f902014-06-03 13:32:54 -07003250 struct audio_port_config backupConfig;
3251 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3252 if (status == NO_ERROR) {
3253 struct audio_port_config newConfig;
3254 audioPortConfig->toAudioPortConfig(&newConfig, config);
3255 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003256 }
Eric Laurenta121f902014-06-03 13:32:54 -07003257 if (status != NO_ERROR) {
3258 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003259 }
Eric Laurente1715a42014-05-20 11:30:42 -07003260
3261 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003262}
3263
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003264void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3265{
Eric Laurentd60560a2015-04-10 11:31:20 -07003266 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003267 clearAudioPatches(uid);
3268 clearSessionRoutes(uid);
3269}
3270
Eric Laurent6a94d692014-05-20 11:18:06 -07003271void AudioPolicyManager::clearAudioPatches(uid_t uid)
3272{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003273 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003274 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3275 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003276 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003277 }
3278 }
3279}
3280
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003281void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3282 audio_io_handle_t ouptutToSkip)
3283{
3284 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3285 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3286 for (size_t j = 0; j < mOutputs.size(); j++) {
3287 if (mOutputs.keyAt(j) == ouptutToSkip) {
3288 continue;
3289 }
3290 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3291 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3292 continue;
3293 }
3294 // If the default device for this strategy is on another output mix,
3295 // invalidate all tracks in this strategy to force re connection.
3296 // Otherwise select new device on the output mix.
3297 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003298 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003299 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3300 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3301 }
3302 }
3303 } else {
3304 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3305 setOutputDevice(outputDesc, newDevice, false);
3306 }
3307 }
3308}
3309
3310void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3311{
3312 // remove output routes associated with this uid
3313 SortedVector<routing_strategy> affectedStrategies;
3314 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3315 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3316 if (route->mUid == uid) {
3317 mOutputRoutes.removeItemsAt(i);
3318 if (route->mDeviceDescriptor != 0) {
3319 affectedStrategies.add(getStrategy(route->mStreamType));
3320 }
3321 }
3322 }
3323 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003324 for (const auto& strategy : affectedStrategies) {
3325 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003326 }
3327
3328 // remove input routes associated with this uid
3329 SortedVector<audio_source_t> affectedSources;
3330 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3331 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3332 if (route->mUid == uid) {
3333 mInputRoutes.removeItemsAt(i);
3334 if (route->mDeviceDescriptor != 0) {
3335 affectedSources.add(route->mSource);
3336 }
3337 }
3338 }
3339 // reroute inputs if necessary
3340 SortedVector<audio_io_handle_t> inputsToClose;
3341 for (size_t i = 0; i < mInputs.size(); i++) {
3342 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003343 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003344 inputsToClose.add(inputDesc->mIoHandle);
3345 }
3346 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003347 for (const auto& input : inputsToClose) {
3348 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003349 }
3350}
3351
Eric Laurentd60560a2015-04-10 11:31:20 -07003352void AudioPolicyManager::clearAudioSources(uid_t uid)
3353{
3354 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3355 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3356 if (sourceDesc->mUid == uid) {
3357 stopAudioSource(mAudioSources.keyAt(i));
3358 }
3359 }
3360}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003361
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003362status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3363 audio_io_handle_t *ioHandle,
3364 audio_devices_t *device)
3365{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003366 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3367 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003368 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003369
François Gaffiedf372692015-03-19 10:43:27 +01003370 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003371}
3372
Eric Laurentd60560a2015-04-10 11:31:20 -07003373status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3374 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003375 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003376 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003377{
Eric Laurentd60560a2015-04-10 11:31:20 -07003378 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3379 if (source == NULL || attributes == NULL || handle == NULL) {
3380 return BAD_VALUE;
3381 }
3382
Glenn Kasten559d4392016-03-29 13:42:57 -07003383 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003384
3385 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3386 source->type != AUDIO_PORT_TYPE_DEVICE) {
3387 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3388 return INVALID_OPERATION;
3389 }
3390
3391 sp<DeviceDescriptor> srcDeviceDesc =
3392 mAvailableInputDevices.getDevice(source->ext.device.type,
3393 String8(source->ext.device.address));
3394 if (srcDeviceDesc == 0) {
3395 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3396 return BAD_VALUE;
3397 }
3398 sp<AudioSourceDescriptor> sourceDesc =
3399 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3400
3401 struct audio_patch dummyPatch;
3402 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3403 sourceDesc->mPatchDesc = patchDesc;
3404
3405 status_t status = connectAudioSource(sourceDesc);
3406 if (status == NO_ERROR) {
3407 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3408 *handle = sourceDesc->getHandle();
3409 }
3410 return status;
3411}
3412
3413status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3414{
3415 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3416
3417 // make sure we only have one patch per source.
3418 disconnectAudioSource(sourceDesc);
3419
3420 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003421 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003422 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3423
3424 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3425 sp<DeviceDescriptor> sinkDeviceDesc =
3426 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3427
3428 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3429 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3430
3431 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3432 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003433 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003434 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3435 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3436 // create patch between src device and output device
3437 // create Hwoutput and add to mHwOutputs
3438 } else {
3439 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3440 audio_io_handle_t output =
3441 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3442 if (output == AUDIO_IO_HANDLE_NONE) {
3443 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3444 return INVALID_OPERATION;
3445 }
3446 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3447 if (outputDesc->isDuplicated()) {
3448 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3449 return INVALID_OPERATION;
3450 }
Eric Laurent733ce942017-12-07 12:18:25 -08003451 status_t status = outputDesc->start();
3452 if (status != NO_ERROR) {
3453 return status;
3454 }
3455
Eric Laurentd60560a2015-04-10 11:31:20 -07003456 // create a special patch with no sink and two sources:
3457 // - the second source indicates to PatchPanel through which output mix this patch should
3458 // be connected as well as the stream type for volume control
3459 // - the sink is defined by whatever output device is currently selected for the output
3460 // though which this patch is routed.
3461 patch->num_sinks = 0;
3462 patch->num_sources = 2;
3463 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3464 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3465 patch->sources[1].ext.mix.usecase.stream = stream;
Eric Laurent733ce942017-12-07 12:18:25 -08003466 status = mpClientInterface->createAudioPatch(patch,
Eric Laurentd60560a2015-04-10 11:31:20 -07003467 &afPatchHandle,
3468 0);
3469 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3470 status, afPatchHandle);
3471 if (status != NO_ERROR) {
3472 ALOGW("%s patch panel could not connect device patch, error %d",
3473 __FUNCTION__, status);
3474 return INVALID_OPERATION;
3475 }
3476 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003477 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003478
3479 if (status != NO_ERROR) {
3480 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3481 return status;
3482 }
3483 sourceDesc->mSwOutput = outputDesc;
3484 if (delayMs != 0) {
3485 usleep(delayMs * 1000);
3486 }
3487 }
3488
3489 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3490 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3491
3492 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003493}
3494
Glenn Kasten559d4392016-03-29 13:42:57 -07003495status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003496{
Eric Laurentd60560a2015-04-10 11:31:20 -07003497 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3498 ALOGV("%s handle %d", __FUNCTION__, handle);
3499 if (sourceDesc == 0) {
3500 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3501 return BAD_VALUE;
3502 }
3503 status_t status = disconnectAudioSource(sourceDesc);
3504
3505 mAudioSources.removeItem(handle);
3506 return status;
3507}
3508
Andy Hung2ddee192015-12-18 17:34:44 -08003509status_t AudioPolicyManager::setMasterMono(bool mono)
3510{
3511 if (mMasterMono == mono) {
3512 return NO_ERROR;
3513 }
3514 mMasterMono = mono;
3515 // if enabling mono we close all offloaded devices, which will invalidate the
3516 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3517 // for recreating the new AudioTrack as non-offloaded PCM.
3518 //
3519 // If disabling mono, we leave all tracks as is: we don't know which clients
3520 // and tracks are able to be recreated as offloaded. The next "song" should
3521 // play back offloaded.
3522 if (mMasterMono) {
3523 Vector<audio_io_handle_t> offloaded;
3524 for (size_t i = 0; i < mOutputs.size(); ++i) {
3525 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3526 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3527 offloaded.push(desc->mIoHandle);
3528 }
3529 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003530 for (const auto& handle : offloaded) {
3531 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003532 }
3533 }
3534 // update master mono for all remaining outputs
3535 for (size_t i = 0; i < mOutputs.size(); ++i) {
3536 updateMono(mOutputs.keyAt(i));
3537 }
3538 return NO_ERROR;
3539}
3540
3541status_t AudioPolicyManager::getMasterMono(bool *mono)
3542{
3543 *mono = mMasterMono;
3544 return NO_ERROR;
3545}
3546
Eric Laurentac9cef52017-06-09 15:46:26 -07003547float AudioPolicyManager::getStreamVolumeDB(
3548 audio_stream_type_t stream, int index, audio_devices_t device)
3549{
3550 return computeVolume(stream, index, device);
3551}
3552
jiabin81772902018-04-02 17:52:27 -07003553status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3554 FormatVector& formats) {
3555 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3556 return BAD_VALUE;
3557 }
3558 String8 reply;
3559 reply = mpClientInterface->getParameters(
3560 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3561 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3562 AudioParameter repliedParameters(reply);
3563 if (repliedParameters.get(
3564 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3565 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3566 return BAD_VALUE;
3567 }
3568 for (auto format : formatsFromString(reply.string())) {
3569 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3570 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3571 if (format == AAC_FORMATS[i]) {
3572 format = AUDIO_FORMAT_AAC_LC;
3573 break;
3574 }
3575 }
3576 bool exist = false;
3577 for (size_t i = 0; i < formats.size(); i++) {
3578 if (format == formats[i]) {
3579 exist = true;
3580 break;
3581 }
3582 }
3583 bool isSurroundFormat = false;
3584 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3585 if (SURROUND_FORMATS[i] == format) {
3586 isSurroundFormat = true;
3587 break;
3588 }
3589 }
3590 if (!exist && isSurroundFormat) {
3591 formats.add(format);
3592 }
3593 }
3594 return NO_ERROR;
3595}
3596
3597status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3598 audio_format_t *surroundFormats,
3599 bool *surroundFormatsEnabled,
3600 bool reported)
3601{
3602 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3603 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3604 return BAD_VALUE;
3605 }
3606 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3607 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3608
3609 // Only return value if there is HDMI output.
3610 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3611 return INVALID_OPERATION;
3612 }
3613
3614 size_t formatsWritten = 0;
3615 size_t formatsMax = *numSurroundFormats;
3616 *numSurroundFormats = 0;
3617 FormatVector formats;
3618 if (reported) {
3619 // Only get surround formats which are reported by device.
3620 // First list already open outputs that can be routed to this device
3621 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3622 SortedVector<audio_io_handle_t> outputs;
3623 bool reportedFormatFound = false;
3624 status_t status;
3625 sp<SwAudioOutputDescriptor> desc;
3626 for (size_t i = 0; i < mOutputs.size(); i++) {
3627 desc = mOutputs.valueAt(i);
3628 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3629 outputs.add(mOutputs.keyAt(i));
3630 }
3631 }
3632 // Open an output to query dynamic parameters.
3633 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3634 AUDIO_DEVICE_OUT_HDMI);
3635 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3636 String8 address = hdmiOutputDevices[i]->mAddress;
3637 for (const auto& hwModule : mHwModules) {
3638 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3639 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3640 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3641 profile->supportDeviceAddress(address)) {
3642 size_t j;
3643 for (j = 0; j < outputs.size(); j++) {
3644 desc = mOutputs.valueFor(outputs.itemAt(j));
3645 if (!desc->isDuplicated() && desc->mProfile == profile) {
3646 break;
3647 }
3648 }
3649 if (j != outputs.size()) {
3650 status = getSupportedFormats(outputs.itemAt(j), formats);
3651 reportedFormatFound |= (status == NO_ERROR);
3652 continue;
3653 }
3654
3655 if (!profile->canOpenNewIo()) {
3656 ALOGW("Max Output number %u already opened for this profile %s",
3657 profile->maxOpenCount, profile->getTagName().c_str());
3658 continue;
3659 }
3660
3661 ALOGV("opening output for device %08x with params %s profile %p name %s",
3662 device, address.string(), profile.get(), profile->getName().string());
3663 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3664 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3665 status_t status = desc->open(nullptr, device, address,
3666 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3667 &output);
3668
3669 if (status == NO_ERROR) {
3670 status = getSupportedFormats(output, formats);
3671 reportedFormatFound |= (status == NO_ERROR);
3672 desc->close();
3673 output = AUDIO_IO_HANDLE_NONE;
3674 }
3675 }
3676 }
3677 }
3678 }
3679
3680 if (!reportedFormatFound) {
3681 return UNKNOWN_ERROR;
3682 }
3683 } else {
3684 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3685 formats.add(SURROUND_FORMATS[i]);
3686 }
3687 }
3688 for (size_t i = 0; i < formats.size(); i++) {
3689 if (formatsWritten < formatsMax) {
3690 surroundFormats[formatsWritten] = formats[i];
3691 bool formatEnabled = false;
3692 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3693 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3694 formatEnabled =
3695 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3696 break;
3697 }
3698 } else {
3699 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3700 }
3701 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3702 }
3703 (*numSurroundFormats)++;
3704 }
3705 return NO_ERROR;
3706}
3707
3708status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3709{
3710 // Check if audio format is a surround formats.
3711 bool isSurroundFormat = false;
3712 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3713 if (audioFormat == SURROUND_FORMATS[i]) {
3714 isSurroundFormat = true;
3715 break;
3716 }
3717 }
3718 if (!isSurroundFormat) {
3719 return BAD_VALUE;
3720 }
3721
3722 // Should only be called when MANUAL.
3723 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3724 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3725 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3726 return INVALID_OPERATION;
3727 }
3728
3729 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3730 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3731 return NO_ERROR;
3732 }
3733
3734 // The operation is valid only when there is HDMI output available.
3735 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3736 return INVALID_OPERATION;
3737 }
3738
3739 if (enabled) {
3740 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3741 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3742 mSurroundFormats.insert(AAC_FORMATS[i]);
3743 }
3744 } else {
3745 mSurroundFormats.insert(audioFormat);
3746 }
3747 } else {
3748 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3749 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3750 mSurroundFormats.erase(AAC_FORMATS[i]);
3751 }
3752 } else {
3753 mSurroundFormats.erase(audioFormat);
3754 }
3755 }
3756
3757 sp<SwAudioOutputDescriptor> outputDesc;
3758 bool profileUpdated = false;
3759 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3760 AUDIO_DEVICE_OUT_HDMI);
3761 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3762 // Simulate reconnection to update enabled surround sound formats.
3763 String8 address = hdmiOutputDevices[i]->mAddress;
3764 String8 name = hdmiOutputDevices[i]->getName();
3765 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3766 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3767 address.c_str(),
3768 name.c_str());
3769 if (status != NO_ERROR) {
3770 continue;
3771 }
3772 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3774 address.c_str(),
3775 name.c_str());
3776 profileUpdated |= (status == NO_ERROR);
3777 }
3778 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3779 AUDIO_DEVICE_IN_HDMI);
3780 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3781 // Simulate reconnection to update enabled surround sound formats.
3782 String8 address = hdmiInputDevices[i]->mAddress;
3783 String8 name = hdmiInputDevices[i]->getName();
3784 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3785 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3786 address.c_str(),
3787 name.c_str());
3788 if (status != NO_ERROR) {
3789 continue;
3790 }
3791 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3792 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3793 address.c_str(),
3794 name.c_str());
3795 profileUpdated |= (status == NO_ERROR);
3796 }
3797
3798 // Undo the surround formats change due to no audio profiles updated.
3799 if (!profileUpdated) {
3800 if (enabled) {
3801 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3802 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3803 mSurroundFormats.erase(AAC_FORMATS[i]);
3804 }
3805 } else {
3806 mSurroundFormats.erase(audioFormat);
3807 }
3808 } else {
3809 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3810 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3811 mSurroundFormats.insert(AAC_FORMATS[i]);
3812 }
3813 } else {
3814 mSurroundFormats.insert(audioFormat);
3815 }
3816 }
3817 }
3818
3819 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3820}
3821
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003822void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3823{
3824 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3825
3826 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3827 for (size_t i = 0; i < activeInputs.size(); i++) {
3828 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3829 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3830 for (size_t j = 0; j < activeSessions.size(); j++) {
3831 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3832 if (activeSession->uid() == uid) {
3833 activeSession->setSilenced(silenced);
3834 }
3835 }
3836 }
3837}
3838
Eric Laurentd60560a2015-04-10 11:31:20 -07003839status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3840{
3841 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3842
3843 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3844 if (patchDesc == 0) {
3845 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3846 sourceDesc->mPatchDesc->mHandle);
3847 return BAD_VALUE;
3848 }
3849 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3850
Eric Laurent28d09f02016-03-08 10:43:05 -08003851 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003852 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3853 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003854 status_t status = stopSource(swOutputDesc, stream, false);
3855 if (status == NO_ERROR) {
3856 swOutputDesc->stop();
3857 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003858 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3859 } else {
3860 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3861 if (hwOutputDesc != 0) {
3862 // release patch between src device and output device
3863 // close Hwoutput and remove from mHwOutputs
3864 } else {
3865 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3866 }
3867 }
3868 return NO_ERROR;
3869}
3870
3871sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3872 audio_io_handle_t output, routing_strategy strategy)
3873{
3874 sp<AudioSourceDescriptor> source;
3875 for (size_t i = 0; i < mAudioSources.size(); i++) {
3876 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3877 routing_strategy sourceStrategy =
3878 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3879 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3880 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3881 source = sourceDesc;
3882 break;
3883 }
3884 }
3885 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003886}
3887
Eric Laurente552edb2014-03-10 17:42:56 -07003888// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003889// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003890// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003891uint32_t AudioPolicyManager::nextAudioPortGeneration()
3892{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003893 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003894}
3895
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003896#ifdef USE_XML_AUDIO_POLICY_CONF
3897// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3898static const char *kConfigLocationList[] =
3899 {"/odm/etc", "/vendor/etc", "/system/etc"};
3900static const int kConfigLocationListSize =
3901 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3902
3903static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3904 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003905 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003906 status_t ret;
3907
Petri Gyntherf497f292018-04-17 18:46:10 -07003908 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3909 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3910 // A2DP offload supported but disabled: try to use special XML file
3911 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3912 }
3913 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3914
3915 for (const char* fileName : fileNames) {
3916 for (int i = 0; i < kConfigLocationListSize; i++) {
3917 PolicySerializer serializer;
3918 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3919 "%s/%s", kConfigLocationList[i], fileName);
3920 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3921 if (ret == NO_ERROR) {
3922 return ret;
3923 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003924 }
3925 }
3926 return ret;
3927}
3928#endif
3929
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003930AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3931 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003932 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003933 mUidCached(getuid()),
3934 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003935 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003937#ifdef USE_XML_AUDIO_POLICY_CONF
3938 mVolumeCurves(new VolumeCurvesCollection()),
3939 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003940 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003941#else
3942 mVolumeCurves(new StreamDescriptorCollection()),
3943 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3944 mDefaultOutputDevice),
3945#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003946 mAudioPortGeneration(1),
3947 mBeaconMuteRefCount(0),
3948 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003949 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003950 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003951 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003952 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3953 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003954{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003955}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003956
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003957AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3958 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3959{
3960 loadConfig();
3961 initialize();
3962}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003963
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003964void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003965#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003966 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003967#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003968 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3969 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003970#endif
3971 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003972 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003973 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003974}
3975
3976status_t AudioPolicyManager::initialize() {
3977 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003978
3979 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003980 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3981 if (!engineInstance) {
3982 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003983 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003984 }
3985 // Retrieve the Policy Manager Interface
3986 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3987 if (mEngine == NULL) {
3988 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003989 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003990 }
3991 mEngine->setObserver(this);
3992 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003993 if (status != NO_ERROR) {
3994 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3995 return status;
3996 }
François Gaffie2110e042015-03-24 08:41:51 +01003997
Eric Laurent3a4311c2014-03-17 12:00:47 -07003998 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003999 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07004000 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
4001 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08004002 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004003 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08004004 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4005 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004006 continue;
4007 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08004008 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07004009 // open all output streams needed to access attached devices
4010 // except for direct output streams that are only opened when they are actually
4011 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07004012 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004013 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004014 if (!outProfile->canOpenNewIo()) {
4015 ALOGE("Invalid Output profile max open count %u for profile %s",
4016 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4017 continue;
4018 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004019 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004020 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 continue;
4022 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004023 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004024 mTtsOutputAvailable = true;
4025 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004027 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004028 continue;
4029 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004030 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004031 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4032 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004033 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004034 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004035 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004036 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004037 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004038 if ((profileType & outputDeviceTypes) == 0) {
4039 continue;
4040 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004041 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4042 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004043 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4044 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
4045 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4046 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004047 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004048 status_t status = outputDesc->open(nullptr, profileType, address,
4049 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004050
4051 if (status != NO_ERROR) {
4052 ALOGW("Cannot open output stream for device %08x on hw module %s",
4053 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004054 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004056 for (const auto& dev : supportedDevices) {
4057 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004058 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004059 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004060 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004061 }
4062 }
4063 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004064 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004065 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004066 }
4067 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004068 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004069 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004070 true,
4071 0,
4072 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004073 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004074 }
Eric Laurente552edb2014-03-10 17:42:56 -07004075 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 // open input streams needed to access attached devices to validate
4077 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004078 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004079 if (!inProfile->canOpenNewIo()) {
4080 ALOGE("Invalid Input profile max open count %u for profile %s",
4081 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4082 continue;
4083 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004084 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004085 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 continue;
4087 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004088 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004089 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004090 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4091
Eric Laurentd78f1532014-09-16 16:38:20 -07004092 if ((profileType & inputDeviceTypes) == 0) {
4093 continue;
4094 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004095 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004096 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004097
Eric Laurent53b810e2017-12-10 17:25:10 -08004098 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4099 // the inputs vector must be of size >= 1, but we don't want to crash here
4100 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4101 : String8("");
4102 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4103 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4104
Eric Laurentd78f1532014-09-16 16:38:20 -07004105 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004106 status_t status = inputDesc->open(nullptr,
4107 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004108 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004109 AUDIO_SOURCE_MIC,
4110 AUDIO_INPUT_FLAG_NONE,
4111 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004112
4113 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004114 for (const auto& dev : inProfile->getSupportedDevices()) {
4115 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004116 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004117 if (index >= 0) {
4118 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4119 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004120 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004121 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004122 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004123 }
4124 }
Eric Laurentfe231122017-11-17 17:48:06 -08004125 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004126 } else {
4127 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004128 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004129 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004130 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004131 }
4132 }
4133 // make sure all attached devices have been allocated a unique ID
4134 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004135 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004136 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004137 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4138 continue;
4139 }
François Gaffie2110e042015-03-24 08:41:51 +01004140 // The device is now validated and can be appended to the available devices of the engine
4141 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4142 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004143 i++;
4144 }
4145 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004146 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004147 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004148 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4149 continue;
4150 }
François Gaffie2110e042015-03-24 08:41:51 +01004151 // The device is now validated and can be appended to the available devices of the engine
4152 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4153 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004154 i++;
4155 }
4156 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004157 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004158 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004159 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004160 }
jiabin9ff780e2018-03-19 18:19:52 -07004161 // If microphones address is empty, set it according to device type
4162 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4163 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4164 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4165 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4166 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4167 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4168 }
4169 }
4170 }
Eric Laurente552edb2014-03-10 17:42:56 -07004171
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004172 if (mPrimaryOutput == 0) {
4173 ALOGE("Failed to open primary output");
4174 status = NO_INIT;
4175 }
Eric Laurente552edb2014-03-10 17:42:56 -07004176
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004177 // Silence ALOGV statements
4178 property_set("log.tag." LOG_TAG, "D");
4179
Eric Laurente552edb2014-03-10 17:42:56 -07004180 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004181 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004182}
4183
Eric Laurente0720872014-03-11 09:30:41 -07004184AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004185{
Eric Laurente552edb2014-03-10 17:42:56 -07004186 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004187 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004188 }
4189 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004190 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004192 mAvailableOutputDevices.clear();
4193 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004194 mOutputs.clear();
4195 mInputs.clear();
4196 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004197 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004198 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004199}
4200
Eric Laurente0720872014-03-11 09:30:41 -07004201status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004202{
Eric Laurent87ffa392015-05-22 10:32:38 -07004203 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004204}
4205
Eric Laurente552edb2014-03-10 17:42:56 -07004206// ---
4207
Eric Laurent98e38192018-02-15 18:31:53 -08004208void AudioPolicyManager::addOutput(audio_io_handle_t output,
4209 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004210{
Eric Laurent1c333e22014-05-20 10:48:17 -07004211 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004212 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004213 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004214 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004216}
4217
François Gaffie53615e22015-03-19 09:24:12 +01004218void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4219{
4220 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004221 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004222}
4223
Eric Laurent98e38192018-02-15 18:31:53 -08004224void AudioPolicyManager::addInput(audio_io_handle_t input,
4225 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004226{
Eric Laurent1c333e22014-05-20 10:48:17 -07004227 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004229}
Eric Laurente552edb2014-03-10 17:42:56 -07004230
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004231void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004232 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004233 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004234 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004235 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004236 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004237 if (devDesc != 0) {
4238 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4239 desc->mIoHandle, address.string());
4240 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004241 }
4242}
4243
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004244status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004245 audio_policy_dev_state_t state,
4246 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004247 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004248{
François Gaffie53615e22015-03-19 09:24:12 +01004249 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004250 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004251
4252 if (audio_device_is_digital(device)) {
4253 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004254 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004255 }
Eric Laurente552edb2014-03-10 17:42:56 -07004256
Eric Laurent3b73df72014-03-11 09:06:29 -07004257 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004258 // first list already open outputs that can be routed to this device
4259 for (size_t i = 0; i < mOutputs.size(); i++) {
4260 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004261 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004262 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004263 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4264 outputs.add(mOutputs.keyAt(i));
4265 } else {
4266 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004267 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004268 }
Eric Laurente552edb2014-03-10 17:42:56 -07004269 }
4270 }
4271 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004272 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004273 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004274 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4275 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004276 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004277 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004278 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004279 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004280 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4281 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004282 }
Eric Laurente552edb2014-03-10 17:42:56 -07004283 }
4284 }
4285 }
4286
Eric Laurent7b279bb2015-12-14 10:18:23 -08004287 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004288
Eric Laurente552edb2014-03-10 17:42:56 -07004289 if (profiles.isEmpty() && outputs.isEmpty()) {
4290 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4291 return BAD_VALUE;
4292 }
4293
4294 // open outputs for matching profiles if needed. Direct outputs are also opened to
4295 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4296 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004297 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004298
4299 // nothing to do if one output is already opened for this profile
4300 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004301 for (j = 0; j < outputs.size(); j++) {
4302 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004303 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004304 // matching profile: save the sample rates, format and channel masks supported
4305 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004306 if (audio_device_is_digital(device)) {
4307 devDesc->importAudioPort(profile);
4308 }
Eric Laurente552edb2014-03-10 17:42:56 -07004309 break;
4310 }
4311 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004312 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004313 continue;
4314 }
4315
Eric Laurent3974e3b2017-12-07 17:58:43 -08004316 if (!profile->canOpenNewIo()) {
4317 ALOGW("Max Output number %u already opened for this profile %s",
4318 profile->maxOpenCount, profile->getTagName().c_str());
4319 continue;
4320 }
4321
Eric Laurent83efe1c2017-07-09 16:51:08 -07004322 ALOGV("opening output for device %08x with params %s profile %p name %s",
4323 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004324 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004325 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004326 status_t status = desc->open(nullptr, device, address,
4327 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004328
Eric Laurentfe231122017-11-17 17:48:06 -08004329 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004330 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004331 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004332 char *param = audio_device_address_to_parameter(device, address);
4333 mpClientInterface->setParameters(output, String8(param));
4334 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004335 }
Phil Burk00eeb322016-03-31 12:41:00 -07004336 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004337 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004338 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004339 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004340 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004341 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004342 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004343 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004344 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4345 profile->pickAudioProfile(
4346 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004347 config.offload_info.sample_rate = config.sample_rate;
4348 config.offload_info.channel_mask = config.channel_mask;
4349 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004350
4351 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4352 AUDIO_OUTPUT_FLAG_NONE, &output);
4353 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004354 output = AUDIO_IO_HANDLE_NONE;
4355 }
Eric Laurentd4692962014-05-05 18:13:44 -07004356 }
4357
Eric Laurentcf2c0212014-07-25 16:20:43 -07004358 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004360 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004361 sp<AudioPolicyMix> policyMix;
4362 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004363 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4364 address.string());
4365 }
François Gaffie036e1e92015-03-19 10:16:24 +01004366 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004367 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004368
Eric Laurent87ffa392015-05-22 10:32:38 -07004369 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4370 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004371 // no duplicated output for direct outputs and
4372 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004373 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004374
Eric Laurentd4692962014-05-05 18:13:44 -07004375 //TODO: configure audio effect output stage here
4376
4377 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004378 sp<SwAudioOutputDescriptor> dupOutputDesc =
4379 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4380 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4381 &duplicatedOutput);
4382 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004383 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004384 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004385 } else {
4386 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004387 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004388 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004389 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004390 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004391 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004392 }
Eric Laurente552edb2014-03-10 17:42:56 -07004393 }
4394 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004395 } else {
4396 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004397 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004398 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004399 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004400 profiles.removeAt(profile_index);
4401 profile_index--;
4402 } else {
4403 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004404 // Load digital format info only for digital devices
4405 if (audio_device_is_digital(device)) {
4406 devDesc->importAudioPort(profile);
4407 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004408
François Gaffie53615e22015-03-19 09:24:12 +01004409 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004410 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4411 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004412 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004413 NULL/*patch handle*/, address.string());
4414 }
Eric Laurente552edb2014-03-10 17:42:56 -07004415 ALOGV("checkOutputsForDevice(): adding output %d", output);
4416 }
4417 }
4418
4419 if (profiles.isEmpty()) {
4420 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4421 return BAD_VALUE;
4422 }
Eric Laurentd4692962014-05-05 18:13:44 -07004423 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004424 // check if one opened output is not needed any more after disconnecting one device
4425 for (size_t i = 0; i < mOutputs.size(); i++) {
4426 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004427 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004428 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004429 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004430 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004431 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004432 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004433 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4434 mOutputs.keyAt(i));
4435 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004436 }
Eric Laurente552edb2014-03-10 17:42:56 -07004437 }
4438 }
Eric Laurentd4692962014-05-05 18:13:44 -07004439 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004440 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004441 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4442 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004443 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004444 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004445 "clearing direct output profile %zu on module %s",
4446 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004447 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004448 }
4449 }
4450 }
4451 }
4452 return NO_ERROR;
4453}
4454
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004455status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004456 audio_policy_dev_state_t state,
4457 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004458 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004459{
Paul McLean9080a4c2015-06-18 08:24:02 -07004460 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004461 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004462
4463 if (audio_device_is_digital(device)) {
4464 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004465 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004466 }
4467
Eric Laurentd4692962014-05-05 18:13:44 -07004468 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4469 // first list already open inputs that can be routed to this device
4470 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4471 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004472 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004473 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4474 inputs.add(mInputs.keyAt(input_index));
4475 }
4476 }
4477
4478 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004479 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004480 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004481 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004482 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004483 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004484 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004485
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004486 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004487 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004488 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004489 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004490 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4491 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004492 }
Eric Laurentd4692962014-05-05 18:13:44 -07004493 }
4494 }
4495 }
4496
4497 if (profiles.isEmpty() && inputs.isEmpty()) {
4498 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4499 return BAD_VALUE;
4500 }
4501
4502 // open inputs for matching profiles if needed. Direct inputs are also opened to
4503 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4504 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4505
Eric Laurent1c333e22014-05-20 10:48:17 -07004506 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004507
Eric Laurentd4692962014-05-05 18:13:44 -07004508 // nothing to do if one input is already opened for this profile
4509 size_t input_index;
4510 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4511 desc = mInputs.valueAt(input_index);
4512 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004513 if (audio_device_is_digital(device)) {
4514 devDesc->importAudioPort(profile);
4515 }
Eric Laurentd4692962014-05-05 18:13:44 -07004516 break;
4517 }
4518 }
4519 if (input_index != mInputs.size()) {
4520 continue;
4521 }
4522
Eric Laurent3974e3b2017-12-07 17:58:43 -08004523 if (!profile->canOpenNewIo()) {
4524 ALOGW("Max Input number %u already opened for this profile %s",
4525 profile->maxOpenCount, profile->getTagName().c_str());
4526 continue;
4527 }
4528
Eric Laurentfe231122017-11-17 17:48:06 -08004529 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004530 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004531 status_t status = desc->open(nullptr,
4532 device,
4533 address,
4534 AUDIO_SOURCE_MIC,
4535 AUDIO_INPUT_FLAG_NONE,
4536 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004537
Eric Laurentcf2c0212014-07-25 16:20:43 -07004538 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004539 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004540 char *param = audio_device_address_to_parameter(device, address);
4541 mpClientInterface->setParameters(input, String8(param));
4542 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004543 }
Phil Burk00eeb322016-03-31 12:41:00 -07004544 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004545 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004546 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004547 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004548 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004549 }
4550
4551 if (input != 0) {
4552 addInput(input, desc);
4553 }
4554 } // endif input != 0
4555
Eric Laurentcf2c0212014-07-25 16:20:43 -07004556 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004557 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004558 profiles.removeAt(profile_index);
4559 profile_index--;
4560 } else {
4561 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004562 if (audio_device_is_digital(device)) {
4563 devDesc->importAudioPort(profile);
4564 }
Eric Laurentd4692962014-05-05 18:13:44 -07004565 ALOGV("checkInputsForDevice(): adding input %d", input);
4566 }
4567 } // end scan profiles
4568
4569 if (profiles.isEmpty()) {
4570 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4571 return BAD_VALUE;
4572 }
4573 } else {
4574 // Disconnect
4575 // check if one opened input is not needed any more after disconnecting one device
4576 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4577 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004578 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004579 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4580 mInputs.keyAt(input_index));
4581 inputs.add(mInputs.keyAt(input_index));
4582 }
4583 }
4584 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004585 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004586 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004587 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004588 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004589 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004590 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004591 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4592 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004593 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004594 }
4595 }
4596 }
4597 } // end disconnect
4598
4599 return NO_ERROR;
4600}
4601
4602
Eric Laurente0720872014-03-11 09:30:41 -07004603void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004604{
4605 ALOGV("closeOutput(%d)", output);
4606
Eric Laurentc75307b2015-03-17 15:29:32 -07004607 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004608 if (outputDesc == NULL) {
4609 ALOGW("closeOutput() unknown output %d", output);
4610 return;
4611 }
François Gaffie036e1e92015-03-19 10:16:24 +01004612 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004613
Eric Laurente552edb2014-03-10 17:42:56 -07004614 // look for duplicated outputs connected to the output being removed.
4615 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004616 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004617 if (dupOutputDesc->isDuplicated() &&
4618 (dupOutputDesc->mOutput1 == outputDesc ||
4619 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004620 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if (dupOutputDesc->mOutput1 == outputDesc) {
4622 outputDesc2 = dupOutputDesc->mOutput2;
4623 } else {
4624 outputDesc2 = dupOutputDesc->mOutput1;
4625 }
4626 // As all active tracks on duplicated output will be deleted,
4627 // and as they were also referenced on the other output, the reference
4628 // count for their stream type must be adjusted accordingly on
4629 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004630 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004631 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004632 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004633 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004634 }
Eric Laurent733ce942017-12-07 12:18:25 -08004635 // stop() will be a no op if the output is still active but is needed in case all
4636 // active streams refcounts where cleared above
4637 if (wasActive) {
4638 outputDesc2->stop();
4639 }
Eric Laurente552edb2014-03-10 17:42:56 -07004640 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4641 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4642
4643 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004644 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004645 }
4646 }
4647
Eric Laurent05b90f82014-08-27 15:32:29 -07004648 nextAudioPortGeneration();
4649
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004650 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004651 if (index >= 0) {
4652 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004653 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004654 mAudioPatches.removeItemsAt(index);
4655 mpClientInterface->onAudioPatchListUpdate();
4656 }
4657
Eric Laurentfe231122017-11-17 17:48:06 -08004658 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004659
François Gaffie53615e22015-03-19 09:24:12 +01004660 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004661 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004662}
4663
4664void AudioPolicyManager::closeInput(audio_io_handle_t input)
4665{
4666 ALOGV("closeInput(%d)", input);
4667
4668 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4669 if (inputDesc == NULL) {
4670 ALOGW("closeInput() unknown input %d", input);
4671 return;
4672 }
4673
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004675
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004676 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004677 if (index >= 0) {
4678 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004679 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004680 mAudioPatches.removeItemsAt(index);
4681 mpClientInterface->onAudioPatchListUpdate();
4682 }
4683
Eric Laurentfe231122017-11-17 17:48:06 -08004684 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004685 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004686}
4687
Eric Laurentc75307b2015-03-17 15:29:32 -07004688SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4689 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004690 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004691{
4692 SortedVector<audio_io_handle_t> outputs;
4693
4694 ALOGVV("getOutputsForDevice() device %04x", device);
4695 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004696 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004697 i, openOutputs.valueAt(i)->isDuplicated(),
4698 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004699 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4700 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4701 outputs.add(openOutputs.keyAt(i));
4702 }
4703 }
4704 return outputs;
4705}
4706
Eric Laurente0720872014-03-11 09:30:41 -07004707bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004708 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004709{
4710 if (outputs1.size() != outputs2.size()) {
4711 return false;
4712 }
4713 for (size_t i = 0; i < outputs1.size(); i++) {
4714 if (outputs1[i] != outputs2[i]) {
4715 return false;
4716 }
4717 }
4718 return true;
4719}
4720
Eric Laurente0720872014-03-11 09:30:41 -07004721void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004722{
4723 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4724 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4725 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4726 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4727
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004728 // also take into account external policy-related changes: add all outputs which are
4729 // associated with policies in the "before" and "after" output vectors
4730 ALOGVV("checkOutputForStrategy(): policy related outputs");
4731 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004732 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004733 if (desc != 0 && desc->mPolicyMix != NULL) {
4734 srcOutputs.add(desc->mIoHandle);
4735 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4736 }
4737 }
4738 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004739 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004740 if (desc != 0 && desc->mPolicyMix != NULL) {
4741 dstOutputs.add(desc->mIoHandle);
4742 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4743 }
4744 }
4745
Eric Laurente552edb2014-03-10 17:42:56 -07004746 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004747 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4748 // audio from invalidated tracks will be rendered when unmuting
4749 uint32_t maxLatency = 0;
4750 for (audio_io_handle_t srcOut : srcOutputs) {
4751 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4752 if (desc != 0 && maxLatency < desc->latency()) {
4753 maxLatency = desc->latency();
4754 }
4755 }
Eric Laurente552edb2014-03-10 17:42:56 -07004756 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4757 strategy, srcOutputs[0], dstOutputs[0]);
4758 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004759 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004760 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4761 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004762 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004763 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004764 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004765 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004766 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004767 if (source != 0){
4768 connectAudioSource(source);
4769 }
Eric Laurente552edb2014-03-10 17:42:56 -07004770 }
4771
4772 // Move effects associated to this strategy from previous output to new output
4773 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004774 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004775 }
4776 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004777 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004778 if (getStrategy((audio_stream_type_t)i) == strategy) {
4779 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004780 }
4781 }
4782 }
4783}
4784
Eric Laurente0720872014-03-11 09:30:41 -07004785void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004786{
François Gaffie2110e042015-03-24 08:41:51 +01004787 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004788 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004789 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004790 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004791 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004792 checkOutputForStrategy(STRATEGY_SONIFICATION);
4793 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004794 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004795 checkOutputForStrategy(STRATEGY_MEDIA);
4796 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004797 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004798}
4799
Eric Laurente0720872014-03-11 09:30:41 -07004800void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004801{
François Gaffie53615e22015-03-19 09:24:12 +01004802 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004803 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004804 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004805 return;
4806 }
4807
Eric Laurent3a4311c2014-03-17 12:00:47 -07004808 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004809 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4810 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4811 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004812
4813 // if suspended, restore A2DP output if:
4814 // ((SCO device is NOT connected) ||
4815 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4816 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004817 //
Eric Laurentf732e072016-08-03 19:30:28 -07004818 // if not suspended, suspend A2DP output if:
4819 // (SCO device is connected) &&
4820 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4821 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004822 //
4823 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004824 if (!isScoConnected ||
4825 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4826 AUDIO_POLICY_FORCE_BT_SCO) &&
4827 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4828 AUDIO_POLICY_FORCE_BT_SCO) &&
4829 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004830 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004831
4832 mpClientInterface->restoreOutput(a2dpOutput);
4833 mA2dpSuspended = false;
4834 }
4835 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004836 if (isScoConnected &&
4837 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4838 AUDIO_POLICY_FORCE_BT_SCO) ||
4839 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4840 AUDIO_POLICY_FORCE_BT_SCO) ||
4841 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004842 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004843
4844 mpClientInterface->suspendOutput(a2dpOutput);
4845 mA2dpSuspended = true;
4846 }
4847 }
4848}
4849
Eric Laurentc75307b2015-03-17 15:29:32 -07004850audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4851 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004852{
4853 audio_devices_t device = AUDIO_DEVICE_NONE;
4854
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004855 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 if (index >= 0) {
4857 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4858 if (patchDesc->mUid != mUidCached) {
4859 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004860 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004861 return outputDesc->device();
4862 }
4863 }
4864
Eric Laurentf3a5a602018-05-22 18:42:55 -07004865 // Check if an explicit routing request exists for an active stream on this output and
4866 // use it in priority before any other rule
4867 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4868 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4869 audio_devices_t forcedDevice =
4870 mOutputRoutes.getActiveDeviceForStream(
4871 (audio_stream_type_t)stream, mAvailableOutputDevices);
4872
4873 if (forcedDevice != AUDIO_DEVICE_NONE) {
4874 return forcedDevice;
4875 }
4876 }
4877 }
4878
Eric Laurente552edb2014-03-10 17:42:56 -07004879 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004880 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004881 // use device for strategy enforced audible
4882 // 2: we are in call or the strategy phone is active on the output:
4883 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004884 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004885 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004886 // 4: the strategy for enforced audible is active but not enforced on the output:
4887 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004888 // 5: the strategy accessibility is active on the output:
4889 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004890 // 6: the strategy "respectful" sonification is active on the output:
4891 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004892 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004893 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004894 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004895 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004896 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004897 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004898
4899 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4900 // with a refined rule considering mutually exclusive devices (using same backend)
4901 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004902 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004903 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4905 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004906 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004907 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004908 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004909 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004910 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4911 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004912 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4913 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004914 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004915 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004916 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004917 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004918 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004920 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004921 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004922 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004923 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004924 }
4925
Eric Laurent1c333e22014-05-20 10:48:17 -07004926 ALOGV("getNewOutputDevice() selected device %x", device);
4927 return device;
4928}
4929
Eric Laurentfb66dd92016-01-28 18:32:03 -08004930audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004931{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004932 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004933
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004934 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 if (index >= 0) {
4936 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4937 if (patchDesc->mUid != mUidCached) {
4938 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004939 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 return inputDesc->mDevice;
4941 }
4942 }
4943
Eric Laurentdc95a252018-04-12 12:46:56 -07004944 // If we are not in call and no client is active on this input, this methods returns
4945 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004946 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004947 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4948 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4949 }
4950 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004951 device = getDeviceAndMixForInputSource(source);
4952 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004953
Eric Laurente552edb2014-03-10 17:42:56 -07004954 return device;
4955}
4956
Eric Laurent794fde22016-03-11 09:50:45 -08004957bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4958 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004959 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004960}
4961
Eric Laurente0720872014-03-11 09:30:41 -07004962uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004963 return (uint32_t)getStrategy(stream);
4964}
4965
Eric Laurente0720872014-03-11 09:30:41 -07004966audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004967 // By checking the range of stream before calling getStrategy, we avoid
4968 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4969 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004970 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 return AUDIO_DEVICE_NONE;
4972 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004973 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004974 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4975 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004976 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 }
Eric Laurent794fde22016-03-11 09:50:45 -08004978 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004979 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004980 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004981 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4982 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004983 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004984 curDevices |= outputDesc->device();
4985 }
4986 }
4987 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004988 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004989
4990 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4991 and doesn't really need to.*/
4992 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4993 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4994 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4995 }
Eric Laurente552edb2014-03-10 17:42:56 -07004996 return devices;
4997}
4998
François Gaffie2110e042015-03-24 08:41:51 +01004999routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
5000{
Eric Laurent223fd5c2014-11-11 13:43:36 -08005001 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01005002 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005003}
5004
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005005uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
5006 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005007 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5008 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
5009 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005010 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5011 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
5012 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005013 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01005014 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005015}
5016
Eric Laurente0720872014-03-11 09:30:41 -07005017void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005018 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005019 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005020 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5021 updateDevicesAndOutputs();
5022 break;
5023 default:
5024 break;
5025 }
5026}
5027
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005028uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005029
5030 // skip beacon mute management if a dedicated TTS output is available
5031 if (mTtsOutputAvailable) {
5032 return 0;
5033 }
5034
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005035 switch(event) {
5036 case STARTING_OUTPUT:
5037 mBeaconMuteRefCount++;
5038 break;
5039 case STOPPING_OUTPUT:
5040 if (mBeaconMuteRefCount > 0) {
5041 mBeaconMuteRefCount--;
5042 }
5043 break;
5044 case STARTING_BEACON:
5045 mBeaconPlayingRefCount++;
5046 break;
5047 case STOPPING_BEACON:
5048 if (mBeaconPlayingRefCount > 0) {
5049 mBeaconPlayingRefCount--;
5050 }
5051 break;
5052 }
5053
5054 if (mBeaconMuteRefCount > 0) {
5055 // any playback causes beacon to be muted
5056 return setBeaconMute(true);
5057 } else {
5058 // no other playback: unmute when beacon starts playing, mute when it stops
5059 return setBeaconMute(mBeaconPlayingRefCount == 0);
5060 }
5061}
5062
5063uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5064 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5065 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5066 // keep track of muted state to avoid repeating mute/unmute operations
5067 if (mBeaconMuted != mute) {
5068 // mute/unmute AUDIO_STREAM_TTS on all outputs
5069 ALOGV("\t muting %d", mute);
5070 uint32_t maxLatency = 0;
5071 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005072 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005073 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005074 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005075 0 /*delay*/, AUDIO_DEVICE_NONE);
5076 const uint32_t latency = desc->latency() * 2;
5077 if (latency > maxLatency) {
5078 maxLatency = latency;
5079 }
5080 }
5081 mBeaconMuted = mute;
5082 return maxLatency;
5083 }
5084 return 0;
5085}
5086
Eric Laurente0720872014-03-11 09:30:41 -07005087audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005088 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005089{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005090 // Check if an explicit routing request exists for a stream type corresponding to the
5091 // specified strategy and use it in priority over default routing rules.
5092 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5093 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5094 audio_devices_t forcedDevice =
5095 mOutputRoutes.getActiveDeviceForStream(
5096 (audio_stream_type_t)stream, mAvailableOutputDevices);
5097 if (forcedDevice != AUDIO_DEVICE_NONE) {
5098 return forcedDevice;
5099 }
Paul McLeanaa981192015-03-21 09:55:15 -07005100 }
5101 }
5102
Eric Laurente552edb2014-03-10 17:42:56 -07005103 if (fromCache) {
5104 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5105 strategy, mDeviceForStrategy[strategy]);
5106 return mDeviceForStrategy[strategy];
5107 }
François Gaffie2110e042015-03-24 08:41:51 +01005108 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005109}
5110
Eric Laurente0720872014-03-11 09:30:41 -07005111void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005112{
5113 for (int i = 0; i < NUM_STRATEGIES; i++) {
5114 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5115 }
5116 mPreviousOutputs = mOutputs;
5117}
5118
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005119uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005120 audio_devices_t prevDevice,
5121 uint32_t delayMs)
5122{
5123 // mute/unmute strategies using an incompatible device combination
5124 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5125 // if unmuting, unmute only after the specified delay
5126 if (outputDesc->isDuplicated()) {
5127 return 0;
5128 }
5129
5130 uint32_t muteWaitMs = 0;
5131 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005132 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005133
5134 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5135 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005136 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005137 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5138 bool doMute = false;
5139
5140 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5141 doMute = true;
5142 outputDesc->mStrategyMutedByDevice[i] = true;
5143 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5144 doMute = true;
5145 outputDesc->mStrategyMutedByDevice[i] = false;
5146 }
Eric Laurent99401132014-05-07 19:48:15 -07005147 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005148 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005149 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 // skip output if it does not share any device with current output
5151 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5152 == AUDIO_DEVICE_NONE) {
5153 continue;
5154 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005155 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005156 mute ? "muting" : "unmuting", i, curDevice);
5157 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005158 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005159 if (mute) {
5160 // FIXME: should not need to double latency if volume could be applied
5161 // immediately by the audioflinger mixer. We must account for the delay
5162 // between now and the next time the audioflinger thread for this output
5163 // will process a buffer (which corresponds to one buffer size,
5164 // usually 1/2 or 1/4 of the latency).
5165 if (muteWaitMs < desc->latency() * 2) {
5166 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005167 }
5168 }
5169 }
5170 }
5171 }
5172 }
5173
Eric Laurent99401132014-05-07 19:48:15 -07005174 // temporary mute output if device selection changes to avoid volume bursts due to
5175 // different per device volumes
5176 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005177 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5178 // temporary mute duration is conservatively set to 4 times the reported latency
5179 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5180 if (muteWaitMs < tempMuteWaitMs) {
5181 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005182 }
Eric Laurentdc462862016-07-19 12:29:53 -07005183
Eric Laurent99401132014-05-07 19:48:15 -07005184 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005185 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005186 // make sure that we do not start the temporary mute period too early in case of
5187 // delayed device change
5188 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005190 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005191 }
5192 }
5193 }
5194
Eric Laurente552edb2014-03-10 17:42:56 -07005195 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5196 if (muteWaitMs > delayMs) {
5197 muteWaitMs -= delayMs;
5198 usleep(muteWaitMs * 1000);
5199 return muteWaitMs;
5200 }
5201 return 0;
5202}
5203
Eric Laurentc75307b2015-03-17 15:29:32 -07005204uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005205 audio_devices_t device,
5206 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005208 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005209 const char *address,
5210 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005211{
Eric Laurentc75307b2015-03-17 15:29:32 -07005212 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005213 AudioParameter param;
5214 uint32_t muteWaitMs;
5215
5216 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005217 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5218 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5219 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5220 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005221 return muteWaitMs;
5222 }
5223 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5224 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005225 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005226 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005227 return 0;
5228 }
5229
5230 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005231 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005232
5233 audio_devices_t prevDevice = outputDesc->mDevice;
5234
Paul McLeanaa981192015-03-21 09:55:15 -07005235 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005236
5237 if (device != AUDIO_DEVICE_NONE) {
5238 outputDesc->mDevice = device;
5239 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005240
5241 // if the outputs are not materially active, there is no need to mute.
5242 if (requiresMuteCheck) {
5243 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5244 } else {
5245 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5246 muteWaitMs = 0;
5247 }
Eric Laurente552edb2014-03-10 17:42:56 -07005248
5249 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005250 // the requested device is AUDIO_DEVICE_NONE
5251 // OR the requested device is the same as current device
5252 // AND force is not specified
5253 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005254 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005255 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5256 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005257 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005258 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005259 return muteWaitMs;
5260 }
5261
5262 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005263
Eric Laurente552edb2014-03-10 17:42:56 -07005264 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005265 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005266 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005268 DeviceVector deviceList;
5269 if ((address == NULL) || (strlen(address) == 0)) {
5270 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5271 } else {
5272 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5273 }
5274
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 if (!deviceList.isEmpty()) {
5276 struct audio_patch patch;
5277 outputDesc->toAudioPortConfig(&patch.sources[0]);
5278 patch.num_sources = 1;
5279 patch.num_sinks = 0;
5280 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5281 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 patch.num_sinks++;
5283 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 ssize_t index;
5285 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5286 index = mAudioPatches.indexOfKey(*patchHandle);
5287 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005288 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 }
5290 sp< AudioPatch> patchDesc;
5291 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5292 if (index >= 0) {
5293 patchDesc = mAudioPatches.valueAt(index);
5294 afPatchHandle = patchDesc->mAfPatchHandle;
5295 }
5296
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 &afPatchHandle,
5299 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005300 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5301 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005305 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 addAudioPatch(patchDesc->mHandle, patchDesc);
5307 } else {
5308 patchDesc->mPatch = patch;
5309 }
5310 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 if (patchHandle) {
5312 *patchHandle = patchDesc->mHandle;
5313 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005314 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005316 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005317 }
5318 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005319
5320 // inform all input as well
5321 for (size_t i = 0; i < mInputs.size(); i++) {
5322 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005323 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005324 AudioParameter inputCmd = AudioParameter();
5325 ALOGV("%s: inform input %d of device:%d", __func__,
5326 inputDescriptor->mIoHandle, device);
5327 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5328 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5329 inputCmd.toString(),
5330 delayMs);
5331 }
5332 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005333 }
Eric Laurente552edb2014-03-10 17:42:56 -07005334
5335 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005336 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005337
5338 return muteWaitMs;
5339}
5340
Eric Laurentc75307b2015-03-17 15:29:32 -07005341status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005342 int delayMs,
5343 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005344{
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 ssize_t index;
5346 if (patchHandle) {
5347 index = mAudioPatches.indexOfKey(*patchHandle);
5348 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005349 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 }
5351 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 return INVALID_OPERATION;
5353 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5355 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005356 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005357 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 removeAudioPatch(patchDesc->mHandle);
5359 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005360 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005361 return status;
5362}
5363
5364status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5365 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 bool force,
5367 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005368{
5369 status_t status = NO_ERROR;
5370
Eric Laurent1f2f2232014-06-02 12:01:23 -07005371 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005372 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5373 inputDesc->mDevice = device;
5374
5375 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5376 if (!deviceList.isEmpty()) {
5377 struct audio_patch patch;
5378 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005379 // AUDIO_SOURCE_HOTWORD is for internal use only:
5380 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005381 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005382 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005383 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5384 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005385 patch.num_sinks = 1;
5386 //only one input device for now
5387 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005388 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 ssize_t index;
5390 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5391 index = mAudioPatches.indexOfKey(*patchHandle);
5392 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005393 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005394 }
5395 sp< AudioPatch> patchDesc;
5396 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5397 if (index >= 0) {
5398 patchDesc = mAudioPatches.valueAt(index);
5399 afPatchHandle = patchDesc->mAfPatchHandle;
5400 }
5401
Eric Laurent1c333e22014-05-20 10:48:17 -07005402 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005403 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005404 0);
5405 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005406 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005407 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005409 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 addAudioPatch(patchDesc->mHandle, patchDesc);
5411 } else {
5412 patchDesc->mPatch = patch;
5413 }
5414 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005415 if (patchHandle) {
5416 *patchHandle = patchDesc->mHandle;
5417 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005418 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005419 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005420 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005421 }
5422 }
5423 }
5424 return status;
5425}
5426
Eric Laurent6a94d692014-05-20 11:18:06 -07005427status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5428 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005429{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005430 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005431 ssize_t index;
5432 if (patchHandle) {
5433 index = mAudioPatches.indexOfKey(*patchHandle);
5434 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005435 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005436 }
5437 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005438 return INVALID_OPERATION;
5439 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005440 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5441 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005442 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005443 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 removeAudioPatch(patchDesc->mHandle);
5445 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005446 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005447 return status;
5448}
5449
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005450sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005451 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005452 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005453 audio_format_t& format,
5454 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005455 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005456{
5457 // Choose an input profile based on the requested capture parameters: select the first available
5458 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005459 //
5460 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5461 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005462
Glenn Kasten730b9262018-03-29 15:01:26 -07005463 sp<IOProfile> firstInexact;
5464 uint32_t updatedSamplingRate = 0;
5465 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5466 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005467 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005468 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005469 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005470 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005471 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005472 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005473 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005474 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005475 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005476 &channelMask /*updatedChannelMask*/,
5477 // FIXME ugly cast
5478 (audio_output_flags_t) flags,
5479 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005480 return profile;
5481 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005482 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5483 samplingRate,
5484 &updatedSamplingRate,
5485 format,
5486 &updatedFormat,
5487 channelMask,
5488 &updatedChannelMask,
5489 // FIXME ugly cast
5490 (audio_output_flags_t) flags,
5491 false /*exactMatchRequiredForInputFlags*/)) {
5492 firstInexact = profile;
5493 }
5494
Eric Laurente552edb2014-03-10 17:42:56 -07005495 }
5496 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005497 if (firstInexact != nullptr) {
5498 samplingRate = updatedSamplingRate;
5499 format = updatedFormat;
5500 channelMask = updatedChannelMask;
5501 return firstInexact;
5502 }
Eric Laurente552edb2014-03-10 17:42:56 -07005503 return NULL;
5504}
5505
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005506
5507audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005508 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005509{
François Gaffie036e1e92015-03-19 10:16:24 +01005510 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5511 audio_devices_t selectedDeviceFromMix =
5512 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005513
François Gaffie036e1e92015-03-19 10:16:24 +01005514 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5515 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005516 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005517 return getDeviceForInputSource(inputSource);
5518}
5519
5520audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5521{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005522 // Routing
5523 // Scan the whole RouteMap to see if we have an explicit route:
5524 // if the input source in the RouteMap is the same as the argument above,
5525 // and activity count is non-zero and the device in the route descriptor is available
5526 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005527 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5528 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005529 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005530 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005531 return route->mDeviceDescriptor->type();
5532 }
5533 }
5534
5535 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005536}
5537
Eric Laurente0720872014-03-11 09:30:41 -07005538float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005539 int index,
5540 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005541{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005542 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005543
5544 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5545 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5546 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5547 // the ringtone volume
5548 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5549 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5550 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5551 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5552 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5553 }
5554
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005555 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005556 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5557 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005558 switch (stream) {
5559 case AUDIO_STREAM_SYSTEM:
5560 case AUDIO_STREAM_RING:
5561 case AUDIO_STREAM_MUSIC:
5562 case AUDIO_STREAM_ALARM:
5563 case AUDIO_STREAM_NOTIFICATION:
5564 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5565 case AUDIO_STREAM_DTMF:
5566 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005567 int voiceVolumeIndex =
5568 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5569 const float maxVoiceVolDb =
5570 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5571 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005572 if (volumeDB > maxVoiceVolDb) {
5573 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5574 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5575 volumeDB = maxVoiceVolDb;
5576 }
5577 } break;
5578 default:
5579 break;
5580 }
5581 }
5582
Eric Laurente552edb2014-03-10 17:42:56 -07005583 // if a headset is connected, apply the following rules to ring tones and notifications
5584 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005585 // - always attenuate notifications volume by 6dB
5586 // - attenuate ring tones volume by 6dB unless music is not playing and
5587 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005588 // - if music is playing, always limit the volume to current music volume,
5589 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005590 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005591 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5592 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5593 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005594 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005595 AUDIO_DEVICE_OUT_USB_HEADSET |
5596 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005597 ((stream_strategy == STRATEGY_SONIFICATION)
5598 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005600 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005601 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005602 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005603 // when the phone is ringing we must consider that music could have been paused just before
5604 // by the music application and behave as if music was active if the last music track was
5605 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005606 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005607 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005608 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005609 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005610 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005611 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5612 musicDevice),
5613 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005614 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5615 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005616 if (volumeDB > minVolDB) {
5617 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005618 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005619 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005620 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5621 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5622 // on A2DP, also ensure notification volume is not too low compared to media when
5623 // intended to be played
5624 if ((volumeDB > -96.0f) &&
5625 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5626 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5627 stream, device,
5628 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5629 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5630 }
5631 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005632 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5633 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005634 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005635 }
5636 }
5637
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005638 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005639}
5640
Eric Laurente0720872014-03-11 09:30:41 -07005641status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005642 int index,
5643 const sp<AudioOutputDescriptor>& outputDesc,
5644 audio_devices_t device,
5645 int delayMs,
5646 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005647{
Eric Laurente552edb2014-03-10 17:42:56 -07005648 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005649 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005650 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005651 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005652 return NO_ERROR;
5653 }
François Gaffie2110e042015-03-24 08:41:51 +01005654 audio_policy_forced_cfg_t forceUseForComm =
5655 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005656 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005657 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5658 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005659 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005660 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005661 return INVALID_OPERATION;
5662 }
5663
Eric Laurentc75307b2015-03-17 15:29:32 -07005664 if (device == AUDIO_DEVICE_NONE) {
5665 device = outputDesc->device();
5666 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005667
Eric Laurentffbc80f2015-03-18 18:30:19 -07005668 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005669 if (outputDesc->isFixedVolume(device) ||
5670 // Force VoIP volume to max for bluetooth SCO
5671 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5672 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005673 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005674 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005675
Eric Laurentffbc80f2015-03-18 18:30:19 -07005676 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005677
Eric Laurent3b73df72014-03-11 09:06:29 -07005678 if (stream == AUDIO_STREAM_VOICE_CALL ||
5679 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005680 float voiceVolume;
5681 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005682 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005683 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005684 } else {
5685 voiceVolume = 1.0;
5686 }
5687
Eric Laurent18fba842016-03-31 14:41:26 -07005688 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005689 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5690 mLastVoiceVolume = voiceVolume;
5691 }
5692 }
5693
5694 return NO_ERROR;
5695}
5696
Eric Laurentc75307b2015-03-17 15:29:32 -07005697void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5698 audio_devices_t device,
5699 int delayMs,
5700 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005701{
Eric Laurentc75307b2015-03-17 15:29:32 -07005702 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005703
Eric Laurent794fde22016-03-11 09:50:45 -08005704 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005705 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005706 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005707 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005708 device,
5709 delayMs,
5710 force);
5711 }
5712}
5713
Eric Laurente0720872014-03-11 09:30:41 -07005714void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005715 bool on,
5716 const sp<AudioOutputDescriptor>& outputDesc,
5717 int delayMs,
5718 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005719{
Eric Laurent72249d52015-06-08 11:12:15 -07005720 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5721 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005722 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005723 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005724 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005725 }
5726 }
5727}
5728
Eric Laurente0720872014-03-11 09:30:41 -07005729void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005730 bool on,
5731 const sp<AudioOutputDescriptor>& outputDesc,
5732 int delayMs,
5733 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005734{
Eric Laurente552edb2014-03-10 17:42:56 -07005735 if (device == AUDIO_DEVICE_NONE) {
5736 device = outputDesc->device();
5737 }
5738
Eric Laurentc75307b2015-03-17 15:29:32 -07005739 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5740 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005741
5742 if (on) {
5743 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005744 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005745 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005746 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005747 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005748 }
5749 }
5750 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5751 outputDesc->mMuteCount[stream]++;
5752 } else {
5753 if (outputDesc->mMuteCount[stream] == 0) {
5754 ALOGV("setStreamMute() unmuting non muted stream!");
5755 return;
5756 }
5757 if (--outputDesc->mMuteCount[stream] == 0) {
5758 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005759 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005760 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005761 device,
5762 delayMs);
5763 }
5764 }
5765}
5766
Eric Laurente0720872014-03-11 09:30:41 -07005767void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005768 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005769{
Eric Laurent87ffa392015-05-22 10:32:38 -07005770 if(!hasPrimaryOutput()) {
5771 return;
5772 }
5773
Eric Laurente552edb2014-03-10 17:42:56 -07005774 // if the stream pertains to sonification strategy and we are in call we must
5775 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5776 // in the device used for phone strategy and play the tone if the selected device does not
5777 // interfere with the device used for phone strategy
5778 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5779 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005780 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005781 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5782 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005783 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005784 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5785 stream, starting, outputDesc->mDevice, stateChange);
5786 if (outputDesc->mRefCount[stream]) {
5787 int muteCount = 1;
5788 if (stateChange) {
5789 muteCount = outputDesc->mRefCount[stream];
5790 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005791 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005792 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5793 for (int i = 0; i < muteCount; i++) {
5794 setStreamMute(stream, starting, mPrimaryOutput);
5795 }
5796 } else {
5797 ALOGV("handleIncallSonification() high visibility");
5798 if (outputDesc->device() &
5799 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5800 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5801 for (int i = 0; i < muteCount; i++) {
5802 setStreamMute(stream, starting, mPrimaryOutput);
5803 }
5804 }
5805 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005806 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5807 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005808 } else {
5809 mpClientInterface->stopTone();
5810 }
5811 }
5812 }
5813 }
5814}
5815
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005816audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5817{
5818 // flags to stream type mapping
5819 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5820 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5821 }
5822 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5823 return AUDIO_STREAM_BLUETOOTH_SCO;
5824 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005825 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5826 return AUDIO_STREAM_TTS;
5827 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005828
5829 // usage to stream type mapping
5830 switch (attr->usage) {
5831 case AUDIO_USAGE_MEDIA:
5832 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005833 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005834 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5835 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005836 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5837 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005838 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5839 return AUDIO_STREAM_SYSTEM;
5840 case AUDIO_USAGE_VOICE_COMMUNICATION:
5841 return AUDIO_STREAM_VOICE_CALL;
5842
5843 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5844 return AUDIO_STREAM_DTMF;
5845
5846 case AUDIO_USAGE_ALARM:
5847 return AUDIO_STREAM_ALARM;
5848 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5849 return AUDIO_STREAM_RING;
5850
5851 case AUDIO_USAGE_NOTIFICATION:
5852 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5853 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5854 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5855 case AUDIO_USAGE_NOTIFICATION_EVENT:
5856 return AUDIO_STREAM_NOTIFICATION;
5857
5858 case AUDIO_USAGE_UNKNOWN:
5859 default:
5860 return AUDIO_STREAM_MUSIC;
5861 }
5862}
Eric Laurente83b55d2014-11-14 10:06:21 -08005863
François Gaffie53615e22015-03-19 09:24:12 +01005864bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5865{
Eric Laurente83b55d2014-11-14 10:06:21 -08005866 // has flags that map to a strategy?
5867 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5868 return true;
5869 }
5870
5871 // has known usage?
5872 switch (paa->usage) {
5873 case AUDIO_USAGE_UNKNOWN:
5874 case AUDIO_USAGE_MEDIA:
5875 case AUDIO_USAGE_VOICE_COMMUNICATION:
5876 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5877 case AUDIO_USAGE_ALARM:
5878 case AUDIO_USAGE_NOTIFICATION:
5879 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5880 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5881 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5882 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5883 case AUDIO_USAGE_NOTIFICATION_EVENT:
5884 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5885 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5886 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5887 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005888 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005889 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005890 break;
5891 default:
5892 return false;
5893 }
5894 return true;
5895}
5896
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005897bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005898 routing_strategy strategy, uint32_t inPastMs,
5899 nsecs_t sysTime) const
5900{
5901 if ((sysTime == 0) && (inPastMs != 0)) {
5902 sysTime = systemTime();
5903 }
Eric Laurent794fde22016-03-11 09:50:45 -08005904 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005905 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5906 (NUM_STRATEGIES == strategy)) &&
5907 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5908 return true;
5909 }
5910 }
5911 return false;
5912}
5913
Eric Laurent484e9272018-06-07 17:29:23 -07005914bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5915 routing_strategy strategy, uint32_t inPastMs,
5916 nsecs_t sysTime) const
5917{
5918 for (size_t i = 0; i < mOutputs.size(); i++) {
5919 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5920 if (outputDesc->sharesHwModuleWith(desc)
5921 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5922 return true;
5923 }
5924 }
5925 return false;
5926}
5927
François Gaffie2110e042015-03-24 08:41:51 +01005928audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5929{
5930 return mEngine->getForceUse(usage);
5931}
5932
5933bool AudioPolicyManager::isInCall()
5934{
5935 return isStateInCall(mEngine->getPhoneState());
5936}
5937
5938bool AudioPolicyManager::isStateInCall(int state)
5939{
5940 return is_state_in_call(state);
5941}
5942
Eric Laurentd60560a2015-04-10 11:31:20 -07005943void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5944{
5945 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5946 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5947 if (sourceDesc->mDevice->equals(deviceDesc)) {
5948 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5949 stopAudioSource(sourceDesc->getHandle());
5950 }
5951 }
5952
5953 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5954 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5955 bool release = false;
5956 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5957 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5958 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5959 source->ext.device.type == deviceDesc->type()) {
5960 release = true;
5961 }
5962 }
5963 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5964 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5965 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5966 sink->ext.device.type == deviceDesc->type()) {
5967 release = true;
5968 }
5969 }
5970 if (release) {
5971 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5972 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5973 }
5974 }
5975}
5976
Phil Burk09bc4612016-02-24 15:58:15 -08005977// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005978void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5979 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005980 // TODO Set this based on Config properties.
5981 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005982
5983 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5984 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005985 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005986
jiabin81772902018-04-02 17:52:27 -07005987 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5988 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5989 formats.clear();
5990 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5991 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005992 }
jiabin81772902018-04-02 17:52:27 -07005993 // Always enable IEC61937 when in MANUAL mode.
5994 formats.add(AUDIO_FORMAT_IEC61937);
5995 } else { // NEVER, AUTO or ALWAYS
5996 // Analyze original support for various formats.
5997 bool supportsAC3 = false;
5998 bool supportsOtherSurround = false;
5999 bool supportsIEC61937 = false;
6000 mSurroundFormats.clear();
6001 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
6002 audio_format_t format = formats[formatIndex];
6003 switch (format) {
6004 case AUDIO_FORMAT_AC3:
6005 supportsAC3 = true;
6006 break;
6007 case AUDIO_FORMAT_E_AC3:
6008 case AUDIO_FORMAT_DTS:
6009 case AUDIO_FORMAT_DTS_HD:
6010 // If ALWAYS, remove all other surround formats here
6011 // since we will add them later.
6012 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6013 formats.removeAt(formatIndex);
6014 formatIndex--;
6015 }
6016 supportsOtherSurround = true;
6017 break;
6018 case AUDIO_FORMAT_IEC61937:
6019 supportsIEC61937 = true;
6020 break;
6021 default:
6022 break;
6023 }
6024 }
Phil Burk09bc4612016-02-24 15:58:15 -08006025
jiabin81772902018-04-02 17:52:27 -07006026 // Modify formats based on surround preferences.
6027 // If NEVER, remove support for surround formats.
6028 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6029 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
6030 // Remove surround sound related formats.
6031 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
6032 audio_format_t format = formats[formatIndex];
6033 switch(format) {
6034 case AUDIO_FORMAT_AC3:
6035 case AUDIO_FORMAT_E_AC3:
6036 case AUDIO_FORMAT_DTS:
6037 case AUDIO_FORMAT_DTS_HD:
6038 case AUDIO_FORMAT_IEC61937:
6039 formats.removeAt(formatIndex);
6040 break;
6041 default:
6042 formatIndex++; // keep it
6043 break;
6044 }
6045 }
6046 supportsAC3 = false;
6047 supportsOtherSurround = false;
6048 supportsIEC61937 = false;
6049 }
6050 } else { // AUTO or ALWAYS
6051 // Most TVs support AC3 even if they do not report it in the EDID.
6052 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6053 && !supportsAC3) {
6054 formats.add(AUDIO_FORMAT_AC3);
6055 supportsAC3 = true;
6056 }
6057
6058 // If ALWAYS, add support for raw surround formats if all are missing.
6059 // This assumes that if any of these formats are reported by the HAL
6060 // then the report is valid and should not be modified.
6061 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6062 formats.add(AUDIO_FORMAT_E_AC3);
6063 formats.add(AUDIO_FORMAT_DTS);
6064 formats.add(AUDIO_FORMAT_DTS_HD);
6065 supportsOtherSurround = true;
6066 }
6067
6068 // Add support for IEC61937 if any raw surround supported.
6069 // The HAL could do this but add it here, just in case.
6070 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6071 formats.add(AUDIO_FORMAT_IEC61937);
6072 supportsIEC61937 = true;
6073 }
6074
6075 // Add reported surround sound formats to enabled surround formats.
6076 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006077 audio_format_t format = formats[formatIndex];
6078 switch(format) {
6079 case AUDIO_FORMAT_AC3:
6080 case AUDIO_FORMAT_E_AC3:
6081 case AUDIO_FORMAT_DTS:
6082 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006083 case AUDIO_FORMAT_AAC_LC:
6084 case AUDIO_FORMAT_DOLBY_TRUEHD:
6085 case AUDIO_FORMAT_E_AC3_JOC:
6086 mSurroundFormats.insert(format);
Chih-Hung Hsieh39399602018-10-16 14:42:13 -07006087 break;
Phil Burk07ac1142016-03-25 13:39:29 -07006088 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006089 break;
6090 }
Phil Burk09bc4612016-02-24 15:58:15 -08006091 }
Phil Burk07ac1142016-03-25 13:39:29 -07006092 }
Phil Burk09bc4612016-02-24 15:58:15 -08006093 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006094}
6095
6096// Modify the list of channel masks supported.
6097void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6098 ChannelsVector &channelMasks = *channelMasksPtr;
6099 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6100 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6101
6102 // If NEVER, then remove support for channelMasks > stereo.
6103 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6104 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6105 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6106 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6107 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6108 channelMasks.removeAt(maskIndex);
6109 } else {
6110 maskIndex++;
6111 }
6112 }
jiabin81772902018-04-02 17:52:27 -07006113 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6114 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6115 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006116 bool supports5dot1 = false;
6117 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006118 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006119 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6120 supports5dot1 = true;
6121 break;
6122 }
6123 }
6124 // If not then add 5.1 support.
6125 if (!supports5dot1) {
6126 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6127 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6128 }
Phil Burk09bc4612016-02-24 15:58:15 -08006129 }
6130}
6131
Phil Burk00eeb322016-03-31 12:41:00 -07006132void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6133 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006134 AudioProfileVector &profiles)
6135{
6136 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006137
François Gaffie112b0af2015-11-19 16:13:25 +01006138 // Format MUST be checked first to update the list of AudioProfile
6139 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006140 reply = mpClientInterface->getParameters(
6141 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006142 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006143 AudioParameter repliedParameters(reply);
6144 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006145 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006146 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6147 return;
6148 }
Phil Burk09bc4612016-02-24 15:58:15 -08006149 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006150 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006151 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006152 }
Phil Burk09bc4612016-02-24 15:58:15 -08006153 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006154 }
François Gaffie112b0af2015-11-19 16:13:25 +01006155
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006156 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006157 ChannelsVector channelMasks;
6158 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006159 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006160 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006161
6162 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006163 reply = mpClientInterface->getParameters(
6164 ioHandle,
6165 requestedParameters.toString() + ";" +
6166 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006167 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006168 AudioParameter repliedParameters(reply);
6169 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006170 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006171 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006172 }
6173 }
6174 if (profiles.hasDynamicChannelsFor(format)) {
6175 reply = mpClientInterface->getParameters(ioHandle,
6176 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006177 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006178 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006179 AudioParameter repliedParameters(reply);
6180 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006181 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006182 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006183 if (device == AUDIO_DEVICE_OUT_HDMI) {
6184 filterSurroundChannelMasks(&channelMasks);
6185 }
François Gaffie112b0af2015-11-19 16:13:25 +01006186 }
6187 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006188 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006189 }
6190}
Eric Laurentd60560a2015-04-10 11:31:20 -07006191
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006192} // namespace android