blob: 899a790e495634eb7b74cf9b61e119151dd94829 [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"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070041#include <media/PatchBuilder.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070042#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070043#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070044#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010047#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010048#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010049#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010050#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010051#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010052#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurent3b73df72014-03-11 09:06:29 -070054namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurentdc462862016-07-19 12:29:53 -070056//FIXME: workaround for truncated touch sounds
57// to be removed when the problem is handled by system UI
58#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070059
60// Largest difference in dB on earpiece in call between the voice volume and another
61// media / notification / system volume.
62constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
63
jiabin81772902018-04-02 17:52:27 -070064#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
65// Array of all surround formats.
66static const audio_format_t SURROUND_FORMATS[] = {
67 AUDIO_FORMAT_AC3,
68 AUDIO_FORMAT_E_AC3,
69 AUDIO_FORMAT_DTS,
70 AUDIO_FORMAT_DTS_HD,
71 AUDIO_FORMAT_AAC_LC,
72 AUDIO_FORMAT_DOLBY_TRUEHD,
73 AUDIO_FORMAT_E_AC3_JOC,
74};
75// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
76static const audio_format_t AAC_FORMATS[] = {
77 AUDIO_FORMAT_AAC_LC,
78 AUDIO_FORMAT_AAC_HE_V1,
79 AUDIO_FORMAT_AAC_HE_V2,
80 AUDIO_FORMAT_AAC_ELD,
81 AUDIO_FORMAT_AAC_XHE,
82};
83
Eric Laurente552edb2014-03-10 17:42:56 -070084// ----------------------------------------------------------------------------
85// AudioPolicyInterface implementation
86// ----------------------------------------------------------------------------
87
Eric Laurente0720872014-03-11 09:30:41 -070088status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080089 audio_policy_dev_state_t state,
90 const char *device_address,
91 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070092{
jiabina7b43792018-02-15 16:04:46 -080093 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
94 nextAudioPortGeneration();
95 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080096}
97
François Gaffie44481e72016-04-20 07:49:57 +020098void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
99 audio_policy_dev_state_t state,
100 const String8 &device_address)
101{
102 AudioParameter param(device_address);
103 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700104 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200105 param.addInt(key, device);
106 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
107}
108
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800110 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800111 const char *device_address,
112 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800113{
Paul McLeane743a472015-01-28 11:07:31 -0800114 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800115 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700116
117 // connect/disconnect only 1 device at a time
118 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
119
François Gaffie53615e22015-03-19 09:24:12 +0100120 sp<DeviceDescriptor> devDesc =
121 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800122
Eric Laurente552edb2014-03-10 17:42:56 -0700123 // handle output devices
124 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700125 SortedVector <audio_io_handle_t> outputs;
126
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
128
Eric Laurente552edb2014-03-10 17:42:56 -0700129 // save a copy of the opened output descriptors before any output is opened or closed
130 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
131 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700132 switch (state)
133 {
134 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800135 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700137 ALOGW("setDeviceConnectionState() device already connected: %x", device);
138 return INVALID_OPERATION;
139 }
140 ALOGV("setDeviceConnectionState() connecting device %x", device);
141
Eric Laurente552edb2014-03-10 17:42:56 -0700142 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700143 index = mAvailableOutputDevices.add(devDesc);
144 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100145 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700146 if (module == 0) {
147 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
148 device);
149 mAvailableOutputDevices.remove(devDesc);
150 return INVALID_OPERATION;
151 }
Paul McLeane743a472015-01-28 11:07:31 -0800152 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 } else {
154 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700155 }
156
François Gaffie44481e72016-04-20 07:49:57 +0200157 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
158 // parameters on newly connected devices (instead of opening the outputs...)
159 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
160
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700162 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200163
164 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
165 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700166 return INVALID_OPERATION;
167 }
François Gaffie2110e042015-03-24 08:41:51 +0100168 // Propagate device availability to Engine
169 mEngine->setDeviceConnectionState(devDesc, state);
170
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700171 // outputs should never be empty here
172 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
173 "checkOutputsForDevice() returned no outputs but status OK");
174 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
175 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800176
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700179 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700180 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700181 ALOGW("setDeviceConnectionState() device not connected: %x", device);
182 return INVALID_OPERATION;
183 }
184
Paul McLean5c477aa2014-08-20 16:47:57 -0700185 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
186
Paul McLeane743a472015-01-28 11:07:31 -0800187 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200188 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700192
Eric Laurenta1d525f2015-01-29 13:36:45 -0800193 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100194
195 // Propagate device availability to Engine
196 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700197 } break;
198
199 default:
200 ALOGE("setDeviceConnectionState() invalid state: %x", state);
201 return BAD_VALUE;
202 }
203
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
205 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700206 checkA2dpSuspend();
207 checkOutputForAllStrategies();
208 // outputs must be closed after checkOutputForAllStrategies() is executed
209 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800210 for (audio_io_handle_t output : outputs) {
211 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700212 // close unused outputs after device disconnection or direct outputs that have been
213 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700214 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700215 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
216 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800217 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700218 }
219 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 // check again after closing A2DP output to reset mA2dpSuspended if needed
221 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700222 }
223
224 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700225 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700226 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
227 updateCallRouting(newDevice);
228 }
Eric Laurente552edb2014-03-10 17:42:56 -0700229 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700230 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
231 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
232 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700233 // do not force device change on duplicated output because if device is 0, it will
234 // also force a device 0 for the two outputs it is duplicated to which may override
235 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700236 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100237 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700238 // always force when disconnecting (a non-duplicated device)
239 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700240 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700241 }
Eric Laurente552edb2014-03-10 17:42:56 -0700242 }
243
Eric Laurentd60560a2015-04-10 11:31:20 -0700244 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
245 cleanUpForDevice(devDesc);
246 }
247
Eric Laurent72aa32f2014-05-30 18:51:48 -0700248 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700249 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700250 } // end if is output device
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // handle input devices
253 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700254 SortedVector <audio_io_handle_t> inputs;
255
Eric Laurent3a4311c2014-03-17 12:00:47 -0700256 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700257 switch (state)
258 {
259 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700260 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700262 ALOGW("setDeviceConnectionState() device already connected: %d", device);
263 return INVALID_OPERATION;
264 }
François Gaffie53615e22015-03-19 09:24:12 +0100265 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700266 if (module == NULL) {
267 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
268 device);
269 return INVALID_OPERATION;
270 }
François Gaffie44481e72016-04-20 07:49:57 +0200271
272 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
273 // parameters on newly connected devices (instead of opening the inputs...)
274 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
275
Paul McLean9080a4c2015-06-18 08:24:02 -0700276 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200277 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
278 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700279 return INVALID_OPERATION;
280 }
281
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 index = mAvailableInputDevices.add(devDesc);
283 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800284 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700285 } else {
286 return NO_MEMORY;
287 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800288
François Gaffie2110e042015-03-24 08:41:51 +0100289 // Propagate device availability to Engine
290 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700291 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700292
293 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700294 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700296 ALOGW("setDeviceConnectionState() device not connected: %d", device);
297 return INVALID_OPERATION;
298 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700299
300 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
301
302 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200303 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700304
Paul McLean9080a4c2015-06-18 08:24:02 -0700305 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700306 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700307
François Gaffie2110e042015-03-24 08:41:51 +0100308 // Propagate device availability to Engine
309 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700310 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700311
312 default:
313 ALOGE("setDeviceConnectionState() invalid state: %x", state);
314 return BAD_VALUE;
315 }
316
Eric Laurentd4692962014-05-05 18:13:44 -0700317 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700318 // As the input device list can impact the output device selection, update
319 // getDeviceForStrategy() cache
320 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700321
Eric Laurent87ffa392015-05-22 10:32:38 -0700322 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700323 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
324 updateCallRouting(newDevice);
325 }
326
Eric Laurentd60560a2015-04-10 11:31:20 -0700327 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
328 cleanUpForDevice(devDesc);
329 }
330
Eric Laurentb52c1522014-05-20 11:27:36 -0700331 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700332 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700333 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700334
335 ALOGW("setDeviceConnectionState() invalid device: %x", device);
336 return BAD_VALUE;
337}
338
Eric Laurente0720872014-03-11 09:30:41 -0700339audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100340 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700341{
Eric Laurent634b7142016-04-20 13:48:02 -0700342 sp<DeviceDescriptor> devDesc =
343 mHwModules.getDeviceDescriptor(device, device_address, "",
344 (strlen(device_address) != 0)/*matchAddress*/);
345
346 if (devDesc == 0) {
347 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
348 device, device_address);
349 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
350 }
François Gaffie53615e22015-03-19 09:24:12 +0100351
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 DeviceVector *deviceVector;
353
Eric Laurente552edb2014-03-10 17:42:56 -0700354 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700355 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700356 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700357 deviceVector = &mAvailableInputDevices;
358 } else {
359 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
360 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700361 }
Eric Laurent634b7142016-04-20 13:48:02 -0700362
363 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
364 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800365}
366
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800367status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
368 const char *device_address,
369 const char *device_name)
370{
371 status_t status;
372
373 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
374 device, device_address, device_name);
375
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800376 // connect/disconnect only 1 device at a time
377 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
378
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800379 // Check if the device is currently connected
380 sp<DeviceDescriptor> devDesc =
381 mHwModules.getDeviceDescriptor(device, device_address, device_name);
382 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
383 if (index < 0) {
384 // Nothing to do: device is not connected
385 return NO_ERROR;
386 }
387
388 // Toggle the device state: UNAVAILABLE -> AVAILABLE
389 // This will force reading again the device configuration
390 status = setDeviceConnectionState(device,
391 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
392 device_address, device_name);
393 if (status != NO_ERROR) {
394 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
395 status);
396 return status;
397 }
398
399 status = setDeviceConnectionState(device,
400 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
401 device_address, device_name);
402 if (status != NO_ERROR) {
403 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
404 status);
405 return status;
406 }
407
408 return NO_ERROR;
409}
410
Eric Laurentdc462862016-07-19 12:29:53 -0700411uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700412{
413 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700414 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700415
Andy Hunga76c7de2016-12-13 19:14:31 -0800416 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700417 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700418 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800419 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700420 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
421
422 // release existing RX patch if any
423 if (mCallRxPatch != 0) {
424 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
425 mCallRxPatch.clear();
426 }
427 // release TX patch if any
428 if (mCallTxPatch != 0) {
429 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
430 mCallTxPatch.clear();
431 }
432
433 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
434 // via setOutputDevice() on primary output.
435 // Otherwise, create two audio patches for TX and RX path.
436 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700437 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700438 // If the TX device is also on the primary HW module, setOutputDevice() will take care
439 // of it due to legacy implementation. If not, create a patch.
440 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
441 == AUDIO_DEVICE_NONE) {
442 createTxPatch = true;
443 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700444 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800445 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446 createTxPatch = true;
447 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700448 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800449 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
450 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700451
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800452 return muteWaitMs;
453}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700454
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800455sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
456 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700457 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700458
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800459 sp<DeviceDescriptor> txSourceDeviceDesc;
460 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700461 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
462 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800463 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700464 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
465 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 }
467
468 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
469 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
470 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
471 // request to reuse existing output stream if one is already opened to reach the target device
472 if (output != AUDIO_IO_HANDLE_NONE) {
473 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
474 ALOG_ASSERT(!outputDesc->isDuplicated(),
475 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700476 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477 }
478
479 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700480 // terminate active capture if on the same HW module as the call TX source device
481 // FIXME: would be better to refine to only inputs whose profile connects to the
482 // call TX device but this information is not in the audio patch and logic here must be
483 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800484 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800485 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
486 AudioSessionCollection activeSessions =
487 activeDesc->getAudioSessions(true /*activeOnly*/);
488 for (size_t j = 0; j < activeSessions.size(); j++) {
489 audio_session_t activeSession = activeSessions.keyAt(j);
490 stopInput(activeDesc->mIoHandle, activeSession);
491 releaseInput(activeDesc->mIoHandle, activeSession);
492 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700493 }
494 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700495 }
Eric Laurentdc462862016-07-19 12:29:53 -0700496
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800497 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 status_t status = mpClientInterface->createAudioPatch(
499 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800500 ALOGW_IF(status != NO_ERROR,
501 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
502 sp<AudioPatch> audioPatch;
503 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700504 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800505 audioPatch->mAfPatchHandle = afPatchHandle;
506 audioPatch->mUid = mUidCached;
507 }
508 return audioPatch;
509}
510
Mikhail Naganovdc769682018-05-04 15:34:08 -0700511sp<DeviceDescriptor> AudioPolicyManager::findDevice(
512 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 DeviceVector deviceList = devices.getDevicesFromType(device);
514 ALOG_ASSERT(!deviceList.isEmpty(),
515 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700516 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517}
518
Eric Laurente0720872014-03-11 09:30:41 -0700519void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700520{
521 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100522 // store previous phone state for management of sonification strategy below
523 int oldState = mEngine->getPhoneState();
524
525 if (mEngine->setPhoneState(state) != NO_ERROR) {
526 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700527 return;
528 }
François Gaffie2110e042015-03-24 08:41:51 +0100529 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700530 // if leaving call state, handle special case of active streams
531 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700532 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700533 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800534 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700535 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700536 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800537
Eric Laurent63dea1d2015-07-02 17:10:28 -0700538 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800539 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700540 }
541
François Gaffie2110e042015-03-24 08:41:51 +0100542 /**
543 * Switching to or from incall state or switching between telephony and VoIP lead to force
544 * routing command.
545 */
546 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
547 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700548
549 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700550 checkA2dpSuspend();
551 checkOutputForAllStrategies();
552 updateDevicesAndOutputs();
553
Eric Laurente552edb2014-03-10 17:42:56 -0700554 int delayMs = 0;
555 if (isStateInCall(state)) {
556 nsecs_t sysTime = systemTime();
557 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 // mute media and sonification strategies and delay device switch by the largest
560 // latency of any output where either strategy is active.
561 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100562 if ((isStrategyActive(desc, STRATEGY_MEDIA,
563 SONIFICATION_HEADSET_MUSIC_DELAY,
564 sysTime) ||
565 isStrategyActive(desc, STRATEGY_SONIFICATION,
566 SONIFICATION_HEADSET_MUSIC_DELAY,
567 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700568 (delayMs < (int)desc->latency()*2)) {
569 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700571 setStrategyMute(STRATEGY_MEDIA, true, desc);
572 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700573 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700574 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
575 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700576 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
577 }
578 }
579
Eric Laurent87ffa392015-05-22 10:32:38 -0700580 if (hasPrimaryOutput()) {
581 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
582 // the device returned is not necessarily reachable via this output
583 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
584 // force routing command to audio hardware when ending call
585 // even if no device change is needed
586 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
587 rxDevice = mPrimaryOutput->device();
588 }
Eric Laurente552edb2014-03-10 17:42:56 -0700589
Eric Laurent87ffa392015-05-22 10:32:38 -0700590 if (state == AUDIO_MODE_IN_CALL) {
591 updateCallRouting(rxDevice, delayMs);
592 } else if (oldState == AUDIO_MODE_IN_CALL) {
593 if (mCallRxPatch != 0) {
594 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
595 mCallRxPatch.clear();
596 }
597 if (mCallTxPatch != 0) {
598 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
599 mCallTxPatch.clear();
600 }
601 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
602 } else {
603 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700606
607 // reevaluate routing on all outputs in case tracks have been started during the call
608 for (size_t i = 0; i < mOutputs.size(); i++) {
609 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
610 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
611 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800612 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700613 }
614 }
615
Eric Laurente552edb2014-03-10 17:42:56 -0700616 // if entering in call state, handle special case of active streams
617 // pertaining to sonification strategy see handleIncallSonification()
618 if (isStateInCall(state)) {
619 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800620 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700621 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700623
624 // force reevaluating accessibility routing when call starts
625 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700626 }
627
628 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700629 if (state == AUDIO_MODE_RINGTONE &&
630 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700631 mLimitRingtoneVolume = true;
632 } else {
633 mLimitRingtoneVolume = false;
634 }
635}
636
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700637audio_mode_t AudioPolicyManager::getPhoneState() {
638 return mEngine->getPhoneState();
639}
640
Eric Laurente0720872014-03-11 09:30:41 -0700641void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700642 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700643{
François Gaffie2110e042015-03-24 08:41:51 +0100644 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700645 if (config == mEngine->getForceUse(usage)) {
646 return;
647 }
Eric Laurente552edb2014-03-10 17:42:56 -0700648
François Gaffie2110e042015-03-24 08:41:51 +0100649 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
650 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
651 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700652 }
François Gaffie2110e042015-03-24 08:41:51 +0100653 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
654 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
655 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700656
657 // check for device and output changes triggered by new force usage
658 checkA2dpSuspend();
659 checkOutputForAllStrategies();
660 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800661
Eric Laurentdc462862016-07-19 12:29:53 -0700662 //FIXME: workaround for truncated touch sounds
663 // to be removed when the problem is handled by system UI
664 uint32_t delayMs = 0;
665 uint32_t waitMs = 0;
666 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
667 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
668 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700671 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700674 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
675 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
676 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700677 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
678 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700679 }
Eric Laurente552edb2014-03-10 17:42:56 -0700680 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700681 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700682 }
683 }
684
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800685 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700687 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800688 if (activeDesc->mProfile->getSupportedDevices().types() &
689 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
690 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700691 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 }
Eric Laurente552edb2014-03-10 17:42:56 -0700694 }
Eric Laurente552edb2014-03-10 17:42:56 -0700695}
696
Eric Laurente0720872014-03-11 09:30:41 -0700697void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700698{
699 ALOGV("setSystemProperty() property %s, value %s", property, value);
700}
701
702// Find a direct output profile compatible with the parameters passed, even if the input flags do
703// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800704sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700705 audio_devices_t device,
706 uint32_t samplingRate,
707 audio_format_t format,
708 audio_channel_mask_t channelMask,
709 audio_output_flags_t flags)
710{
Eric Laurent861a6282015-05-18 15:40:16 -0700711 // only retain flags that will drive the direct output profile selection
712 // if explicitly requested
713 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700714 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
715 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700716 flags =
717 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
718
719 sp<IOProfile> profile;
720
Mikhail Naganovd4120142017-12-06 15:49:22 -0800721 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800722 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700723 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700724 samplingRate, NULL /*updatedSamplingRate*/,
725 format, NULL /*updatedFormat*/,
726 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700727 flags)) {
728 continue;
729 }
730 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100731 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700732 continue;
733 }
734 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100735 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700736 continue;
737 }
738 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100739 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700740 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700741 }
Eric Laurente552edb2014-03-10 17:42:56 -0700742 }
743 }
Eric Laurent861a6282015-05-18 15:40:16 -0700744 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700745}
746
Eric Laurentf4e63452017-11-06 19:31:46 +0000747audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700748{
Eric Laurent3b73df72014-03-11 09:06:29 -0700749 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700750 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800751
752 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
753 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
754 // format, flags, etc. This may result in some discrepancy for functions that utilize
755 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
756 // and AudioSystem::getOutputSamplingRate().
757
Eric Laurentf4e63452017-11-06 19:31:46 +0000758 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
759 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700760
Eric Laurentf4e63452017-11-06 19:31:46 +0000761 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
762 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700763}
764
Eric Laurente83b55d2014-11-14 10:06:21 -0800765status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
766 audio_io_handle_t *output,
767 audio_session_t session,
768 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700769 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800770 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200771 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700772 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800773 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700774{
Eric Laurente83b55d2014-11-14 10:06:21 -0800775 audio_attributes_t attributes;
776 if (attr != NULL) {
777 if (!isValidAttributes(attr)) {
778 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
779 attr->usage, attr->content_type, attr->flags,
780 attr->tags);
781 return BAD_VALUE;
782 }
783 attributes = *attr;
784 } else {
785 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
786 ALOGE("getOutputForAttr(): invalid stream type");
787 return BAD_VALUE;
788 }
789 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700790 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800791
792 // TODO: check for existing client for this port ID
793 if (*portId == AUDIO_PORT_HANDLE_NONE) {
794 *portId = AudioPort::getNextUniqueId();
795 }
796
Eric Laurentc75307b2015-03-17 15:29:32 -0700797 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800798 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100799 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800800 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100801 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800802 }
François Gaffie036e1e92015-03-19 10:16:24 +0100803 *stream = streamTypefromAttributesInt(&attributes);
804 *output = desc->mIoHandle;
805 ALOGV("getOutputForAttr() returns output %d", *output);
806 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800807 }
808 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
809 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
810 return BAD_VALUE;
811 }
812
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700813 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
814 " session %d selectedDeviceId %d",
815 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700816 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700817
818 *stream = streamTypefromAttributesInt(&attributes);
819
820 // Explicit routing?
821 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800823 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700824 }
825 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700826
Eric Laurente83b55d2014-11-14 10:06:21 -0800827 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700828 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700829
Eric Laurente83b55d2014-11-14 10:06:21 -0800830 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200831 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700832 }
833
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800834 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
835 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200836 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700837
Andy Hungc88b0642018-04-27 15:42:35 -0700838 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800839 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700840 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800841 return INVALID_OPERATION;
842 }
Paul McLeanaa981192015-03-21 09:55:15 -0700843
Eric Laurent2ac76942017-06-22 17:17:09 -0700844 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
845 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
846 : AUDIO_PORT_HANDLE_NONE;
847
848 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700851}
852
853audio_io_handle_t AudioPolicyManager::getOutputForDevice(
854 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800855 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700856 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800857 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200858 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700859{
Andy Hungc88b0642018-04-27 15:42:35 -0700860 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700861 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862
Eric Laurente552edb2014-03-10 17:42:56 -0700863 // open a direct output if required by specified parameters
864 //force direct flag if offload flag is set: offloading implies a direct output stream
865 // and all common behaviors are driven by checking only the direct flag
866 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200867 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
868 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700869 }
Nadav Bar766fb022018-01-07 12:18:03 +0200870 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
871 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700872 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800873 // only allow deep buffering for music stream type
874 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200875 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700876 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200877 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700878 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
879 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200880 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800881 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700882 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200883 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700884 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800885 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200886 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700887 AUDIO_OUTPUT_FLAG_DIRECT);
888 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200889 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
890 stream == AUDIO_STREAM_MUSIC &&
891 audio_is_linear_pcm(config->format) &&
892 isInCall()) {
893 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700894 }
Eric Laurente552edb2014-03-10 17:42:56 -0700895
Nadav Bar766fb022018-01-07 12:18:03 +0200896
Eric Laurentb732cf52014-09-24 19:08:21 -0700897 sp<IOProfile> profile;
898
899 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700900 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200901 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800902 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
903 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700904 goto non_direct_output;
905 }
906
Andy Hung2ddee192015-12-18 17:34:44 -0800907 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
908 // This prevents creating an offloaded track and tearing it down immediately after start
909 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700910 // FIXME: We should check the audio session here but we do not have it in this context.
911 // This may prevent offloading in rare situations where effects are left active by apps
912 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700913
Nadav Bar766fb022018-01-07 12:18:03 +0200914 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800915 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700916 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800917 config->sample_rate,
918 config->format,
919 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200920 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
Eric Laurent1c333e22014-05-20 10:48:17 -0700923 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700924 // exclusive outputs for MMAP and Offload are enforced by different session ids.
925 for (size_t i = 0; i < mOutputs.size(); i++) {
926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
927 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
928 // reuse direct output if currently open by the same client
929 // and configured with same parameters
930 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700931 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700932 (config->channel_mask == desc->mChannelMask) &&
933 (session == desc->mDirectClientSession)) {
934 desc->mDirectOpenCount++;
935 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
936 mOutputs.keyAt(i), session);
937 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 }
939 }
940 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800941
942 if (!profile->canOpenNewIo()) {
943 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700944 }
Eric Laurent861a6282015-05-18 15:40:16 -0700945
Eric Laurent3974e3b2017-12-07 17:58:43 -0800946 sp<SwAudioOutputDescriptor> outputDesc =
947 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800948
949 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
950 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
951 : String8("");
952
Nadav Bar766fb022018-01-07 12:18:03 +0200953 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700954
955 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700956 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800957 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700958 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800959 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
960 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
961 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
962 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
963 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700964 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800965 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700966 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800967 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800968 if (audio_is_linear_pcm(config->format) &&
969 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800970 goto non_direct_output;
971 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700974 outputDesc->mRefCount[stream] = 0;
975 outputDesc->mStopTime[stream] = 0;
976 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800977 outputDesc->mDirectClientSession = session;
978
Eric Laurente552edb2014-03-10 17:42:56 -0700979 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000981 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700982 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700983 return output;
984 }
985
Eric Laurentb732cf52014-09-24 19:08:21 -0700986non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700987
988 // A request for HW A/V sync cannot fallback to a mixed output because time
989 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -0800990 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -0700991 return AUDIO_IO_HANDLE_NONE;
992 }
993
Eric Laurente552edb2014-03-10 17:42:56 -0700994 // ignoring channel mask due to downmix capability in mixer
995
996 // open a non direct output
997
998 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -0800999 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001000 // get which output is suitable for the specified stream. The actual
1001 // routing change will happen when startOutput() will be called
1002 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1003
Eric Laurent8838a382014-09-08 16:44:28 -07001004 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001005 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1006 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001007 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001008 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001009 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001010 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001011
Eric Laurente552edb2014-03-10 17:42:56 -07001012 return output;
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001016 audio_output_flags_t flags,
1017 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001018{
1019 // select one output among several that provide a path to a particular device or set of
1020 // devices (the list was previously build by getOutputsForDevice()).
1021 // The priority is as follows:
1022 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001023 // 2: the output with the bit depth the closest to the requested one
1024 // 3: the primary output
1025 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001026
1027 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001028 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
1030 if (outputs.size() == 1) {
1031 return outputs[0];
1032 }
1033
1034 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001035 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1036 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1037 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001038 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1039 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001040
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001041 for (audio_io_handle_t output : outputs) {
1042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001043 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001044 // if a valid format is specified, skip output if not compatible
1045 if (format != AUDIO_FORMAT_INVALID) {
1046 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001047 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001048 continue;
1049 }
1050 } else if (!audio_is_linear_pcm(format)) {
1051 continue;
1052 }
Eric Laurente6930022016-02-11 10:20:40 -08001053 if (AudioPort::isBetterFormatMatch(
1054 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001055 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001056 bestFormat = outputDesc->mFormat;
1057 }
Eric Laurent8838a382014-09-08 16:44:28 -07001058 }
1059
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001060 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001061 if (commonFlags >= maxCommonFlags) {
1062 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001063 if (format != AUDIO_FORMAT_INVALID
1064 && AudioPort::isBetterFormatMatch(
1065 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001066 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001067 bestFormatForFlags = outputDesc->mFormat;
1068 }
1069 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001070 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001071 maxCommonFlags = commonFlags;
1072 bestFormatForFlags = outputDesc->mFormat;
1073 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001074 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001075 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001076 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001077 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001078 }
1079 }
1080 }
1081
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001082 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001083 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001085 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001086 return outputForFormat;
1087 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001088 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001089 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001090 }
1091
1092 return outputs[0];
1093}
1094
Eric Laurente0720872014-03-11 09:30:41 -07001095status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001096 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001097 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001098{
Paul McLeanaa981192015-03-21 09:55:15 -07001099 ALOGV("startOutput() output %d, stream %d, session %d",
1100 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001101 ssize_t index = mOutputs.indexOfKey(output);
1102 if (index < 0) {
1103 ALOGW("startOutput() unknown output %d", output);
1104 return BAD_VALUE;
1105 }
1106
Eric Laurentc75307b2015-03-17 15:29:32 -07001107 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1108
Eric Laurent733ce942017-12-07 12:18:25 -08001109 status_t status = outputDesc->start();
1110 if (status != NO_ERROR) {
1111 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001112 }
1113
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001114 // Routing?
1115 mOutputRoutes.incRouteActivity(session);
1116
Eric Laurentc75307b2015-03-17 15:29:32 -07001117 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001118 AudioMix *policyMix = NULL;
1119 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001120 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001121 policyMix = outputDesc->mPolicyMix;
1122 address = policyMix->mDeviceAddress.string();
1123 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1124 newDevice = policyMix->mDeviceType;
1125 } else {
1126 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1127 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001128 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001129 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001130 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001131 } else {
1132 newDevice = AUDIO_DEVICE_NONE;
1133 }
1134
1135 uint32_t delayMs = 0;
1136
Eric Laurent733ce942017-12-07 12:18:25 -08001137 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001138
1139 if (status != NO_ERROR) {
1140 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001141 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001142 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001143 }
1144 // Automatically enable the remote submix input when output is started on a re routing mix
1145 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001146 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1147 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001148 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1149 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001150 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 "remote-submix");
1152 }
1153
1154 if (delayMs != 0) {
1155 usleep(delayMs * 1000);
1156 }
1157
1158 return status;
1159}
1160
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001161status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001162 audio_stream_type_t stream,
1163 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001164 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 uint32_t *delayMs)
1166{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001167 // cannot start playback of STREAM_TTS if any other output is being used
1168 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001169
1170 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001171 if (stream == AUDIO_STREAM_TTS) {
1172 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001173 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001174 return INVALID_OPERATION;
1175 } else {
1176 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1177 }
1178 } else {
1179 // some playback other than beacon starts
1180 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1181 }
1182
Eric Laurent77305a62016-07-25 16:39:22 -07001183 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001184 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001185 bool force = !outputDesc->isActive() &&
1186 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001187
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001188 // requiresMuteCheck is false when we can bypass mute strategy.
1189 // It covers a common case when there is no materially active audio
1190 // and muting would result in unnecessary delay and dropped audio.
1191 const uint32_t outputLatencyMs = outputDesc->latency();
1192 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1193
Eric Laurente552edb2014-03-10 17:42:56 -07001194 // increment usage count for this stream on the requested output:
1195 // NOTE that the usage count is the same for duplicated output and hardware output which is
1196 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1197 outputDesc->changeRefCount(stream, 1);
1198
Eric Laurent36829f92017-04-07 19:04:42 -07001199 if (stream == AUDIO_STREAM_MUSIC) {
1200 selectOutputForMusicEffects();
1201 }
1202
Eric Laurent493404d2015-04-21 15:07:36 -07001203 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001204 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001205 if (device == AUDIO_DEVICE_NONE) {
1206 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001207 }
Eric Laurent36829f92017-04-07 19:04:42 -07001208
Eric Laurente552edb2014-03-10 17:42:56 -07001209 routing_strategy strategy = getStrategy(stream);
1210 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001211 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1212 (beaconMuteLatency > 0);
1213 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001214 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001215 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001216 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001217 // An output has a shared device if
1218 // - managed by the same hw module
1219 // - supports the currently selected device
1220 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1221 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1222
Eric Laurent77305a62016-07-25 16:39:22 -07001223 // force a device change if any other output is:
1224 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001225 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001226 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001227 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001228 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001229 // change the device currently selected by the other output.
1230 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001231 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001232 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001233 force = true;
1234 }
1235 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001236 // a notification so that audio focus effect can propagate, or that a mute/unmute
1237 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001238 const uint32_t latencyMs = desc->latency();
1239 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1240
1241 if (shouldWait && isActive && (waitMs < latencyMs)) {
1242 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001243 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001244
1245 // Require mute check if another output is on a shared device
1246 // and currently active to have proper drain and avoid pops.
1247 // Note restoring AudioTracks onto this output needs to invoke
1248 // a volume ramp if there is no mute.
1249 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
1251 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001252
1253 const uint32_t muteWaitMs =
1254 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001255
1256 // handle special case for sonification while in call
1257 if (isInCall()) {
1258 handleIncallSonification(stream, true, false);
1259 }
1260
1261 // apply volume rules for current stream and device if necessary
1262 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001263 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001264 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001265 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001266
1267 // update the outputs if starting an output with a stream that can affect notification
1268 // routing
1269 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001270
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001271 // force reevaluating accessibility routing when ringtone or alarm starts
1272 if (strategy == STRATEGY_SONIFICATION) {
1273 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1274 }
Eric Laurentdc462862016-07-19 12:29:53 -07001275
1276 if (waitMs > muteWaitMs) {
1277 *delayMs = waitMs - muteWaitMs;
1278 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001279
1280 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1281 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1282 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1283 // change occurs after the MixerThread starts and causes a stream volume
1284 // glitch.
1285 //
1286 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001287 }
Eric Laurentdc462862016-07-19 12:29:53 -07001288
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001289 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1290 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1291 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1292 }
1293
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001294 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1295 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1296 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1297 }
1298
Eric Laurente552edb2014-03-10 17:42:56 -07001299 return NO_ERROR;
1300}
1301
1302
Eric Laurente0720872014-03-11 09:30:41 -07001303status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001304 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001305 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001306{
1307 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1308 ssize_t index = mOutputs.indexOfKey(output);
1309 if (index < 0) {
1310 ALOGW("stopOutput() unknown output %d", output);
1311 return BAD_VALUE;
1312 }
1313
Eric Laurentc75307b2015-03-17 15:29:32 -07001314 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001315
Eric Laurentc75307b2015-03-17 15:29:32 -07001316 if (outputDesc->mRefCount[stream] == 1) {
1317 // Automatically disable the remote submix input when output is stopped on a
1318 // re routing mix of type MIX_TYPE_RECORDERS
1319 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1320 outputDesc->mPolicyMix != NULL &&
1321 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1322 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1323 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001324 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001325 "remote-submix");
1326 }
1327 }
1328
1329 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001330 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001332 int activityCount = mOutputRoutes.decRouteActivity(session);
1333 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1334
1335 if (forceDeviceUpdate) {
1336 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1337 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 }
1339
Eric Laurent3974e3b2017-12-07 17:58:43 -08001340 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1341
Eric Laurent733ce942017-12-07 12:18:25 -08001342 if (status == NO_ERROR ) {
1343 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001344 }
1345 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001346}
1347
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001348status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 audio_stream_type_t stream,
1350 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001351{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001352 // always handle stream stop, check which stream type is stopping
1353 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1354
Eric Laurente552edb2014-03-10 17:42:56 -07001355 // handle special case for sonification while in call
1356 if (isInCall()) {
1357 handleIncallSonification(stream, false, false);
1358 }
1359
1360 if (outputDesc->mRefCount[stream] > 0) {
1361 // decrement usage count of this stream on the output
1362 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001363
Eric Laurente552edb2014-03-10 17:42:56 -07001364 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001365 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001366 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001367 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001368 // delay the device switch by twice the latency because stopOutput() is executed when
1369 // the track stop() command is received and at that time the audio track buffer can
1370 // still contain data that needs to be drained. The latency only covers the audio HAL
1371 // and kernel buffers. Also the latency does not always include additional delay in the
1372 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001373 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001374
1375 // force restoring the device selection on other active outputs if it differs from the
1376 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001377 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001378 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001379 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001380 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001381 desc->isActive() &&
1382 outputDesc->sharesHwModuleWith(desc) &&
1383 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001384 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1385 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001386 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001387 newDevice2,
1388 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001389 delayMs);
1390 // re-apply device specific volume if not done by setOutputDevice()
1391 if (!force) {
1392 applyStreamVolumes(desc, newDevice2, delayMs);
1393 }
Eric Laurente552edb2014-03-10 17:42:56 -07001394 }
1395 }
1396 // update the outputs if stopping one with a stream that can affect notification routing
1397 handleNotificationRoutingForStream(stream);
1398 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001399
1400 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1401 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1402 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1403 }
1404
Eric Laurent36829f92017-04-07 19:04:42 -07001405 if (stream == AUDIO_STREAM_MUSIC) {
1406 selectOutputForMusicEffects();
1407 }
Eric Laurente552edb2014-03-10 17:42:56 -07001408 return NO_ERROR;
1409 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001411 return INVALID_OPERATION;
1412 }
1413}
1414
Eric Laurente83b55d2014-11-14 10:06:21 -08001415void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001416 audio_stream_type_t stream __unused,
1417 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001418{
1419 ALOGV("releaseOutput() %d", output);
1420 ssize_t index = mOutputs.indexOfKey(output);
1421 if (index < 0) {
1422 ALOGW("releaseOutput() releasing unknown output %d", output);
1423 return;
1424 }
1425
Paul McLeanaa981192015-03-21 09:55:15 -07001426 // Routing
1427 mOutputRoutes.removeRoute(session);
1428
Eric Laurentc75307b2015-03-17 15:29:32 -07001429 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001430 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001431 if (desc->mDirectOpenCount <= 0) {
1432 ALOGW("releaseOutput() invalid open count %d for output %d",
1433 desc->mDirectOpenCount, output);
1434 return;
1435 }
1436 if (--desc->mDirectOpenCount == 0) {
1437 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001438 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001439 }
1440 }
1441}
1442
1443
Eric Laurentcaf7f482014-11-25 17:50:47 -08001444status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1445 audio_io_handle_t *input,
1446 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001447 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001448 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001449 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001450 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001451 input_type_t *inputType,
1452 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001453{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001454 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001455 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001456 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001457
Eric Laurentad2e7b92017-09-14 20:06:42 -07001458 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001459 // handle legacy remote submix case where the address was not always specified
1460 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001461 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001462 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001463 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001464 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001465
Eric Laurentfe231122017-11-17 17:48:06 -08001466 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1467 inputSource = AUDIO_SOURCE_MIC;
1468 }
1469
Paul McLean466dc8e2015-04-17 13:15:36 -06001470 // Explicit routing?
1471 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001472 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001473 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001474 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001475 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001476
Eric Laurentad2e7b92017-09-14 20:06:42 -07001477 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1478 // possible
1479 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1480 *input != AUDIO_IO_HANDLE_NONE) {
1481 ssize_t index = mInputs.indexOfKey(*input);
1482 if (index < 0) {
1483 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1484 status = BAD_VALUE;
1485 goto error;
1486 }
1487 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1488 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1489 if (audioSession == 0) {
1490 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1491 status = BAD_VALUE;
1492 goto error;
1493 }
1494 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1495 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001496 // corresponds to a new client and is only permitted from the same UID.
1497 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001498 if (audioSession->openCount() == 1) {
1499 audioSession->setUid(uid);
1500 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001501 if (!audioSession->isSilenced()) {
1502 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1503 uid, session, audioSession->uid());
1504 status = INVALID_OPERATION;
1505 goto error;
1506 }
1507 audioSession->setUid(uid);
1508 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001509 }
1510 audioSession->changeOpenCount(1);
1511 *inputType = API_INPUT_LEGACY;
1512 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1513 *portId = AudioPort::getNextUniqueId();
1514 }
1515 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1516 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1517 : AUDIO_PORT_HANDLE_NONE;
1518 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1519
1520 return NO_ERROR;
1521 }
1522
1523 *input = AUDIO_IO_HANDLE_NONE;
1524 *inputType = API_INPUT_INVALID;
1525
Eric Laurentad2e7b92017-09-14 20:06:42 -07001526 halInputSource = inputSource;
1527
1528 // TODO: check for existing client for this port ID
1529 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1530 *portId = AudioPort::getNextUniqueId();
1531 }
1532
1533 audio_devices_t device;
1534
Eric Laurentc447ded2015-01-06 08:47:05 -08001535 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001536 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001537 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1538 if (status != NO_ERROR) {
1539 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001540 }
1541 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001542 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1543 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001544 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001545 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001546 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001547 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001548 status = BAD_VALUE;
1549 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001550 }
Eric Laurentc722f302014-12-10 11:21:49 -08001551 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001552 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001553 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1554 // there is an external policy, but this input is attached to a mix of recorders,
1555 // meaning it receives audio injected into the framework, so the recorder doesn't
1556 // know about it and is therefore considered "legacy"
1557 *inputType = API_INPUT_LEGACY;
1558 } else {
1559 // recording a mix of players defined by an external policy, we're rerouting for
1560 // an external policy
1561 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1562 }
Eric Laurentc722f302014-12-10 11:21:49 -08001563 } else if (audio_is_remote_submix_device(device)) {
1564 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001565 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001566 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1567 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001568 } else {
1569 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001570 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001571
Eric Laurent599c7582015-12-07 18:05:55 -08001572 }
1573
1574 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001575 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001576 policyMix);
1577 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001578 status = INVALID_OPERATION;
1579 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001580 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001581
Eric Laurentad2e7b92017-09-14 20:06:42 -07001582 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001583 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1584 : AUDIO_PORT_HANDLE_NONE;
1585
1586 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1587 *input, *inputType, *selectedDeviceId);
1588
Eric Laurent599c7582015-12-07 18:05:55 -08001589 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001590
1591error:
1592 mInputRoutes.removeRoute(session);
1593 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001594}
1595
1596
1597audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1598 String8 address,
1599 audio_session_t session,
1600 uid_t uid,
1601 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001602 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001603 audio_input_flags_t flags,
1604 AudioMix *policyMix)
1605{
1606 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1607 audio_source_t halInputSource = inputSource;
1608 bool isSoundTrigger = false;
1609
1610 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1611 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1612 if (index >= 0) {
1613 input = mSoundTriggerSessions.valueFor(session);
1614 isSoundTrigger = true;
1615 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1616 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1617 } else {
1618 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001619 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001620 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001621 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001622 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001623 }
1624
Andy Hungf129b032015-04-07 13:45:50 -07001625 // find a compatible input profile (not necessarily identical in parameters)
1626 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001627 // sampling rate and flags may be updated by getInputProfile
1628 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1629 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001630 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001631 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001632 audio_input_flags_t profileFlags = flags;
1633 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001634 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001635 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001636 profileSamplingRate, profileFormat, profileChannelMask,
1637 profileFlags);
1638 if (profile != 0) {
1639 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001640 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1641 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001642 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1643 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1644 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001645 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001646 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1647 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001648 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001651 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001652 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001653 if (samplingRate == 0) {
1654 samplingRate = profileSamplingRate;
1655 }
Eric Laurente552edb2014-03-10 17:42:56 -07001656
Eric Laurent322b4d22015-04-03 15:57:54 -07001657 if (profile->getModuleHandle() == 0) {
1658 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001659 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001660 }
1661
Eric Laurent599c7582015-12-07 18:05:55 -08001662 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001663 inputSource,
1664 config->format,
1665 samplingRate,
1666 config->channel_mask,
1667 flags,
1668 uid,
1669 isSoundTrigger,
1670 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001671
Eric Laurent74708e72017-04-07 17:13:42 -07001672// FIXME: disable concurrent capture until UI is ready
1673#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001674 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001675 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001676 for (size_t i = 0; i < mInputs.size(); i++) {
1677 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001678 // reuse input if:
1679 // - it shares the same profile
1680 // AND
1681 // - it is not a reroute submix input
1682 // AND
1683 // - it is: not used for sound trigger
1684 // OR
1685 // used for sound trigger and all clients use the same session ID
1686 //
1687 if ((profile == desc->mProfile) &&
1688 (isSoundTrigger == desc->isSoundTrigger()) &&
1689 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001690
1691 sp<AudioSession> as = desc->getAudioSession(session);
1692 if (as != 0) {
1693 // do not allow unmatching properties on same session
1694 if (as->matches(audioSession)) {
1695 as->changeOpenCount(1);
1696 } else {
1697 ALOGW("getInputForDevice() record with different attributes"
1698 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001699 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001700 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001701 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001702 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001703 }
Eric Laurentbb948092017-01-23 18:33:30 -08001704
Eric Laurent555530a2017-02-07 18:17:24 -08001705 // Reuse the already opened input stream on this profile if:
1706 // - the new capture source is background OR
1707 // - the path requested configurations match OR
1708 // - the new source priority is less than the highest source priority on this input
1709 // If the input stream cannot be reused, close it before opening a new stream
1710 // on the same profile for the new client so that the requested path configuration
1711 // can be selected.
1712 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001713 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001714 desc->mChannelMask != config->channel_mask ||
1715 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001716 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001717 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001718 reusedInputDesc = desc;
1719 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001720 } else {
1721 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001722 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1723 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001724 }
Eric Laurent599c7582015-12-07 18:05:55 -08001725 }
1726 }
Eric Laurent599c7582015-12-07 18:05:55 -08001727
Eric Laurent555530a2017-02-07 18:17:24 -08001728 if (reusedInputDesc != 0) {
1729 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1730 for (size_t j = 0; j < sessions.size(); j++) {
1731 audio_session_t currentSession = sessions.keyAt(j);
1732 stopInput(reusedInputDesc->mIoHandle, currentSession);
1733 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1734 }
1735 }
Eric Laurent74708e72017-04-07 17:13:42 -07001736#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001737
Eric Laurent3974e3b2017-12-07 17:58:43 -08001738 if (!profile->canOpenNewIo()) {
1739 return AUDIO_IO_HANDLE_NONE;
1740 }
1741
Eric Laurentfe231122017-11-17 17:48:06 -08001742 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001743
Eric Laurentfe231122017-11-17 17:48:06 -08001744 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1745 lConfig.sample_rate = profileSamplingRate;
1746 lConfig.channel_mask = profileChannelMask;
1747 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001748
Eric Laurent53b810e2017-12-10 17:25:10 -08001749 if (address == "") {
1750 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1751 // the inputs vector must be of size >= 1, but we don't want to crash here
1752 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1753 }
1754
Eric Laurentfe231122017-11-17 17:48:06 -08001755 status_t status = inputDesc->open(&lConfig, device, address,
1756 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001757
1758 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001759 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001760 (profileSamplingRate != lConfig.sample_rate) ||
1761 !audio_formats_match(profileFormat, lConfig.format) ||
1762 (profileChannelMask != lConfig.channel_mask)) {
1763 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001764 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001765 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001766 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001767 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001768 }
Eric Laurent599c7582015-12-07 18:05:55 -08001769 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001770 }
1771
Eric Laurentc722f302014-12-10 11:21:49 -08001772 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001773 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001774
Eric Laurent599c7582015-12-07 18:05:55 -08001775 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001776 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001777
Eric Laurent599c7582015-12-07 18:05:55 -08001778 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001779}
1780
Eric Laurentbb948092017-01-23 18:33:30 -08001781//static
1782bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1783{
1784 return (source == AUDIO_SOURCE_HOTWORD) ||
1785 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1786 (source == AUDIO_SOURCE_FM_TUNER);
1787}
1788
Eric Laurentfb66dd92016-01-28 18:32:03 -08001789bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1790 const sp<AudioSession>& audioSession)
1791{
1792 // Do not allow capture if an active voice call is using a software patch and
1793 // the call TX source device is on the same HW module.
1794 // FIXME: would be better to refine to only inputs whose profile connects to the
1795 // call TX device but this information is not in the audio patch
1796 if (mCallTxPatch != 0 &&
1797 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1798 return false;
1799 }
1800
1801 // starting concurrent capture is enabled if:
1802 // 1) capturing for re-routing
1803 // 2) capturing for HOTWORD source
1804 // 3) capturing for FM TUNER source
1805 // 3) All other active captures are either for re-routing or HOTWORD
1806
1807 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001808 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001809 return true;
1810 }
1811
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001812 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001813 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001814 !is_virtual_input_device(activeInput->mDevice)) {
1815 return false;
1816 }
1817 }
1818
1819 return true;
1820}
1821
Chris Thornton2b864642017-06-27 21:26:07 -07001822// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1823bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1824 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1825 bool soundTriggerSupportsConcurrentCapture = false;
1826 unsigned int numModules = 0;
1827 struct sound_trigger_module_descriptor* nModules = NULL;
1828
1829 status_t status = SoundTrigger::listModules(nModules, &numModules);
1830 if (status == NO_ERROR && numModules != 0) {
1831 nModules = (struct sound_trigger_module_descriptor*) calloc(
1832 numModules, sizeof(struct sound_trigger_module_descriptor));
1833 if (nModules == NULL) {
1834 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1835 // ram the next time this function is called.
1836 ALOGE("Failed to allocate buffer for module descriptors");
1837 return false;
1838 }
1839
1840 status = SoundTrigger::listModules(nModules, &numModules);
1841 if (status == NO_ERROR) {
1842 soundTriggerSupportsConcurrentCapture = true;
1843 for (size_t i = 0; i < numModules; ++i) {
1844 soundTriggerSupportsConcurrentCapture &=
1845 nModules[i].properties.concurrent_capture;
1846 }
1847 }
1848 free(nModules);
1849 }
1850 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1851 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1852 }
1853 return mSoundTriggerSupportsConcurrentCapture;
1854}
1855
Eric Laurentfb66dd92016-01-28 18:32:03 -08001856
Eric Laurent4dc68062014-07-28 17:26:49 -07001857status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001858 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001859 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001860 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001861{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001862
1863 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1864 input, session, silenced, *concurrency);
1865
Eric Laurentfb66dd92016-01-28 18:32:03 -08001866 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001867
Eric Laurente552edb2014-03-10 17:42:56 -07001868 ssize_t index = mInputs.indexOfKey(input);
1869 if (index < 0) {
1870 ALOGW("startInput() unknown input %d", input);
1871 return BAD_VALUE;
1872 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001873 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001874
Eric Laurent599c7582015-12-07 18:05:55 -08001875 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1876 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001877 ALOGW("startInput() unknown session %d on input %d", session, input);
1878 return BAD_VALUE;
1879 }
1880
Eric Laurent74708e72017-04-07 17:13:42 -07001881// FIXME: disable concurrent capture until UI is ready
1882#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001883 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1884 ALOGW("startInput(%d) failed: other input already started", input);
1885 return INVALID_OPERATION;
1886 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001887
Eric Laurentfb66dd92016-01-28 18:32:03 -08001888 if (isInCall()) {
1889 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1890 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001891 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001892 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001893 }
Eric Laurent74708e72017-04-07 17:13:42 -07001894#else
1895 if (!is_virtual_input_device(inputDesc->mDevice)) {
1896 if (mCallTxPatch != 0 &&
1897 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1898 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001899 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001900 return INVALID_OPERATION;
1901 }
1902
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001903 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001904
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001905 // If a UID is idle and records silence and another not silenced recording starts
1906 // from another UID (idle or active) we stop the current idle UID recording in
1907 // favor of the new one - "There can be only one" TM
1908 if (!silenced) {
1909 for (const auto& activeDesc : activeInputs) {
1910 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1911 activeDesc->getId() == inputDesc->getId()) {
1912 continue;
1913 }
1914
1915 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1916 true /*activeOnly*/);
1917 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1918 if (activeSession->isSilenced()) {
1919 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1920 audio_session_t activeSessionId = activeSession->session();
1921 stopInput(activeInput, activeSessionId);
1922 releaseInput(activeInput, activeSessionId);
1923 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1924 activeInputs = mInputs.getActiveInputs();
1925 }
1926 }
1927 }
1928
1929 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001930 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1931 activeDesc->getId() == inputDesc->getId()) {
1932 continue;
1933 }
1934
Eric Laurent74708e72017-04-07 17:13:42 -07001935 audio_source_t activeSource = activeDesc->inputSource(true);
1936 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1937 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1938 if (activeDesc->hasPreemptedSession(session)) {
1939 ALOGW("startInput(%d) failed for HOTWORD: "
1940 "other input %d already started for HOTWORD",
1941 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001942 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001943 return INVALID_OPERATION;
1944 }
1945 } else {
1946 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1947 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001948 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001949 return INVALID_OPERATION;
1950 }
1951 } else {
1952 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1953 ALOGW("startInput(%d) failed: other input %d already started",
1954 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001955 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001956 return INVALID_OPERATION;
1957 }
1958 }
1959 }
1960
Chris Thornton2b864642017-06-27 21:26:07 -07001961 // We only need to check if the sound trigger session supports concurrent capture if the
1962 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1963 // that's running.
1964 const bool allowConcurrentWithSoundTrigger =
1965 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1966
Eric Laurent74708e72017-04-07 17:13:42 -07001967 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001968 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001969 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1970 continue;
1971 }
1972
Eric Laurent74708e72017-04-07 17:13:42 -07001973 audio_source_t activeSource = activeDesc->inputSource(true);
1974 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1975 AudioSessionCollection activeSessions =
1976 activeDesc->getAudioSessions(true /*activeOnly*/);
1977 audio_session_t activeSession = activeSessions.keyAt(0);
1978 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1979 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001980 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001981 sessions.add(activeSession);
1982 inputDesc->setPreemptedSessions(sessions);
1983 stopInput(activeHandle, activeSession);
1984 releaseInput(activeHandle, activeSession);
1985 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1986 input, activeDesc->mIoHandle);
1987 }
1988 }
1989 }
1990#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001991
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001992 // Make sure we start with the correct silence state
1993 audioSession->setSilenced(silenced);
1994
Eric Laurent313d1e72016-01-29 09:56:57 -08001995 // increment activity count before calling getNewInputDevice() below as only active sessions
1996 // are considered for device selection
1997 audioSession->changeActiveCount(1);
1998
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001999 // Routing?
2000 mInputRoutes.incRouteActivity(session);
2001
Eric Laurent2157f5b2018-04-25 18:33:02 -07002002 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002003 // indicate active capture to sound trigger service if starting capture from a mic on
2004 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002005 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002006 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002007
Eric Laurent733ce942017-12-07 12:18:25 -08002008 status_t status = inputDesc->start();
2009 if (status != NO_ERROR) {
2010 mInputRoutes.decRouteActivity(session);
2011 audioSession->changeActiveCount(-1);
2012 return status;
2013 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002014
Eric Laurent733ce942017-12-07 12:18:25 -08002015 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002016 // if input maps to a dynamic policy with an activity listener, notify of state change
2017 if ((inputDesc->mPolicyMix != NULL)
2018 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2019 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2020 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002021 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002022
Eric Laurentf7c50102016-09-30 15:19:43 -07002023 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2024 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002025 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002026 SoundTrigger::setCaptureState(true);
2027 }
2028
2029 // automatically enable the remote submix output when input is started if not
2030 // used by a policy mix of type MIX_TYPE_RECORDERS
2031 // For remote submix (a virtual device), we open only one input per capture request.
2032 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2033 String8 address = String8("");
2034 if (inputDesc->mPolicyMix == NULL) {
2035 address = String8("0");
2036 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2037 address = inputDesc->mPolicyMix->mDeviceAddress;
2038 }
2039 if (address != "") {
2040 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2041 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2042 address, "remote-submix");
2043 }
Eric Laurentc722f302014-12-10 11:21:49 -08002044 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002045 }
Eric Laurente552edb2014-03-10 17:42:56 -07002046 }
2047
Eric Laurent599c7582015-12-07 18:05:55 -08002048 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002049
Eric Laurente552edb2014-03-10 17:42:56 -07002050 return NO_ERROR;
2051}
2052
Eric Laurent4dc68062014-07-28 17:26:49 -07002053status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2054 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002055{
2056 ALOGV("stopInput() input %d", input);
2057 ssize_t index = mInputs.indexOfKey(input);
2058 if (index < 0) {
2059 ALOGW("stopInput() unknown input %d", input);
2060 return BAD_VALUE;
2061 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002062 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurent599c7582015-12-07 18:05:55 -08002064 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002065 if (index < 0) {
2066 ALOGW("stopInput() unknown session %d on input %d", session, input);
2067 return BAD_VALUE;
2068 }
2069
Eric Laurent599c7582015-12-07 18:05:55 -08002070 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002071 ALOGW("stopInput() input %d already stopped", input);
2072 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002073 }
2074
Eric Laurent599c7582015-12-07 18:05:55 -08002075 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002076
2077 // Routing?
2078 mInputRoutes.decRouteActivity(session);
2079
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002080 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002081 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002082 if (inputDesc->isActive()) {
2083 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2084 } else {
2085 // if input maps to a dynamic policy with an activity listener, notify of state change
2086 if ((inputDesc->mPolicyMix != NULL)
2087 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2088 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2089 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002090 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002091
2092 // automatically disable the remote submix output when input is stopped if not
2093 // used by a policy mix of type MIX_TYPE_RECORDERS
2094 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2095 String8 address = String8("");
2096 if (inputDesc->mPolicyMix == NULL) {
2097 address = String8("0");
2098 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2099 address = inputDesc->mPolicyMix->mDeviceAddress;
2100 }
2101 if (address != "") {
2102 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2103 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2104 address, "remote-submix");
2105 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002106 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002107
Eric Laurentf7c50102016-09-30 15:19:43 -07002108 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002109 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002110
Eric Laurentf7c50102016-09-30 15:19:43 -07002111 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2112 // primary HW module
2113 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2114 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2115 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002116 SoundTrigger::setCaptureState(false);
2117 }
2118 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002119 }
Eric Laurente552edb2014-03-10 17:42:56 -07002120 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002121 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002122}
2123
Eric Laurent4dc68062014-07-28 17:26:49 -07002124void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2125 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002126{
2127 ALOGV("releaseInput() %d", input);
2128 ssize_t index = mInputs.indexOfKey(input);
2129 if (index < 0) {
2130 ALOGW("releaseInput() releasing unknown input %d", input);
2131 return;
2132 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002133
2134 // Routing
2135 mInputRoutes.removeRoute(session);
2136
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002137 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2138 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002139
Eric Laurent599c7582015-12-07 18:05:55 -08002140 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002141 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002142 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2143 return;
2144 }
Eric Laurent599c7582015-12-07 18:05:55 -08002145
2146 if (audioSession->openCount() == 0) {
2147 ALOGW("releaseInput() invalid open count %d on session %d",
2148 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002149 return;
2150 }
Eric Laurent599c7582015-12-07 18:05:55 -08002151
2152 if (audioSession->changeOpenCount(-1) == 0) {
2153 inputDesc->removeAudioSession(session);
2154 }
2155
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002156 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002157 ALOGV("releaseInput() exit > 0");
2158 return;
2159 }
2160
Eric Laurent05b90f82014-08-27 15:32:29 -07002161 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002162 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002163 ALOGV("releaseInput() exit");
2164}
2165
Eric Laurentd4692962014-05-05 18:13:44 -07002166void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002167 bool patchRemoved = false;
2168
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002169 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002170 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002171 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002172 if (patch_index >= 0) {
2173 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002174 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002175 mAudioPatches.removeItemsAt(patch_index);
2176 patchRemoved = true;
2177 }
Eric Laurentfe231122017-11-17 17:48:06 -08002178 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002179 }
jiabin829a00b2018-04-04 16:28:32 -07002180 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002181 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002182 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002183 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002184
2185 if (patchRemoved) {
2186 mpClientInterface->onAudioPatchListUpdate();
2187 }
Eric Laurentd4692962014-05-05 18:13:44 -07002188}
2189
Eric Laurente0720872014-03-11 09:30:41 -07002190void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002191 int indexMin,
2192 int indexMax)
2193{
2194 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002195 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002196
2197 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002198 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2199 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002200 continue;
2201 }
2202 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002203 }
Eric Laurente552edb2014-03-10 17:42:56 -07002204}
2205
Eric Laurente0720872014-03-11 09:30:41 -07002206status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002207 int index,
2208 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002209{
2210
Nadav Bar7c605f62017-12-25 00:01:52 +02002211 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2212 // app that has MODIFY_PHONE_STATE permission.
2213 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2214 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002215 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002216 return BAD_VALUE;
2217 }
2218 if (!audio_is_output_device(device)) {
2219 return BAD_VALUE;
2220 }
2221
2222 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002223 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002224
Eric Laurent1fd372e2016-04-06 14:23:53 -07002225 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002226 stream, device, index);
2227
Eric Laurent28d09f02016-03-08 10:43:05 -08002228 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002229 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2230 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002231 continue;
2232 }
2233 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2234 }
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Eric Laurent1fd372e2016-04-06 14:23:53 -07002236 // update volume on all outputs and streams matching the following:
2237 // - The requested stream (or a stream matching for volume control) is active on the output
2238 // - The device (or devices) selected by the strategy corresponding to this stream includes
2239 // the requested device
2240 // - For non default requested device, currently selected device on the output is either the
2241 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002242 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2243 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002244 status_t status = NO_ERROR;
2245 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2247 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002248 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2249 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002250 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002252 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2253 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002254 continue;
2255 }
Eric Laurent794fde22016-03-11 09:50:45 -08002256 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002257 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2258 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002259 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2260 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002261 continue;
2262 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002263 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002264 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002266 applyVolume = (curDevice & curStreamDevice) != 0;
2267 } else {
2268 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002269 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002270 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002271
Eric Laurente76f29c2016-09-14 17:17:53 -07002272 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002273 //FIXME: workaround for truncated touch sounds
2274 // delayed volume change for system stream to be removed when the problem is
2275 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002276 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002277 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2278 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002279 if (volStatus != NO_ERROR) {
2280 status = volStatus;
2281 }
2282 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002283 }
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
2285 return status;
2286}
2287
Eric Laurente0720872014-03-11 09:30:41 -07002288status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002289 int *index,
2290 audio_devices_t device)
2291{
2292 if (index == NULL) {
2293 return BAD_VALUE;
2294 }
2295 if (!audio_is_output_device(device)) {
2296 return BAD_VALUE;
2297 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002298 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002299 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002300 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002301 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2302 }
François Gaffiedfd74092015-03-19 12:10:59 +01002303 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002304
François Gaffied1ab2bd2015-12-02 18:20:06 +01002305 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002306 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2307 return NO_ERROR;
2308}
2309
Eric Laurent36829f92017-04-07 19:04:42 -07002310audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002311{
2312 // select one output among several suitable for global effects.
2313 // The priority is as follows:
2314 // 1: An offloaded output. If the effect ends up not being offloadable,
2315 // AudioFlinger will invalidate the track and the offloaded output
2316 // will be closed causing the effect to be moved to a PCM output.
2317 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002318 // 3: The primary output
2319 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002320
Eric Laurent3b73df72014-03-11 09:06:29 -07002321 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002322 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002323 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002324
Eric Laurent36829f92017-04-07 19:04:42 -07002325 if (outputs.size() == 0) {
2326 return AUDIO_IO_HANDLE_NONE;
2327 }
Eric Laurente552edb2014-03-10 17:42:56 -07002328
Eric Laurent36829f92017-04-07 19:04:42 -07002329 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2330 bool activeOnly = true;
2331
2332 while (output == AUDIO_IO_HANDLE_NONE) {
2333 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2334 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2335 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2336
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002337 for (audio_io_handle_t output : outputs) {
2338 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002339 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2340 continue;
2341 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002342 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2343 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002344 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002345 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002346 }
2347 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002348 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002349 }
2350 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002351 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002352 }
2353 }
2354 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2355 output = outputOffloaded;
2356 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2357 output = outputDeepBuffer;
2358 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2359 output = outputPrimary;
2360 } else {
2361 output = outputs[0];
2362 }
2363 activeOnly = false;
2364 }
2365
2366 if (output != mMusicEffectOutput) {
2367 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2368 mMusicEffectOutput = output;
2369 }
2370
2371 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002372 return output;
2373}
2374
Eric Laurent36829f92017-04-07 19:04:42 -07002375audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2376{
2377 return selectOutputForMusicEffects();
2378}
2379
Eric Laurente0720872014-03-11 09:30:41 -07002380status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002381 audio_io_handle_t io,
2382 uint32_t strategy,
2383 int session,
2384 int id)
2385{
2386 ssize_t index = mOutputs.indexOfKey(io);
2387 if (index < 0) {
2388 index = mInputs.indexOfKey(io);
2389 if (index < 0) {
2390 ALOGW("registerEffect() unknown io %d", io);
2391 return INVALID_OPERATION;
2392 }
2393 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002394 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002395}
2396
Eric Laurentc75307b2015-03-17 15:29:32 -07002397bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2398{
Eric Laurent28d09f02016-03-08 10:43:05 -08002399 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002400 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2401 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002402 continue;
2403 }
2404 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2405 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002406 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002407}
2408
2409bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2410{
2411 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2412}
2413
Eric Laurente0720872014-03-11 09:30:41 -07002414bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002415{
2416 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002417 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002418 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002419 return true;
2420 }
2421 }
2422 return false;
2423}
2424
Eric Laurent275e8e92014-11-30 15:14:47 -08002425// Register a list of custom mixes with their attributes and format.
2426// When a mix is registered, corresponding input and output profiles are
2427// added to the remote submix hw module. The profile contains only the
2428// parameters (sampling rate, format...) specified by the mix.
2429// The corresponding input remote submix device is also connected.
2430//
2431// When a remote submix device is connected, the address is checked to select the
2432// appropriate profile and the corresponding input or output stream is opened.
2433//
2434// When capture starts, getInputForAttr() will:
2435// - 1 look for a mix matching the address passed in attribtutes tags if any
2436// - 2 if none found, getDeviceForInputSource() will:
2437// - 2.1 look for a mix matching the attributes source
2438// - 2.2 if none found, default to device selection by policy rules
2439// At this time, the corresponding output remote submix device is also connected
2440// and active playback use cases can be transferred to this mix if needed when reconnecting
2441// after AudioTracks are invalidated
2442//
2443// When playback starts, getOutputForAttr() will:
2444// - 1 look for a mix matching the address passed in attribtutes tags if any
2445// - 2 if none found, look for a mix matching the attributes usage
2446// - 3 if none found, default to device and output selection by policy rules.
2447
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002448status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002449{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002450 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2451 status_t res = NO_ERROR;
2452
2453 sp<HwModule> rSubmixModule;
2454 // examine each mix's route type
2455 for (size_t i = 0; i < mixes.size(); i++) {
2456 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2457 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2458 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002459 break;
2460 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002462 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002463 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002464 rSubmixModule = mHwModules.getModuleFromName(
2465 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2466 if (rSubmixModule == 0) {
2467 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2468 i);
2469 res = INVALID_OPERATION;
2470 break;
2471 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002473
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002475
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002477 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002478 res = INVALID_OPERATION;
2479 break;
2480 }
2481 audio_config_t outputConfig = mixes[i].mFormat;
2482 audio_config_t inputConfig = mixes[i].mFormat;
2483 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2484 // stereo and let audio flinger do the channel conversion if needed.
2485 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2486 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2487 rSubmixModule->addOutputProfile(address, &outputConfig,
2488 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2489 rSubmixModule->addInputProfile(address, &inputConfig,
2490 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002491
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2493 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2494 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2495 address.string(), "remote-submix");
2496 } else {
2497 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2499 address.string(), "remote-submix");
2500 }
2501 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002502 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002503 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002504 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2505 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002507 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2509 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2510 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2511 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2512 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2513 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002514 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2515 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002516 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2517 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002518 } else {
2519 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520 }
2521 break;
2522 }
2523 }
2524
2525 if (res != NO_ERROR) {
2526 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 i, device, address.string());
2528 res = INVALID_OPERATION;
2529 break;
2530 } else if (!foundOutput) {
2531 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2532 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 res = INVALID_OPERATION;
2534 break;
2535 }
Eric Laurentc722f302014-12-10 11:21:49 -08002536 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002537 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002538 if (res != NO_ERROR) {
2539 unregisterPolicyMixes(mixes);
2540 }
2541 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002542}
2543
2544status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2545{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002546 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547 status_t res = NO_ERROR;
2548 sp<HwModule> rSubmixModule;
2549 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002550 for (const auto& mix : mixes) {
2551 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002552
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002554 rSubmixModule = mHwModules.getModuleFromName(
2555 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2556 if (rSubmixModule == 0) {
2557 res = INVALID_OPERATION;
2558 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002559 }
2560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002561
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002562 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002563
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2565 res = INVALID_OPERATION;
2566 continue;
2567 }
2568
2569 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2570 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2571 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2572 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2573 address.string(), "remote-submix");
2574 }
2575 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2576 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2577 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2578 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2579 address.string(), "remote-submix");
2580 }
2581 rSubmixModule->removeOutputProfile(address);
2582 rSubmixModule->removeInputProfile(address);
2583
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002584 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2585 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002586 res = INVALID_OPERATION;
2587 continue;
2588 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002589 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002590 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002591 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002592}
2593
Eric Laurente552edb2014-03-10 17:42:56 -07002594
Eric Laurente0720872014-03-11 09:30:41 -07002595status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002596{
Eric Laurente552edb2014-03-10 17:42:56 -07002597 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002598 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2599 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002600 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002601 std::string stateLiteral;
2602 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002603 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2604 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2605 "communications", "media", "record", "dock", "system",
2606 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2607 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2608 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2609 result.appendFormat(" Force use for %s: %d\n",
2610 forceUses[i], mEngine->getForceUse(i));
2611 }
2612 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2613 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2614 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002615 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002616
François Gaffie112b0af2015-11-19 16:13:25 +01002617 mAvailableOutputDevices.dump(fd, String8("Available output"));
2618 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002619 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002620 mOutputs.dump(fd);
2621 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002622 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002623 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002624 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002625 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002626
2627 return NO_ERROR;
2628}
2629
2630// This function checks for the parameters which can be offloaded.
2631// This can be enhanced depending on the capability of the DSP and policy
2632// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002633bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002634{
2635 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002636 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002637 offloadInfo.sample_rate, offloadInfo.channel_mask,
2638 offloadInfo.format,
2639 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2640 offloadInfo.has_video);
2641
Andy Hung2ddee192015-12-18 17:34:44 -08002642 if (mMasterMono) {
2643 return false; // no offloading if mono is set.
2644 }
2645
Eric Laurente552edb2014-03-10 17:42:56 -07002646 // Check if offload has been disabled
2647 char propValue[PROPERTY_VALUE_MAX];
2648 if (property_get("audio.offload.disable", propValue, "0")) {
2649 if (atoi(propValue) != 0) {
2650 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2651 return false;
2652 }
2653 }
2654
2655 // Check if stream type is music, then only allow offload as of now.
2656 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2657 {
2658 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2659 return false;
2660 }
2661
2662 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002663 const bool allowOffloadWithVideo =
2664 property_get_bool("audio.offload.video", false /* default_value */);
2665 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002666 ALOGV("isOffloadSupported: has_video == true, returning false");
2667 return false;
2668 }
2669
2670 //If duration is less than minimum value defined in property, return false
2671 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2672 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2673 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2674 return false;
2675 }
2676 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2677 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2678 return false;
2679 }
2680
2681 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2682 // creating an offloaded track and tearing it down immediately after start when audioflinger
2683 // detects there is an active non offloadable effect.
2684 // FIXME: We should check the audio session here but we do not have it in this context.
2685 // This may prevent offloading in rare situations where effects are left active by apps
2686 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002687 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002688 return false;
2689 }
2690
2691 // See if there is a profile to support this.
2692 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002693 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002694 offloadInfo.sample_rate,
2695 offloadInfo.format,
2696 offloadInfo.channel_mask,
2697 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002698 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2699 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002700}
2701
Eric Laurent6a94d692014-05-20 11:18:06 -07002702status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2703 audio_port_type_t type,
2704 unsigned int *num_ports,
2705 struct audio_port *ports,
2706 unsigned int *generation)
2707{
2708 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2709 generation == NULL) {
2710 return BAD_VALUE;
2711 }
2712 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2713 if (ports == NULL) {
2714 *num_ports = 0;
2715 }
2716
2717 size_t portsWritten = 0;
2718 size_t portsMax = *num_ports;
2719 *num_ports = 0;
2720 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002721 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2722 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002723 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002724 for (const auto& dev : mAvailableOutputDevices) {
2725 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002726 continue;
2727 }
2728 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002729 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002730 }
2731 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002733 }
2734 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002735 for (const auto& dev : mAvailableInputDevices) {
2736 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002737 continue;
2738 }
2739 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002740 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002741 }
2742 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002744 }
2745 }
2746 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2747 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2748 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2749 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2750 }
2751 *num_ports += mInputs.size();
2752 }
2753 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002754 size_t numOutputs = 0;
2755 for (size_t i = 0; i < mOutputs.size(); i++) {
2756 if (!mOutputs[i]->isDuplicated()) {
2757 numOutputs++;
2758 if (portsWritten < portsMax) {
2759 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2760 }
2761 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002762 }
Eric Laurent84c70242014-06-23 08:46:27 -07002763 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002764 }
2765 }
2766 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002767 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002768 return NO_ERROR;
2769}
2770
2771status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2772{
2773 return NO_ERROR;
2774}
2775
Eric Laurent6a94d692014-05-20 11:18:06 -07002776status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2777 audio_patch_handle_t *handle,
2778 uid_t uid)
2779{
2780 ALOGV("createAudioPatch()");
2781
2782 if (handle == NULL || patch == NULL) {
2783 return BAD_VALUE;
2784 }
2785 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2786
Eric Laurent874c42872014-08-08 15:13:39 -07002787 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2788 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2789 return BAD_VALUE;
2790 }
2791 // only one source per audio patch supported for now
2792 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002793 return INVALID_OPERATION;
2794 }
Eric Laurent874c42872014-08-08 15:13:39 -07002795
2796 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002797 return INVALID_OPERATION;
2798 }
Eric Laurent874c42872014-08-08 15:13:39 -07002799 for (size_t i = 0; i < patch->num_sinks; i++) {
2800 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2801 return INVALID_OPERATION;
2802 }
2803 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002804
2805 sp<AudioPatch> patchDesc;
2806 ssize_t index = mAudioPatches.indexOfKey(*handle);
2807
Eric Laurent6a94d692014-05-20 11:18:06 -07002808 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2809 patch->sources[0].role,
2810 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002811#if LOG_NDEBUG == 0
2812 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002813 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002814 patch->sinks[i].role,
2815 patch->sinks[i].type);
2816 }
2817#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002818
2819 if (index >= 0) {
2820 patchDesc = mAudioPatches.valueAt(index);
2821 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2822 mUidCached, patchDesc->mUid, uid);
2823 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2824 return INVALID_OPERATION;
2825 }
2826 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002827 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 }
2829
2830 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002831 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 if (outputDesc == NULL) {
2833 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2834 return BAD_VALUE;
2835 }
Eric Laurent84c70242014-06-23 08:46:27 -07002836 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2837 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002838 if (patchDesc != 0) {
2839 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2840 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2841 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2842 return BAD_VALUE;
2843 }
2844 }
Eric Laurent874c42872014-08-08 15:13:39 -07002845 DeviceVector devices;
2846 for (size_t i = 0; i < patch->num_sinks; i++) {
2847 // Only support mix to devices connection
2848 // TODO add support for mix to mix connection
2849 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2850 ALOGV("createAudioPatch() source mix but sink is not a device");
2851 return INVALID_OPERATION;
2852 }
2853 sp<DeviceDescriptor> devDesc =
2854 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2855 if (devDesc == 0) {
2856 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2857 return BAD_VALUE;
2858 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002859
François Gaffie53615e22015-03-19 09:24:12 +01002860 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002861 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002862 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002863 NULL, // updatedSamplingRate
2864 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002865 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002866 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002867 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002868 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002869 ALOGV("createAudioPatch() profile not supported for device %08x",
2870 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002871 return INVALID_OPERATION;
2872 }
2873 devices.add(devDesc);
2874 }
2875 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002876 return INVALID_OPERATION;
2877 }
Eric Laurent874c42872014-08-08 15:13:39 -07002878
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 // TODO: reconfigure output format and channels here
2880 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002881 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002882 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002883 index = mAudioPatches.indexOfKey(*handle);
2884 if (index >= 0) {
2885 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2886 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2887 }
2888 patchDesc = mAudioPatches.valueAt(index);
2889 patchDesc->mUid = uid;
2890 ALOGV("createAudioPatch() success");
2891 } else {
2892 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2893 return INVALID_OPERATION;
2894 }
2895 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2896 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2897 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002898 // only one sink supported when connecting an input device to a mix
2899 if (patch->num_sinks > 1) {
2900 return INVALID_OPERATION;
2901 }
François Gaffie53615e22015-03-19 09:24:12 +01002902 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 if (inputDesc == NULL) {
2904 return BAD_VALUE;
2905 }
2906 if (patchDesc != 0) {
2907 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2908 return BAD_VALUE;
2909 }
2910 }
2911 sp<DeviceDescriptor> devDesc =
2912 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2913 if (devDesc == 0) {
2914 return BAD_VALUE;
2915 }
2916
François Gaffie53615e22015-03-19 09:24:12 +01002917 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002918 devDesc->mAddress,
2919 patch->sinks[0].sample_rate,
2920 NULL, /*updatedSampleRate*/
2921 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002922 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002923 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002924 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002925 // FIXME for the parameter type,
2926 // and the NONE
2927 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002928 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 return INVALID_OPERATION;
2930 }
2931 // TODO: reconfigure output format and channels here
2932 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002933 devDesc->type(), inputDesc->mIoHandle);
2934 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002935 index = mAudioPatches.indexOfKey(*handle);
2936 if (index >= 0) {
2937 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2938 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2939 }
2940 patchDesc = mAudioPatches.valueAt(index);
2941 patchDesc->mUid = uid;
2942 ALOGV("createAudioPatch() success");
2943 } else {
2944 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2945 return INVALID_OPERATION;
2946 }
2947 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2948 // device to device connection
2949 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002950 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002951 return BAD_VALUE;
2952 }
2953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 sp<DeviceDescriptor> srcDeviceDesc =
2955 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002956 if (srcDeviceDesc == 0) {
2957 return BAD_VALUE;
2958 }
Eric Laurent874c42872014-08-08 15:13:39 -07002959
Eric Laurent6a94d692014-05-20 11:18:06 -07002960 //update source and sink with our own data as the data passed in the patch may
2961 // be incomplete.
2962 struct audio_patch newPatch = *patch;
2963 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002964
Eric Laurent874c42872014-08-08 15:13:39 -07002965 for (size_t i = 0; i < patch->num_sinks; i++) {
2966 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2967 ALOGV("createAudioPatch() source device but one sink is not a device");
2968 return INVALID_OPERATION;
2969 }
2970
2971 sp<DeviceDescriptor> sinkDeviceDesc =
2972 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2973 if (sinkDeviceDesc == 0) {
2974 return BAD_VALUE;
2975 }
2976 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2977
Eric Laurent3bcf8592015-04-03 12:13:24 -07002978 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002979 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07002980 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002981 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002982 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002983 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002984 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002985 return INVALID_OPERATION;
2986 }
Eric Laurent874c42872014-08-08 15:13:39 -07002987 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002988 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002989 // if the sink device is reachable via an opened output stream, request to go via
2990 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002991 audio_io_handle_t output = selectOutput(outputs,
2992 AUDIO_OUTPUT_FLAG_NONE,
2993 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002994 if (output != AUDIO_IO_HANDLE_NONE) {
2995 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2996 if (outputDesc->isDuplicated()) {
2997 return INVALID_OPERATION;
2998 }
2999 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003000 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003001 newPatch.num_sources = 2;
3002 }
Eric Laurent83b88082014-06-20 18:31:16 -07003003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003004 }
3005 // TODO: check from routing capabilities in config file and other conflicting patches
3006
Mikhail Naganovdc769682018-05-04 15:34:08 -07003007 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3008 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3010 status);
3011 return INVALID_OPERATION;
3012 }
3013 } else {
3014 return BAD_VALUE;
3015 }
3016 } else {
3017 return BAD_VALUE;
3018 }
3019 return NO_ERROR;
3020}
3021
3022status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3023 uid_t uid)
3024{
3025 ALOGV("releaseAudioPatch() patch %d", handle);
3026
3027 ssize_t index = mAudioPatches.indexOfKey(handle);
3028
3029 if (index < 0) {
3030 return BAD_VALUE;
3031 }
3032 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3033 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3034 mUidCached, patchDesc->mUid, uid);
3035 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3036 return INVALID_OPERATION;
3037 }
3038
3039 struct audio_patch *patch = &patchDesc->mPatch;
3040 patchDesc->mUid = mUidCached;
3041 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003043 if (outputDesc == NULL) {
3044 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3045 return BAD_VALUE;
3046 }
3047
Eric Laurentc75307b2015-03-17 15:29:32 -07003048 setOutputDevice(outputDesc,
3049 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 true,
3051 0,
3052 NULL);
3053 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3054 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003055 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003056 if (inputDesc == NULL) {
3057 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3058 return BAD_VALUE;
3059 }
3060 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003061 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003062 true,
3063 NULL);
3064 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003065 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3066 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3067 status, patchDesc->mAfPatchHandle);
3068 removeAudioPatch(patchDesc->mHandle);
3069 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003070 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003071 } else {
3072 return BAD_VALUE;
3073 }
3074 } else {
3075 return BAD_VALUE;
3076 }
3077 return NO_ERROR;
3078}
3079
3080status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3081 struct audio_patch *patches,
3082 unsigned int *generation)
3083{
François Gaffie53615e22015-03-19 09:24:12 +01003084 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 return BAD_VALUE;
3086 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003087 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003088 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003089}
3090
Eric Laurente1715a42014-05-20 11:30:42 -07003091status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003092{
Eric Laurente1715a42014-05-20 11:30:42 -07003093 ALOGV("setAudioPortConfig()");
3094
3095 if (config == NULL) {
3096 return BAD_VALUE;
3097 }
3098 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3099 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003100 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3101 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003102 }
3103
Eric Laurenta121f902014-06-03 13:32:54 -07003104 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003105 if (config->type == AUDIO_PORT_TYPE_MIX) {
3106 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003107 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003108 if (outputDesc == NULL) {
3109 return BAD_VALUE;
3110 }
Eric Laurent84c70242014-06-23 08:46:27 -07003111 ALOG_ASSERT(!outputDesc->isDuplicated(),
3112 "setAudioPortConfig() called on duplicated output %d",
3113 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003114 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003115 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003116 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003117 if (inputDesc == NULL) {
3118 return BAD_VALUE;
3119 }
Eric Laurenta121f902014-06-03 13:32:54 -07003120 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003121 } else {
3122 return BAD_VALUE;
3123 }
3124 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3125 sp<DeviceDescriptor> deviceDesc;
3126 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3127 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3128 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3129 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3130 } else {
3131 return BAD_VALUE;
3132 }
3133 if (deviceDesc == NULL) {
3134 return BAD_VALUE;
3135 }
Eric Laurenta121f902014-06-03 13:32:54 -07003136 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003137 } else {
3138 return BAD_VALUE;
3139 }
3140
Eric Laurenta121f902014-06-03 13:32:54 -07003141 struct audio_port_config backupConfig;
3142 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3143 if (status == NO_ERROR) {
3144 struct audio_port_config newConfig;
3145 audioPortConfig->toAudioPortConfig(&newConfig, config);
3146 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003147 }
Eric Laurenta121f902014-06-03 13:32:54 -07003148 if (status != NO_ERROR) {
3149 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003150 }
Eric Laurente1715a42014-05-20 11:30:42 -07003151
3152 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003153}
3154
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003155void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3156{
Eric Laurentd60560a2015-04-10 11:31:20 -07003157 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003158 clearAudioPatches(uid);
3159 clearSessionRoutes(uid);
3160}
3161
Eric Laurent6a94d692014-05-20 11:18:06 -07003162void AudioPolicyManager::clearAudioPatches(uid_t uid)
3163{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003164 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3166 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003167 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003168 }
3169 }
3170}
3171
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003172void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3173 audio_io_handle_t ouptutToSkip)
3174{
3175 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3176 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3177 for (size_t j = 0; j < mOutputs.size(); j++) {
3178 if (mOutputs.keyAt(j) == ouptutToSkip) {
3179 continue;
3180 }
3181 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3182 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3183 continue;
3184 }
3185 // If the default device for this strategy is on another output mix,
3186 // invalidate all tracks in this strategy to force re connection.
3187 // Otherwise select new device on the output mix.
3188 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003189 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003190 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3191 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3192 }
3193 }
3194 } else {
3195 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3196 setOutputDevice(outputDesc, newDevice, false);
3197 }
3198 }
3199}
3200
3201void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3202{
3203 // remove output routes associated with this uid
3204 SortedVector<routing_strategy> affectedStrategies;
3205 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3206 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3207 if (route->mUid == uid) {
3208 mOutputRoutes.removeItemsAt(i);
3209 if (route->mDeviceDescriptor != 0) {
3210 affectedStrategies.add(getStrategy(route->mStreamType));
3211 }
3212 }
3213 }
3214 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003215 for (const auto& strategy : affectedStrategies) {
3216 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003217 }
3218
3219 // remove input routes associated with this uid
3220 SortedVector<audio_source_t> affectedSources;
3221 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3222 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3223 if (route->mUid == uid) {
3224 mInputRoutes.removeItemsAt(i);
3225 if (route->mDeviceDescriptor != 0) {
3226 affectedSources.add(route->mSource);
3227 }
3228 }
3229 }
3230 // reroute inputs if necessary
3231 SortedVector<audio_io_handle_t> inputsToClose;
3232 for (size_t i = 0; i < mInputs.size(); i++) {
3233 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003234 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003235 inputsToClose.add(inputDesc->mIoHandle);
3236 }
3237 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003238 for (const auto& input : inputsToClose) {
3239 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003240 }
3241}
3242
Eric Laurentd60560a2015-04-10 11:31:20 -07003243void AudioPolicyManager::clearAudioSources(uid_t uid)
3244{
3245 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3246 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3247 if (sourceDesc->mUid == uid) {
3248 stopAudioSource(mAudioSources.keyAt(i));
3249 }
3250 }
3251}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003252
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003253status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3254 audio_io_handle_t *ioHandle,
3255 audio_devices_t *device)
3256{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003257 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3258 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003259 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003260
François Gaffiedf372692015-03-19 10:43:27 +01003261 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003262}
3263
Eric Laurentd60560a2015-04-10 11:31:20 -07003264status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3265 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003266 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003267 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003268{
Eric Laurentd60560a2015-04-10 11:31:20 -07003269 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3270 if (source == NULL || attributes == NULL || handle == NULL) {
3271 return BAD_VALUE;
3272 }
3273
Glenn Kasten559d4392016-03-29 13:42:57 -07003274 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003275
3276 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3277 source->type != AUDIO_PORT_TYPE_DEVICE) {
3278 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3279 return INVALID_OPERATION;
3280 }
3281
3282 sp<DeviceDescriptor> srcDeviceDesc =
3283 mAvailableInputDevices.getDevice(source->ext.device.type,
3284 String8(source->ext.device.address));
3285 if (srcDeviceDesc == 0) {
3286 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3287 return BAD_VALUE;
3288 }
3289 sp<AudioSourceDescriptor> sourceDesc =
3290 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3291
3292 struct audio_patch dummyPatch;
3293 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3294 sourceDesc->mPatchDesc = patchDesc;
3295
3296 status_t status = connectAudioSource(sourceDesc);
3297 if (status == NO_ERROR) {
3298 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3299 *handle = sourceDesc->getHandle();
3300 }
3301 return status;
3302}
3303
3304status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3305{
3306 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3307
3308 // make sure we only have one patch per source.
3309 disconnectAudioSource(sourceDesc);
3310
3311 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003312 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003313 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3314
3315 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3316 sp<DeviceDescriptor> sinkDeviceDesc =
3317 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3318
3319 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003320
3321 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3322 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003323 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003324 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3325 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3326 // create patch between src device and output device
3327 // create Hwoutput and add to mHwOutputs
3328 } else {
3329 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3330 audio_io_handle_t output =
3331 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3332 if (output == AUDIO_IO_HANDLE_NONE) {
3333 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3334 return INVALID_OPERATION;
3335 }
3336 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3337 if (outputDesc->isDuplicated()) {
3338 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3339 return INVALID_OPERATION;
3340 }
Eric Laurent733ce942017-12-07 12:18:25 -08003341 status_t status = outputDesc->start();
3342 if (status != NO_ERROR) {
3343 return status;
3344 }
3345
Eric Laurentd60560a2015-04-10 11:31:20 -07003346 // create a special patch with no sink and two sources:
3347 // - the second source indicates to PatchPanel through which output mix this patch should
3348 // be connected as well as the stream type for volume control
3349 // - the sink is defined by whatever output device is currently selected for the output
3350 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003351 PatchBuilder patchBuilder;
3352 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3353 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003354 &afPatchHandle,
3355 0);
3356 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3357 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003358 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003359 if (status != NO_ERROR) {
3360 ALOGW("%s patch panel could not connect device patch, error %d",
3361 __FUNCTION__, status);
3362 return INVALID_OPERATION;
3363 }
3364 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003365 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003366
3367 if (status != NO_ERROR) {
3368 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3369 return status;
3370 }
3371 sourceDesc->mSwOutput = outputDesc;
3372 if (delayMs != 0) {
3373 usleep(delayMs * 1000);
3374 }
3375 }
3376
3377 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3378 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3379
3380 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003381}
3382
Glenn Kasten559d4392016-03-29 13:42:57 -07003383status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003384{
Eric Laurentd60560a2015-04-10 11:31:20 -07003385 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3386 ALOGV("%s handle %d", __FUNCTION__, handle);
3387 if (sourceDesc == 0) {
3388 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3389 return BAD_VALUE;
3390 }
3391 status_t status = disconnectAudioSource(sourceDesc);
3392
3393 mAudioSources.removeItem(handle);
3394 return status;
3395}
3396
Andy Hung2ddee192015-12-18 17:34:44 -08003397status_t AudioPolicyManager::setMasterMono(bool mono)
3398{
3399 if (mMasterMono == mono) {
3400 return NO_ERROR;
3401 }
3402 mMasterMono = mono;
3403 // if enabling mono we close all offloaded devices, which will invalidate the
3404 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3405 // for recreating the new AudioTrack as non-offloaded PCM.
3406 //
3407 // If disabling mono, we leave all tracks as is: we don't know which clients
3408 // and tracks are able to be recreated as offloaded. The next "song" should
3409 // play back offloaded.
3410 if (mMasterMono) {
3411 Vector<audio_io_handle_t> offloaded;
3412 for (size_t i = 0; i < mOutputs.size(); ++i) {
3413 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3414 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3415 offloaded.push(desc->mIoHandle);
3416 }
3417 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003418 for (const auto& handle : offloaded) {
3419 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003420 }
3421 }
3422 // update master mono for all remaining outputs
3423 for (size_t i = 0; i < mOutputs.size(); ++i) {
3424 updateMono(mOutputs.keyAt(i));
3425 }
3426 return NO_ERROR;
3427}
3428
3429status_t AudioPolicyManager::getMasterMono(bool *mono)
3430{
3431 *mono = mMasterMono;
3432 return NO_ERROR;
3433}
3434
Eric Laurentac9cef52017-06-09 15:46:26 -07003435float AudioPolicyManager::getStreamVolumeDB(
3436 audio_stream_type_t stream, int index, audio_devices_t device)
3437{
3438 return computeVolume(stream, index, device);
3439}
3440
jiabin81772902018-04-02 17:52:27 -07003441status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3442 FormatVector& formats) {
3443 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3444 return BAD_VALUE;
3445 }
3446 String8 reply;
3447 reply = mpClientInterface->getParameters(
3448 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3449 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3450 AudioParameter repliedParameters(reply);
3451 if (repliedParameters.get(
3452 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3453 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3454 return BAD_VALUE;
3455 }
3456 for (auto format : formatsFromString(reply.string())) {
3457 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3458 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3459 if (format == AAC_FORMATS[i]) {
3460 format = AUDIO_FORMAT_AAC_LC;
3461 break;
3462 }
3463 }
3464 bool exist = false;
3465 for (size_t i = 0; i < formats.size(); i++) {
3466 if (format == formats[i]) {
3467 exist = true;
3468 break;
3469 }
3470 }
3471 bool isSurroundFormat = false;
3472 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3473 if (SURROUND_FORMATS[i] == format) {
3474 isSurroundFormat = true;
3475 break;
3476 }
3477 }
3478 if (!exist && isSurroundFormat) {
3479 formats.add(format);
3480 }
3481 }
3482 return NO_ERROR;
3483}
3484
3485status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3486 audio_format_t *surroundFormats,
3487 bool *surroundFormatsEnabled,
3488 bool reported)
3489{
3490 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3491 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3492 return BAD_VALUE;
3493 }
3494 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3495 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3496
3497 // Only return value if there is HDMI output.
3498 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3499 return INVALID_OPERATION;
3500 }
3501
3502 size_t formatsWritten = 0;
3503 size_t formatsMax = *numSurroundFormats;
3504 *numSurroundFormats = 0;
3505 FormatVector formats;
3506 if (reported) {
3507 // Only get surround formats which are reported by device.
3508 // First list already open outputs that can be routed to this device
3509 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3510 SortedVector<audio_io_handle_t> outputs;
3511 bool reportedFormatFound = false;
3512 status_t status;
3513 sp<SwAudioOutputDescriptor> desc;
3514 for (size_t i = 0; i < mOutputs.size(); i++) {
3515 desc = mOutputs.valueAt(i);
3516 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3517 outputs.add(mOutputs.keyAt(i));
3518 }
3519 }
3520 // Open an output to query dynamic parameters.
3521 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3522 AUDIO_DEVICE_OUT_HDMI);
3523 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3524 String8 address = hdmiOutputDevices[i]->mAddress;
3525 for (const auto& hwModule : mHwModules) {
3526 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3527 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3528 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3529 profile->supportDeviceAddress(address)) {
3530 size_t j;
3531 for (j = 0; j < outputs.size(); j++) {
3532 desc = mOutputs.valueFor(outputs.itemAt(j));
3533 if (!desc->isDuplicated() && desc->mProfile == profile) {
3534 break;
3535 }
3536 }
3537 if (j != outputs.size()) {
3538 status = getSupportedFormats(outputs.itemAt(j), formats);
3539 reportedFormatFound |= (status == NO_ERROR);
3540 continue;
3541 }
3542
3543 if (!profile->canOpenNewIo()) {
3544 ALOGW("Max Output number %u already opened for this profile %s",
3545 profile->maxOpenCount, profile->getTagName().c_str());
3546 continue;
3547 }
3548
3549 ALOGV("opening output for device %08x with params %s profile %p name %s",
3550 device, address.string(), profile.get(), profile->getName().string());
3551 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3552 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3553 status_t status = desc->open(nullptr, device, address,
3554 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3555 &output);
3556
3557 if (status == NO_ERROR) {
3558 status = getSupportedFormats(output, formats);
3559 reportedFormatFound |= (status == NO_ERROR);
3560 desc->close();
3561 output = AUDIO_IO_HANDLE_NONE;
3562 }
3563 }
3564 }
3565 }
3566 }
3567
3568 if (!reportedFormatFound) {
3569 return UNKNOWN_ERROR;
3570 }
3571 } else {
3572 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3573 formats.add(SURROUND_FORMATS[i]);
3574 }
3575 }
3576 for (size_t i = 0; i < formats.size(); i++) {
3577 if (formatsWritten < formatsMax) {
3578 surroundFormats[formatsWritten] = formats[i];
3579 bool formatEnabled = false;
3580 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3581 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3582 formatEnabled =
3583 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3584 break;
3585 }
3586 } else {
3587 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3588 }
3589 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3590 }
3591 (*numSurroundFormats)++;
3592 }
3593 return NO_ERROR;
3594}
3595
3596status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3597{
3598 // Check if audio format is a surround formats.
3599 bool isSurroundFormat = false;
3600 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3601 if (audioFormat == SURROUND_FORMATS[i]) {
3602 isSurroundFormat = true;
3603 break;
3604 }
3605 }
3606 if (!isSurroundFormat) {
3607 return BAD_VALUE;
3608 }
3609
3610 // Should only be called when MANUAL.
3611 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3612 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3613 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3614 return INVALID_OPERATION;
3615 }
3616
3617 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3618 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3619 return NO_ERROR;
3620 }
3621
3622 // The operation is valid only when there is HDMI output available.
3623 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3624 return INVALID_OPERATION;
3625 }
3626
3627 if (enabled) {
3628 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3629 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3630 mSurroundFormats.insert(AAC_FORMATS[i]);
3631 }
3632 } else {
3633 mSurroundFormats.insert(audioFormat);
3634 }
3635 } else {
3636 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3637 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3638 mSurroundFormats.erase(AAC_FORMATS[i]);
3639 }
3640 } else {
3641 mSurroundFormats.erase(audioFormat);
3642 }
3643 }
3644
3645 sp<SwAudioOutputDescriptor> outputDesc;
3646 bool profileUpdated = false;
3647 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3648 AUDIO_DEVICE_OUT_HDMI);
3649 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3650 // Simulate reconnection to update enabled surround sound formats.
3651 String8 address = hdmiOutputDevices[i]->mAddress;
3652 String8 name = hdmiOutputDevices[i]->getName();
3653 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3654 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3655 address.c_str(),
3656 name.c_str());
3657 if (status != NO_ERROR) {
3658 continue;
3659 }
3660 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3661 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3662 address.c_str(),
3663 name.c_str());
3664 profileUpdated |= (status == NO_ERROR);
3665 }
3666 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3667 AUDIO_DEVICE_IN_HDMI);
3668 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3669 // Simulate reconnection to update enabled surround sound formats.
3670 String8 address = hdmiInputDevices[i]->mAddress;
3671 String8 name = hdmiInputDevices[i]->getName();
3672 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3673 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3674 address.c_str(),
3675 name.c_str());
3676 if (status != NO_ERROR) {
3677 continue;
3678 }
3679 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3680 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3681 address.c_str(),
3682 name.c_str());
3683 profileUpdated |= (status == NO_ERROR);
3684 }
3685
3686 // Undo the surround formats change due to no audio profiles updated.
3687 if (!profileUpdated) {
3688 if (enabled) {
3689 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3690 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3691 mSurroundFormats.erase(AAC_FORMATS[i]);
3692 }
3693 } else {
3694 mSurroundFormats.erase(audioFormat);
3695 }
3696 } else {
3697 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3698 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3699 mSurroundFormats.insert(AAC_FORMATS[i]);
3700 }
3701 } else {
3702 mSurroundFormats.insert(audioFormat);
3703 }
3704 }
3705 }
3706
3707 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3708}
3709
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003710void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3711{
3712 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3713
3714 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3715 for (size_t i = 0; i < activeInputs.size(); i++) {
3716 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3717 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3718 for (size_t j = 0; j < activeSessions.size(); j++) {
3719 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3720 if (activeSession->uid() == uid) {
3721 activeSession->setSilenced(silenced);
3722 }
3723 }
3724 }
3725}
3726
Eric Laurentd60560a2015-04-10 11:31:20 -07003727status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3728{
3729 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3730
3731 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3732 if (patchDesc == 0) {
3733 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3734 sourceDesc->mPatchDesc->mHandle);
3735 return BAD_VALUE;
3736 }
3737 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3738
Eric Laurent28d09f02016-03-08 10:43:05 -08003739 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003740 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3741 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003742 status_t status = stopSource(swOutputDesc, stream, false);
3743 if (status == NO_ERROR) {
3744 swOutputDesc->stop();
3745 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003746 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3747 } else {
3748 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3749 if (hwOutputDesc != 0) {
3750 // release patch between src device and output device
3751 // close Hwoutput and remove from mHwOutputs
3752 } else {
3753 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3754 }
3755 }
3756 return NO_ERROR;
3757}
3758
3759sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3760 audio_io_handle_t output, routing_strategy strategy)
3761{
3762 sp<AudioSourceDescriptor> source;
3763 for (size_t i = 0; i < mAudioSources.size(); i++) {
3764 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3765 routing_strategy sourceStrategy =
3766 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3767 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3768 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3769 source = sourceDesc;
3770 break;
3771 }
3772 }
3773 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003774}
3775
Eric Laurente552edb2014-03-10 17:42:56 -07003776// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003777// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003778// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003779uint32_t AudioPolicyManager::nextAudioPortGeneration()
3780{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003781 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003782}
3783
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003784#ifdef USE_XML_AUDIO_POLICY_CONF
3785// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3786static const char *kConfigLocationList[] =
3787 {"/odm/etc", "/vendor/etc", "/system/etc"};
3788static const int kConfigLocationListSize =
3789 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3790
3791static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3792 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003793 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003794 status_t ret;
3795
Petri Gyntherf497f292018-04-17 18:46:10 -07003796 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3797 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3798 // A2DP offload supported but disabled: try to use special XML file
3799 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3800 }
3801 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3802
3803 for (const char* fileName : fileNames) {
3804 for (int i = 0; i < kConfigLocationListSize; i++) {
3805 PolicySerializer serializer;
3806 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3807 "%s/%s", kConfigLocationList[i], fileName);
3808 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3809 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003810 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003811 return ret;
3812 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003813 }
3814 }
3815 return ret;
3816}
3817#endif
3818
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003819AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3820 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003821 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003822 mUidCached(getuid()),
3823 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003824 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003825 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003826#ifdef USE_XML_AUDIO_POLICY_CONF
3827 mVolumeCurves(new VolumeCurvesCollection()),
3828 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003829 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003830#else
3831 mVolumeCurves(new StreamDescriptorCollection()),
3832 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3833 mDefaultOutputDevice),
3834#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003835 mAudioPortGeneration(1),
3836 mBeaconMuteRefCount(0),
3837 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003838 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003839 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003840 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003841 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3842 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003843{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003844}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003845
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003846AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3847 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3848{
3849 loadConfig();
3850 initialize();
3851}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003852
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003853void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003854#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003856#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003857 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3858 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003859#endif
3860 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003862 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003863}
3864
3865status_t AudioPolicyManager::initialize() {
3866 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003867
3868 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003869 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3870 if (!engineInstance) {
3871 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003872 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003873 }
3874 // Retrieve the Policy Manager Interface
3875 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3876 if (mEngine == NULL) {
3877 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003878 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003879 }
3880 mEngine->setObserver(this);
3881 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003882 if (status != NO_ERROR) {
3883 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3884 return status;
3885 }
François Gaffie2110e042015-03-24 08:41:51 +01003886
Eric Laurent3a4311c2014-03-17 12:00:47 -07003887 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003888 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003889 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3890 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003891 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003892 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003893 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3894 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003895 continue;
3896 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003897 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003898 // open all output streams needed to access attached devices
3899 // except for direct output streams that are only opened when they are actually
3900 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003901 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003902 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003903 if (!outProfile->canOpenNewIo()) {
3904 ALOGE("Invalid Output profile max open count %u for profile %s",
3905 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3906 continue;
3907 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003908 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003909 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003910 continue;
3911 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003912 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003913 mTtsOutputAvailable = true;
3914 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003915
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003916 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003917 continue;
3918 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003919 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003920 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3921 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003922 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003923 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003924 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003925 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003926 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003927 if ((profileType & outputDeviceTypes) == 0) {
3928 continue;
3929 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003930 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3931 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003932 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3933 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3934 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3935 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003936 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003937 status_t status = outputDesc->open(nullptr, profileType, address,
3938 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003939
3940 if (status != NO_ERROR) {
3941 ALOGW("Cannot open output stream for device %08x on hw module %s",
3942 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003943 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003944 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003945 for (const auto& dev : supportedDevices) {
3946 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003947 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003948 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003949 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003950 }
3951 }
3952 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003953 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003954 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003955 }
3956 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003957 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003958 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003959 true,
3960 0,
3961 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003962 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 }
Eric Laurente552edb2014-03-10 17:42:56 -07003964 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003965 // open input streams needed to access attached devices to validate
3966 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003967 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003968 if (!inProfile->canOpenNewIo()) {
3969 ALOGE("Invalid Input profile max open count %u for profile %s",
3970 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3971 continue;
3972 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003973 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003974 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003975 continue;
3976 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003977 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003978 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003979 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3980
Eric Laurentd78f1532014-09-16 16:38:20 -07003981 if ((profileType & inputDeviceTypes) == 0) {
3982 continue;
3983 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003984 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003985 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003986
Eric Laurent53b810e2017-12-10 17:25:10 -08003987 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3988 // the inputs vector must be of size >= 1, but we don't want to crash here
3989 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3990 : String8("");
3991 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3992 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3993
Eric Laurentd78f1532014-09-16 16:38:20 -07003994 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003995 status_t status = inputDesc->open(nullptr,
3996 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003997 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003998 AUDIO_SOURCE_MIC,
3999 AUDIO_INPUT_FLAG_NONE,
4000 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004001
4002 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004003 for (const auto& dev : inProfile->getSupportedDevices()) {
4004 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004005 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004006 if (index >= 0) {
4007 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4008 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004009 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004010 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004011 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004012 }
4013 }
Eric Laurentfe231122017-11-17 17:48:06 -08004014 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004015 } else {
4016 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004017 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004018 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004020 }
4021 }
4022 // make sure all attached devices have been allocated a unique ID
4023 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004024 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004025 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004026 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4027 continue;
4028 }
François Gaffie2110e042015-03-24 08:41:51 +01004029 // The device is now validated and can be appended to the available devices of the engine
4030 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4031 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004032 i++;
4033 }
4034 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004035 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004036 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004037 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4038 continue;
4039 }
François Gaffie2110e042015-03-24 08:41:51 +01004040 // The device is now validated and can be appended to the available devices of the engine
4041 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4042 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 i++;
4044 }
4045 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004046 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004047 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004048 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004049 }
jiabin9ff780e2018-03-19 18:19:52 -07004050 // If microphones address is empty, set it according to device type
4051 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4052 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4053 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4054 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4055 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4056 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4057 }
4058 }
4059 }
Eric Laurente552edb2014-03-10 17:42:56 -07004060
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004061 if (mPrimaryOutput == 0) {
4062 ALOGE("Failed to open primary output");
4063 status = NO_INIT;
4064 }
Eric Laurente552edb2014-03-10 17:42:56 -07004065
4066 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004067 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004068}
4069
Eric Laurente0720872014-03-11 09:30:41 -07004070AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004071{
Eric Laurente552edb2014-03-10 17:42:56 -07004072 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004073 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004074 }
4075 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004076 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004077 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004078 mAvailableOutputDevices.clear();
4079 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004080 mOutputs.clear();
4081 mInputs.clear();
4082 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004083 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004084 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004085}
4086
Eric Laurente0720872014-03-11 09:30:41 -07004087status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004088{
Eric Laurent87ffa392015-05-22 10:32:38 -07004089 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004090}
4091
Eric Laurente552edb2014-03-10 17:42:56 -07004092// ---
4093
Eric Laurent98e38192018-02-15 18:31:53 -08004094void AudioPolicyManager::addOutput(audio_io_handle_t output,
4095 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004096{
Eric Laurent1c333e22014-05-20 10:48:17 -07004097 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004098 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004099 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004100 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004101 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004102}
4103
François Gaffie53615e22015-03-19 09:24:12 +01004104void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4105{
4106 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004107 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004108}
4109
Eric Laurent98e38192018-02-15 18:31:53 -08004110void AudioPolicyManager::addInput(audio_io_handle_t input,
4111 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004112{
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004114 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004115}
Eric Laurente552edb2014-03-10 17:42:56 -07004116
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004117void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004118 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004119 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004120 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004121 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004122 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004123 if (devDesc != 0) {
4124 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4125 desc->mIoHandle, address.string());
4126 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004127 }
4128}
4129
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004130status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004131 audio_policy_dev_state_t state,
4132 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004133 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004134{
François Gaffie53615e22015-03-19 09:24:12 +01004135 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004136 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004137
4138 if (audio_device_is_digital(device)) {
4139 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004140 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004141 }
Eric Laurente552edb2014-03-10 17:42:56 -07004142
Eric Laurent3b73df72014-03-11 09:06:29 -07004143 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004144 // first list already open outputs that can be routed to this device
4145 for (size_t i = 0; i < mOutputs.size(); i++) {
4146 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004147 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004148 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004149 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4150 outputs.add(mOutputs.keyAt(i));
4151 } else {
4152 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004153 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004154 }
Eric Laurente552edb2014-03-10 17:42:56 -07004155 }
4156 }
4157 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004158 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004159 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004160 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4161 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004162 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004163 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004164 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004165 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004166 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4167 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004168 }
Eric Laurente552edb2014-03-10 17:42:56 -07004169 }
4170 }
4171 }
4172
Eric Laurent7b279bb2015-12-14 10:18:23 -08004173 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004174
Eric Laurente552edb2014-03-10 17:42:56 -07004175 if (profiles.isEmpty() && outputs.isEmpty()) {
4176 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4177 return BAD_VALUE;
4178 }
4179
4180 // open outputs for matching profiles if needed. Direct outputs are also opened to
4181 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4182 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004183 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004184
4185 // nothing to do if one output is already opened for this profile
4186 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004187 for (j = 0; j < outputs.size(); j++) {
4188 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004189 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004190 // matching profile: save the sample rates, format and channel masks supported
4191 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004192 if (audio_device_is_digital(device)) {
4193 devDesc->importAudioPort(profile);
4194 }
Eric Laurente552edb2014-03-10 17:42:56 -07004195 break;
4196 }
4197 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004198 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004199 continue;
4200 }
4201
Eric Laurent3974e3b2017-12-07 17:58:43 -08004202 if (!profile->canOpenNewIo()) {
4203 ALOGW("Max Output number %u already opened for this profile %s",
4204 profile->maxOpenCount, profile->getTagName().c_str());
4205 continue;
4206 }
4207
Eric Laurent83efe1c2017-07-09 16:51:08 -07004208 ALOGV("opening output for device %08x with params %s profile %p name %s",
4209 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004210 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004211 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004212 status_t status = desc->open(nullptr, device, address,
4213 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004214
Eric Laurentfe231122017-11-17 17:48:06 -08004215 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004216 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004217 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004218 char *param = audio_device_address_to_parameter(device, address);
4219 mpClientInterface->setParameters(output, String8(param));
4220 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004221 }
Phil Burk00eeb322016-03-31 12:41:00 -07004222 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004223 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004224 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004225 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004226 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004227 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004228 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004229 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004230 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4231 profile->pickAudioProfile(
4232 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004233 config.offload_info.sample_rate = config.sample_rate;
4234 config.offload_info.channel_mask = config.channel_mask;
4235 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004236
4237 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4238 AUDIO_OUTPUT_FLAG_NONE, &output);
4239 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004240 output = AUDIO_IO_HANDLE_NONE;
4241 }
Eric Laurentd4692962014-05-05 18:13:44 -07004242 }
4243
Eric Laurentcf2c0212014-07-25 16:20:43 -07004244 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004246 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004247 sp<AudioPolicyMix> policyMix;
4248 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004249 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4250 address.string());
4251 }
François Gaffie036e1e92015-03-19 10:16:24 +01004252 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004253 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004254
Eric Laurent87ffa392015-05-22 10:32:38 -07004255 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4256 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004257 // no duplicated output for direct outputs and
4258 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004259 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004260
Eric Laurentd4692962014-05-05 18:13:44 -07004261 //TODO: configure audio effect output stage here
4262
4263 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004264 sp<SwAudioOutputDescriptor> dupOutputDesc =
4265 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4266 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4267 &duplicatedOutput);
4268 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004269 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004270 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004271 } else {
4272 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004273 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004274 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004275 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004277 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004278 }
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
4280 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004281 } else {
4282 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004283 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004284 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004285 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004286 profiles.removeAt(profile_index);
4287 profile_index--;
4288 } else {
4289 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004290 // Load digital format info only for digital devices
4291 if (audio_device_is_digital(device)) {
4292 devDesc->importAudioPort(profile);
4293 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004294
François Gaffie53615e22015-03-19 09:24:12 +01004295 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004296 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4297 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004298 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004299 NULL/*patch handle*/, address.string());
4300 }
Eric Laurente552edb2014-03-10 17:42:56 -07004301 ALOGV("checkOutputsForDevice(): adding output %d", output);
4302 }
4303 }
4304
4305 if (profiles.isEmpty()) {
4306 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4307 return BAD_VALUE;
4308 }
Eric Laurentd4692962014-05-05 18:13:44 -07004309 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004310 // check if one opened output is not needed any more after disconnecting one device
4311 for (size_t i = 0; i < mOutputs.size(); i++) {
4312 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004313 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004314 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004315 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004316 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004317 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004318 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004319 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4320 mOutputs.keyAt(i));
4321 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004322 }
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
4324 }
Eric Laurentd4692962014-05-05 18:13:44 -07004325 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004326 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004327 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4328 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004329 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004330 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004331 "clearing direct output profile %zu on module %s",
4332 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004333 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004334 }
4335 }
4336 }
4337 }
4338 return NO_ERROR;
4339}
4340
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004341status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004342 audio_policy_dev_state_t state,
4343 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004344 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004345{
Paul McLean9080a4c2015-06-18 08:24:02 -07004346 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004347 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004348
4349 if (audio_device_is_digital(device)) {
4350 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004351 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004352 }
4353
Eric Laurentd4692962014-05-05 18:13:44 -07004354 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4355 // first list already open inputs that can be routed to this device
4356 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4357 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004358 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004359 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4360 inputs.add(mInputs.keyAt(input_index));
4361 }
4362 }
4363
4364 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004365 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004366 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004367 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004368 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004369 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004370 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004371
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004372 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004373 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004374 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004375 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004376 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4377 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004378 }
Eric Laurentd4692962014-05-05 18:13:44 -07004379 }
4380 }
4381 }
4382
4383 if (profiles.isEmpty() && inputs.isEmpty()) {
4384 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4385 return BAD_VALUE;
4386 }
4387
4388 // open inputs for matching profiles if needed. Direct inputs are also opened to
4389 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4390 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4391
Eric Laurent1c333e22014-05-20 10:48:17 -07004392 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004393
Eric Laurentd4692962014-05-05 18:13:44 -07004394 // nothing to do if one input is already opened for this profile
4395 size_t input_index;
4396 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4397 desc = mInputs.valueAt(input_index);
4398 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004399 if (audio_device_is_digital(device)) {
4400 devDesc->importAudioPort(profile);
4401 }
Eric Laurentd4692962014-05-05 18:13:44 -07004402 break;
4403 }
4404 }
4405 if (input_index != mInputs.size()) {
4406 continue;
4407 }
4408
Eric Laurent3974e3b2017-12-07 17:58:43 -08004409 if (!profile->canOpenNewIo()) {
4410 ALOGW("Max Input number %u already opened for this profile %s",
4411 profile->maxOpenCount, profile->getTagName().c_str());
4412 continue;
4413 }
4414
Eric Laurentfe231122017-11-17 17:48:06 -08004415 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004416 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004417 status_t status = desc->open(nullptr,
4418 device,
4419 address,
4420 AUDIO_SOURCE_MIC,
4421 AUDIO_INPUT_FLAG_NONE,
4422 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004423
Eric Laurentcf2c0212014-07-25 16:20:43 -07004424 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004425 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004426 char *param = audio_device_address_to_parameter(device, address);
4427 mpClientInterface->setParameters(input, String8(param));
4428 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004429 }
Phil Burk00eeb322016-03-31 12:41:00 -07004430 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004431 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004432 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004433 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004434 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004435 }
4436
4437 if (input != 0) {
4438 addInput(input, desc);
4439 }
4440 } // endif input != 0
4441
Eric Laurentcf2c0212014-07-25 16:20:43 -07004442 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004443 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004444 profiles.removeAt(profile_index);
4445 profile_index--;
4446 } else {
4447 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004448 if (audio_device_is_digital(device)) {
4449 devDesc->importAudioPort(profile);
4450 }
Eric Laurentd4692962014-05-05 18:13:44 -07004451 ALOGV("checkInputsForDevice(): adding input %d", input);
4452 }
4453 } // end scan profiles
4454
4455 if (profiles.isEmpty()) {
4456 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4457 return BAD_VALUE;
4458 }
4459 } else {
4460 // Disconnect
4461 // check if one opened input is not needed any more after disconnecting one device
4462 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4463 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004464 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004465 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4466 mInputs.keyAt(input_index));
4467 inputs.add(mInputs.keyAt(input_index));
4468 }
4469 }
4470 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004471 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004472 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004473 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004474 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004475 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004476 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004477 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4478 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004479 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004480 }
4481 }
4482 }
4483 } // end disconnect
4484
4485 return NO_ERROR;
4486}
4487
4488
Eric Laurente0720872014-03-11 09:30:41 -07004489void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004490{
4491 ALOGV("closeOutput(%d)", output);
4492
Eric Laurentc75307b2015-03-17 15:29:32 -07004493 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004494 if (outputDesc == NULL) {
4495 ALOGW("closeOutput() unknown output %d", output);
4496 return;
4497 }
François Gaffie036e1e92015-03-19 10:16:24 +01004498 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004499
Eric Laurente552edb2014-03-10 17:42:56 -07004500 // look for duplicated outputs connected to the output being removed.
4501 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004502 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004503 if (dupOutputDesc->isDuplicated() &&
4504 (dupOutputDesc->mOutput1 == outputDesc ||
4505 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004506 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004507 if (dupOutputDesc->mOutput1 == outputDesc) {
4508 outputDesc2 = dupOutputDesc->mOutput2;
4509 } else {
4510 outputDesc2 = dupOutputDesc->mOutput1;
4511 }
4512 // As all active tracks on duplicated output will be deleted,
4513 // and as they were also referenced on the other output, the reference
4514 // count for their stream type must be adjusted accordingly on
4515 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004516 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004517 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004518 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004519 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004520 }
Eric Laurent733ce942017-12-07 12:18:25 -08004521 // stop() will be a no op if the output is still active but is needed in case all
4522 // active streams refcounts where cleared above
4523 if (wasActive) {
4524 outputDesc2->stop();
4525 }
Eric Laurente552edb2014-03-10 17:42:56 -07004526 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4527 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4528
4529 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004530 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004531 }
4532 }
4533
Eric Laurent05b90f82014-08-27 15:32:29 -07004534 nextAudioPortGeneration();
4535
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004536 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004537 if (index >= 0) {
4538 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004539 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004540 mAudioPatches.removeItemsAt(index);
4541 mpClientInterface->onAudioPatchListUpdate();
4542 }
4543
Eric Laurentfe231122017-11-17 17:48:06 -08004544 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004545
François Gaffie53615e22015-03-19 09:24:12 +01004546 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004547 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004548}
4549
4550void AudioPolicyManager::closeInput(audio_io_handle_t input)
4551{
4552 ALOGV("closeInput(%d)", input);
4553
4554 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4555 if (inputDesc == NULL) {
4556 ALOGW("closeInput() unknown input %d", input);
4557 return;
4558 }
4559
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004561
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004562 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004563 if (index >= 0) {
4564 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004565 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004566 mAudioPatches.removeItemsAt(index);
4567 mpClientInterface->onAudioPatchListUpdate();
4568 }
4569
Eric Laurentfe231122017-11-17 17:48:06 -08004570 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004571 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004572}
4573
Eric Laurentc75307b2015-03-17 15:29:32 -07004574SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4575 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004576 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004577{
4578 SortedVector<audio_io_handle_t> outputs;
4579
4580 ALOGVV("getOutputsForDevice() device %04x", device);
4581 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004582 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004583 i, openOutputs.valueAt(i)->isDuplicated(),
4584 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004585 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4586 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4587 outputs.add(openOutputs.keyAt(i));
4588 }
4589 }
4590 return outputs;
4591}
4592
Eric Laurente0720872014-03-11 09:30:41 -07004593bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004594 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004595{
4596 if (outputs1.size() != outputs2.size()) {
4597 return false;
4598 }
4599 for (size_t i = 0; i < outputs1.size(); i++) {
4600 if (outputs1[i] != outputs2[i]) {
4601 return false;
4602 }
4603 }
4604 return true;
4605}
4606
Eric Laurente0720872014-03-11 09:30:41 -07004607void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004608{
4609 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4610 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4611 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4612 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4613
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004614 // also take into account external policy-related changes: add all outputs which are
4615 // associated with policies in the "before" and "after" output vectors
4616 ALOGVV("checkOutputForStrategy(): policy related outputs");
4617 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004618 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004619 if (desc != 0 && desc->mPolicyMix != NULL) {
4620 srcOutputs.add(desc->mIoHandle);
4621 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4622 }
4623 }
4624 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004625 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004626 if (desc != 0 && desc->mPolicyMix != NULL) {
4627 dstOutputs.add(desc->mIoHandle);
4628 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4629 }
4630 }
4631
Eric Laurente552edb2014-03-10 17:42:56 -07004632 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004633 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4634 // audio from invalidated tracks will be rendered when unmuting
4635 uint32_t maxLatency = 0;
4636 for (audio_io_handle_t srcOut : srcOutputs) {
4637 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4638 if (desc != 0 && maxLatency < desc->latency()) {
4639 maxLatency = desc->latency();
4640 }
4641 }
Eric Laurente552edb2014-03-10 17:42:56 -07004642 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4643 strategy, srcOutputs[0], dstOutputs[0]);
4644 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004645 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004646 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4647 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004648 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004649 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004650 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004651 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004652 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004653 if (source != 0){
4654 connectAudioSource(source);
4655 }
Eric Laurente552edb2014-03-10 17:42:56 -07004656 }
4657
4658 // Move effects associated to this strategy from previous output to new output
4659 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004660 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004661 }
4662 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004663 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004664 if (getStrategy((audio_stream_type_t)i) == strategy) {
4665 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004666 }
4667 }
4668 }
4669}
4670
Eric Laurente0720872014-03-11 09:30:41 -07004671void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004672{
François Gaffie2110e042015-03-24 08:41:51 +01004673 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004674 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004675 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004676 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004677 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004678 checkOutputForStrategy(STRATEGY_SONIFICATION);
4679 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004680 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004681 checkOutputForStrategy(STRATEGY_MEDIA);
4682 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004683 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004684}
4685
Eric Laurente0720872014-03-11 09:30:41 -07004686void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004687{
François Gaffie53615e22015-03-19 09:24:12 +01004688 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004689 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004690 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004691 return;
4692 }
4693
Eric Laurent3a4311c2014-03-17 12:00:47 -07004694 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004695 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4696 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4697 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004698
4699 // if suspended, restore A2DP output if:
4700 // ((SCO device is NOT connected) ||
4701 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4702 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004703 //
Eric Laurentf732e072016-08-03 19:30:28 -07004704 // if not suspended, suspend A2DP output if:
4705 // (SCO device is connected) &&
4706 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4707 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004708 //
4709 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004710 if (!isScoConnected ||
4711 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4712 AUDIO_POLICY_FORCE_BT_SCO) &&
4713 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4714 AUDIO_POLICY_FORCE_BT_SCO) &&
4715 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004716 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004717
4718 mpClientInterface->restoreOutput(a2dpOutput);
4719 mA2dpSuspended = false;
4720 }
4721 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004722 if (isScoConnected &&
4723 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4724 AUDIO_POLICY_FORCE_BT_SCO) ||
4725 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4726 AUDIO_POLICY_FORCE_BT_SCO) ||
4727 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004728 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004729
4730 mpClientInterface->suspendOutput(a2dpOutput);
4731 mA2dpSuspended = true;
4732 }
4733 }
4734}
4735
Eric Laurentc75307b2015-03-17 15:29:32 -07004736audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4737 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
4739 audio_devices_t device = AUDIO_DEVICE_NONE;
4740
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004741 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 if (index >= 0) {
4743 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4744 if (patchDesc->mUid != mUidCached) {
4745 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004746 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004747 return outputDesc->device();
4748 }
4749 }
4750
Eric Laurente552edb2014-03-10 17:42:56 -07004751 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004752 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004753 // use device for strategy enforced audible
4754 // 2: we are in call or the strategy phone is active on the output:
4755 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004756 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004757 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004758 // 4: the strategy for enforced audible is active but not enforced on the output:
4759 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004760 // 5: the strategy accessibility is active on the output:
4761 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004762 // 6: the strategy "respectful" sonification is active on the output:
4763 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004764 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004765 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004766 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004767 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004768 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004769 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004770 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004771 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004772 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4773 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004774 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004775 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004776 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004777 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004778 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4779 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004780 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4781 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004782 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004783 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004784 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004785 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004786 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004787 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004788 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004789 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004790 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004791 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004792 }
4793
Eric Laurent1c333e22014-05-20 10:48:17 -07004794 ALOGV("getNewOutputDevice() selected device %x", device);
4795 return device;
4796}
4797
Eric Laurentfb66dd92016-01-28 18:32:03 -08004798audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004799{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004800 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004801
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004802 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 if (index >= 0) {
4804 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4805 if (patchDesc->mUid != mUidCached) {
4806 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004807 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 return inputDesc->mDevice;
4809 }
4810 }
4811
Eric Laurentdc95a252018-04-12 12:46:56 -07004812 // If we are not in call and no client is active on this input, this methods returns
4813 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004814 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004815 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4816 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4817 }
4818 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004819 device = getDeviceAndMixForInputSource(source);
4820 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004821
Eric Laurente552edb2014-03-10 17:42:56 -07004822 return device;
4823}
4824
Eric Laurent794fde22016-03-11 09:50:45 -08004825bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4826 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004827 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004828}
4829
Eric Laurente0720872014-03-11 09:30:41 -07004830uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004831 return (uint32_t)getStrategy(stream);
4832}
4833
Eric Laurente0720872014-03-11 09:30:41 -07004834audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004835 // By checking the range of stream before calling getStrategy, we avoid
4836 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4837 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004838 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004839 return AUDIO_DEVICE_NONE;
4840 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004841 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004842 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4843 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004844 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004845 }
Eric Laurent794fde22016-03-11 09:50:45 -08004846 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004847 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004848 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004849 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4850 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004851 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004852 curDevices |= outputDesc->device();
4853 }
4854 }
4855 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004856 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004857
4858 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4859 and doesn't really need to.*/
4860 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4861 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4862 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4863 }
Eric Laurente552edb2014-03-10 17:42:56 -07004864 return devices;
4865}
4866
François Gaffie2110e042015-03-24 08:41:51 +01004867routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4868{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004869 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004870 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004871}
4872
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004873uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4874 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004875 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4876 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4877 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004878 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4879 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4880 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004881 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004882 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004883}
4884
Eric Laurente0720872014-03-11 09:30:41 -07004885void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004886 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004887 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004888 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4889 updateDevicesAndOutputs();
4890 break;
4891 default:
4892 break;
4893 }
4894}
4895
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004896uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004897
4898 // skip beacon mute management if a dedicated TTS output is available
4899 if (mTtsOutputAvailable) {
4900 return 0;
4901 }
4902
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004903 switch(event) {
4904 case STARTING_OUTPUT:
4905 mBeaconMuteRefCount++;
4906 break;
4907 case STOPPING_OUTPUT:
4908 if (mBeaconMuteRefCount > 0) {
4909 mBeaconMuteRefCount--;
4910 }
4911 break;
4912 case STARTING_BEACON:
4913 mBeaconPlayingRefCount++;
4914 break;
4915 case STOPPING_BEACON:
4916 if (mBeaconPlayingRefCount > 0) {
4917 mBeaconPlayingRefCount--;
4918 }
4919 break;
4920 }
4921
4922 if (mBeaconMuteRefCount > 0) {
4923 // any playback causes beacon to be muted
4924 return setBeaconMute(true);
4925 } else {
4926 // no other playback: unmute when beacon starts playing, mute when it stops
4927 return setBeaconMute(mBeaconPlayingRefCount == 0);
4928 }
4929}
4930
4931uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4932 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4933 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4934 // keep track of muted state to avoid repeating mute/unmute operations
4935 if (mBeaconMuted != mute) {
4936 // mute/unmute AUDIO_STREAM_TTS on all outputs
4937 ALOGV("\t muting %d", mute);
4938 uint32_t maxLatency = 0;
4939 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004940 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004941 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004942 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004943 0 /*delay*/, AUDIO_DEVICE_NONE);
4944 const uint32_t latency = desc->latency() * 2;
4945 if (latency > maxLatency) {
4946 maxLatency = latency;
4947 }
4948 }
4949 mBeaconMuted = mute;
4950 return maxLatency;
4951 }
4952 return 0;
4953}
4954
Eric Laurente0720872014-03-11 09:30:41 -07004955audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004956 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004957{
Paul McLeanaa981192015-03-21 09:55:15 -07004958 // Routing
4959 // see if we have an explicit route
4960 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4961 // (getStrategy(stream)).
4962 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004963 // and activity count is non-zero and the device in the route descriptor is available
4964 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004965 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4966 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004967 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurent2157f5b2018-04-25 18:33:02 -07004968 if ((routeStrategy == strategy) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07004969 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07004970 return route->mDeviceDescriptor->type();
4971 }
4972 }
4973
Eric Laurente552edb2014-03-10 17:42:56 -07004974 if (fromCache) {
4975 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4976 strategy, mDeviceForStrategy[strategy]);
4977 return mDeviceForStrategy[strategy];
4978 }
François Gaffie2110e042015-03-24 08:41:51 +01004979 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004980}
4981
Eric Laurente0720872014-03-11 09:30:41 -07004982void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004983{
4984 for (int i = 0; i < NUM_STRATEGIES; i++) {
4985 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4986 }
4987 mPreviousOutputs = mOutputs;
4988}
4989
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004990uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004991 audio_devices_t prevDevice,
4992 uint32_t delayMs)
4993{
4994 // mute/unmute strategies using an incompatible device combination
4995 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4996 // if unmuting, unmute only after the specified delay
4997 if (outputDesc->isDuplicated()) {
4998 return 0;
4999 }
5000
5001 uint32_t muteWaitMs = 0;
5002 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005003 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005004
5005 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5006 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005007 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005008 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5009 bool doMute = false;
5010
5011 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5012 doMute = true;
5013 outputDesc->mStrategyMutedByDevice[i] = true;
5014 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5015 doMute = true;
5016 outputDesc->mStrategyMutedByDevice[i] = false;
5017 }
Eric Laurent99401132014-05-07 19:48:15 -07005018 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005019 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005020 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005021 // skip output if it does not share any device with current output
5022 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5023 == AUDIO_DEVICE_NONE) {
5024 continue;
5025 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005026 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005027 mute ? "muting" : "unmuting", i, curDevice);
5028 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005029 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005030 if (mute) {
5031 // FIXME: should not need to double latency if volume could be applied
5032 // immediately by the audioflinger mixer. We must account for the delay
5033 // between now and the next time the audioflinger thread for this output
5034 // will process a buffer (which corresponds to one buffer size,
5035 // usually 1/2 or 1/4 of the latency).
5036 if (muteWaitMs < desc->latency() * 2) {
5037 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005038 }
5039 }
5040 }
5041 }
5042 }
5043 }
5044
Eric Laurent99401132014-05-07 19:48:15 -07005045 // temporary mute output if device selection changes to avoid volume bursts due to
5046 // different per device volumes
5047 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005048 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5049 // temporary mute duration is conservatively set to 4 times the reported latency
5050 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5051 if (muteWaitMs < tempMuteWaitMs) {
5052 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005053 }
Eric Laurentdc462862016-07-19 12:29:53 -07005054
Eric Laurent99401132014-05-07 19:48:15 -07005055 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005056 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005057 // make sure that we do not start the temporary mute period too early in case of
5058 // delayed device change
5059 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005061 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005062 }
5063 }
5064 }
5065
Eric Laurente552edb2014-03-10 17:42:56 -07005066 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5067 if (muteWaitMs > delayMs) {
5068 muteWaitMs -= delayMs;
5069 usleep(muteWaitMs * 1000);
5070 return muteWaitMs;
5071 }
5072 return 0;
5073}
5074
Eric Laurentc75307b2015-03-17 15:29:32 -07005075uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005076 audio_devices_t device,
5077 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005078 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005079 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005080 const char *address,
5081 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005082{
Eric Laurentc75307b2015-03-17 15:29:32 -07005083 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005084 AudioParameter param;
5085 uint32_t muteWaitMs;
5086
5087 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005088 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5089 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5090 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5091 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005092 return muteWaitMs;
5093 }
5094 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5095 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005096 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005097 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005098 return 0;
5099 }
5100
5101 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005102 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005103
5104 audio_devices_t prevDevice = outputDesc->mDevice;
5105
Paul McLeanaa981192015-03-21 09:55:15 -07005106 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005107
5108 if (device != AUDIO_DEVICE_NONE) {
5109 outputDesc->mDevice = device;
5110 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005111
5112 // if the outputs are not materially active, there is no need to mute.
5113 if (requiresMuteCheck) {
5114 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5115 } else {
5116 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5117 muteWaitMs = 0;
5118 }
Eric Laurente552edb2014-03-10 17:42:56 -07005119
5120 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005121 // the requested device is AUDIO_DEVICE_NONE
5122 // OR the requested device is the same as current device
5123 // AND force is not specified
5124 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005125 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005126 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5127 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005128 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 return muteWaitMs;
5131 }
5132
5133 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005134
Eric Laurente552edb2014-03-10 17:42:56 -07005135 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005136 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005137 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005138 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005139 DeviceVector deviceList;
5140 if ((address == NULL) || (strlen(address) == 0)) {
5141 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5142 } else {
5143 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5144 }
5145
Eric Laurent1c333e22014-05-20 10:48:17 -07005146 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005147 PatchBuilder patchBuilder;
5148 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005149 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005150 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005151 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005152 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005153 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005154
5155 // inform all input as well
5156 for (size_t i = 0; i < mInputs.size(); i++) {
5157 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005158 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005159 AudioParameter inputCmd = AudioParameter();
5160 ALOGV("%s: inform input %d of device:%d", __func__,
5161 inputDescriptor->mIoHandle, device);
5162 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5163 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5164 inputCmd.toString(),
5165 delayMs);
5166 }
5167 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005168 }
Eric Laurente552edb2014-03-10 17:42:56 -07005169
5170 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005171 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005172
5173 return muteWaitMs;
5174}
5175
Eric Laurentc75307b2015-03-17 15:29:32 -07005176status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005177 int delayMs,
5178 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005179{
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 ssize_t index;
5181 if (patchHandle) {
5182 index = mAudioPatches.indexOfKey(*patchHandle);
5183 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005184 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 }
5186 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005187 return INVALID_OPERATION;
5188 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5190 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005191 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005192 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 removeAudioPatch(patchDesc->mHandle);
5194 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005195 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005196 return status;
5197}
5198
5199status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5200 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 bool force,
5202 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005203{
5204 status_t status = NO_ERROR;
5205
Eric Laurent1f2f2232014-06-02 12:01:23 -07005206 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005207 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5208 inputDesc->mDevice = device;
5209
5210 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5211 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005212 PatchBuilder patchBuilder;
5213 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005214 // AUDIO_SOURCE_HOTWORD is for internal use only:
5215 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005216 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5217 auto result = usecase;
5218 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5219 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5220 }
5221 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005222 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005223 addSource(deviceList.itemAt(0));
5224 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 }
5226 }
5227 return status;
5228}
5229
Eric Laurent6a94d692014-05-20 11:18:06 -07005230status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5231 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005232{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005233 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 ssize_t index;
5235 if (patchHandle) {
5236 index = mAudioPatches.indexOfKey(*patchHandle);
5237 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005238 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 }
5240 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005241 return INVALID_OPERATION;
5242 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5244 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005246 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 removeAudioPatch(patchDesc->mHandle);
5248 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005249 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005250 return status;
5251}
5252
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005253sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005254 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005255 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005256 audio_format_t& format,
5257 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005258 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005259{
5260 // Choose an input profile based on the requested capture parameters: select the first available
5261 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005262 //
5263 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5264 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005265
Glenn Kasten730b9262018-03-29 15:01:26 -07005266 sp<IOProfile> firstInexact;
5267 uint32_t updatedSamplingRate = 0;
5268 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5269 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005270 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005271 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005272 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005273 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005274 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005275 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005276 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005277 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005278 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005279 &channelMask /*updatedChannelMask*/,
5280 // FIXME ugly cast
5281 (audio_output_flags_t) flags,
5282 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005283 return profile;
5284 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005285 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5286 samplingRate,
5287 &updatedSamplingRate,
5288 format,
5289 &updatedFormat,
5290 channelMask,
5291 &updatedChannelMask,
5292 // FIXME ugly cast
5293 (audio_output_flags_t) flags,
5294 false /*exactMatchRequiredForInputFlags*/)) {
5295 firstInexact = profile;
5296 }
5297
Eric Laurente552edb2014-03-10 17:42:56 -07005298 }
5299 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005300 if (firstInexact != nullptr) {
5301 samplingRate = updatedSamplingRate;
5302 format = updatedFormat;
5303 channelMask = updatedChannelMask;
5304 return firstInexact;
5305 }
Eric Laurente552edb2014-03-10 17:42:56 -07005306 return NULL;
5307}
5308
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005309
5310audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005311 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005312{
François Gaffie036e1e92015-03-19 10:16:24 +01005313 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5314 audio_devices_t selectedDeviceFromMix =
5315 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005316
François Gaffie036e1e92015-03-19 10:16:24 +01005317 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5318 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005319 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005320 return getDeviceForInputSource(inputSource);
5321}
5322
5323audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5324{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005325 // Routing
5326 // Scan the whole RouteMap to see if we have an explicit route:
5327 // if the input source in the RouteMap is the same as the argument above,
5328 // and activity count is non-zero and the device in the route descriptor is available
5329 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005330 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5331 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005332 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005333 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005334 return route->mDeviceDescriptor->type();
5335 }
5336 }
5337
5338 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005339}
5340
Eric Laurente0720872014-03-11 09:30:41 -07005341float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005342 int index,
5343 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005344{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005345 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005346
5347 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5348 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5349 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5350 // the ringtone volume
5351 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5352 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5353 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5354 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5355 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5356 }
5357
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005358 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005359 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5360 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005361 switch (stream) {
5362 case AUDIO_STREAM_SYSTEM:
5363 case AUDIO_STREAM_RING:
5364 case AUDIO_STREAM_MUSIC:
5365 case AUDIO_STREAM_ALARM:
5366 case AUDIO_STREAM_NOTIFICATION:
5367 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5368 case AUDIO_STREAM_DTMF:
5369 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005370 int voiceVolumeIndex =
5371 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5372 const float maxVoiceVolDb =
5373 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5374 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005375 if (volumeDB > maxVoiceVolDb) {
5376 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5377 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5378 volumeDB = maxVoiceVolDb;
5379 }
5380 } break;
5381 default:
5382 break;
5383 }
5384 }
5385
Eric Laurente552edb2014-03-10 17:42:56 -07005386 // if a headset is connected, apply the following rules to ring tones and notifications
5387 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005388 // - always attenuate notifications volume by 6dB
5389 // - attenuate ring tones volume by 6dB unless music is not playing and
5390 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005391 // - if music is playing, always limit the volume to current music volume,
5392 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005393 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005394 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5395 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5396 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005397 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005398 AUDIO_DEVICE_OUT_USB_HEADSET |
5399 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005400 ((stream_strategy == STRATEGY_SONIFICATION)
5401 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005402 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005403 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005404 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005405 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005406 // when the phone is ringing we must consider that music could have been paused just before
5407 // by the music application and behave as if music was active if the last music track was
5408 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005409 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005410 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005411 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005412 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005413 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005414 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5415 musicDevice),
5416 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005417 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5418 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005419 if (volumeDB > minVolDB) {
5420 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005421 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005422 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005423 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5424 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5425 // on A2DP, also ensure notification volume is not too low compared to media when
5426 // intended to be played
5427 if ((volumeDB > -96.0f) &&
5428 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5429 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5430 stream, device,
5431 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5432 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5433 }
5434 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005435 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5436 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005437 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005438 }
5439 }
5440
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005441 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005442}
5443
Eric Laurente0720872014-03-11 09:30:41 -07005444status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005445 int index,
5446 const sp<AudioOutputDescriptor>& outputDesc,
5447 audio_devices_t device,
5448 int delayMs,
5449 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005450{
Eric Laurente552edb2014-03-10 17:42:56 -07005451 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005452 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005453 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005454 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005455 return NO_ERROR;
5456 }
François Gaffie2110e042015-03-24 08:41:51 +01005457 audio_policy_forced_cfg_t forceUseForComm =
5458 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005459 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005460 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5461 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005462 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005463 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005464 return INVALID_OPERATION;
5465 }
5466
Eric Laurentc75307b2015-03-17 15:29:32 -07005467 if (device == AUDIO_DEVICE_NONE) {
5468 device = outputDesc->device();
5469 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005470
Eric Laurentffbc80f2015-03-18 18:30:19 -07005471 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005472 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005473 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005474 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005475
Eric Laurentffbc80f2015-03-18 18:30:19 -07005476 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005477
Eric Laurent3b73df72014-03-11 09:06:29 -07005478 if (stream == AUDIO_STREAM_VOICE_CALL ||
5479 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005480 float voiceVolume;
5481 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005482 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005483 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005484 } else {
5485 voiceVolume = 1.0;
5486 }
5487
Eric Laurent18fba842016-03-31 14:41:26 -07005488 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005489 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5490 mLastVoiceVolume = voiceVolume;
5491 }
5492 }
5493
5494 return NO_ERROR;
5495}
5496
Eric Laurentc75307b2015-03-17 15:29:32 -07005497void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5498 audio_devices_t device,
5499 int delayMs,
5500 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005501{
Eric Laurentc75307b2015-03-17 15:29:32 -07005502 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005503
Eric Laurent794fde22016-03-11 09:50:45 -08005504 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005505 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005506 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005507 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005508 device,
5509 delayMs,
5510 force);
5511 }
5512}
5513
Eric Laurente0720872014-03-11 09:30:41 -07005514void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005515 bool on,
5516 const sp<AudioOutputDescriptor>& outputDesc,
5517 int delayMs,
5518 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005519{
Eric Laurent72249d52015-06-08 11:12:15 -07005520 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5521 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005522 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005523 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005524 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005525 }
5526 }
5527}
5528
Eric Laurente0720872014-03-11 09:30:41 -07005529void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005530 bool on,
5531 const sp<AudioOutputDescriptor>& outputDesc,
5532 int delayMs,
5533 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005534{
Eric Laurente552edb2014-03-10 17:42:56 -07005535 if (device == AUDIO_DEVICE_NONE) {
5536 device = outputDesc->device();
5537 }
5538
Eric Laurentc75307b2015-03-17 15:29:32 -07005539 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5540 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005541
5542 if (on) {
5543 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005544 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005545 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005546 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005547 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005548 }
5549 }
5550 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5551 outputDesc->mMuteCount[stream]++;
5552 } else {
5553 if (outputDesc->mMuteCount[stream] == 0) {
5554 ALOGV("setStreamMute() unmuting non muted stream!");
5555 return;
5556 }
5557 if (--outputDesc->mMuteCount[stream] == 0) {
5558 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005559 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005560 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005561 device,
5562 delayMs);
5563 }
5564 }
5565}
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005568 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005569{
Eric Laurent87ffa392015-05-22 10:32:38 -07005570 if(!hasPrimaryOutput()) {
5571 return;
5572 }
5573
Eric Laurente552edb2014-03-10 17:42:56 -07005574 // if the stream pertains to sonification strategy and we are in call we must
5575 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5576 // in the device used for phone strategy and play the tone if the selected device does not
5577 // interfere with the device used for phone strategy
5578 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5579 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005580 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005581 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5582 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005583 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005584 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5585 stream, starting, outputDesc->mDevice, stateChange);
5586 if (outputDesc->mRefCount[stream]) {
5587 int muteCount = 1;
5588 if (stateChange) {
5589 muteCount = outputDesc->mRefCount[stream];
5590 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005592 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5593 for (int i = 0; i < muteCount; i++) {
5594 setStreamMute(stream, starting, mPrimaryOutput);
5595 }
5596 } else {
5597 ALOGV("handleIncallSonification() high visibility");
5598 if (outputDesc->device() &
5599 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5600 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5601 for (int i = 0; i < muteCount; i++) {
5602 setStreamMute(stream, starting, mPrimaryOutput);
5603 }
5604 }
5605 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005606 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5607 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005608 } else {
5609 mpClientInterface->stopTone();
5610 }
5611 }
5612 }
5613 }
5614}
5615
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005616audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5617{
5618 // flags to stream type mapping
5619 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5620 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5621 }
5622 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5623 return AUDIO_STREAM_BLUETOOTH_SCO;
5624 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005625 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5626 return AUDIO_STREAM_TTS;
5627 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005628
5629 // usage to stream type mapping
5630 switch (attr->usage) {
5631 case AUDIO_USAGE_MEDIA:
5632 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005633 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005634 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5635 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005636 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5637 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005638 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5639 return AUDIO_STREAM_SYSTEM;
5640 case AUDIO_USAGE_VOICE_COMMUNICATION:
5641 return AUDIO_STREAM_VOICE_CALL;
5642
5643 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5644 return AUDIO_STREAM_DTMF;
5645
5646 case AUDIO_USAGE_ALARM:
5647 return AUDIO_STREAM_ALARM;
5648 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5649 return AUDIO_STREAM_RING;
5650
5651 case AUDIO_USAGE_NOTIFICATION:
5652 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5653 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5654 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5655 case AUDIO_USAGE_NOTIFICATION_EVENT:
5656 return AUDIO_STREAM_NOTIFICATION;
5657
5658 case AUDIO_USAGE_UNKNOWN:
5659 default:
5660 return AUDIO_STREAM_MUSIC;
5661 }
5662}
Eric Laurente83b55d2014-11-14 10:06:21 -08005663
François Gaffie53615e22015-03-19 09:24:12 +01005664bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5665{
Eric Laurente83b55d2014-11-14 10:06:21 -08005666 // has flags that map to a strategy?
5667 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5668 return true;
5669 }
5670
5671 // has known usage?
5672 switch (paa->usage) {
5673 case AUDIO_USAGE_UNKNOWN:
5674 case AUDIO_USAGE_MEDIA:
5675 case AUDIO_USAGE_VOICE_COMMUNICATION:
5676 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5677 case AUDIO_USAGE_ALARM:
5678 case AUDIO_USAGE_NOTIFICATION:
5679 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5680 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5681 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5682 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5683 case AUDIO_USAGE_NOTIFICATION_EVENT:
5684 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5685 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5686 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5687 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005688 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005689 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005690 break;
5691 default:
5692 return false;
5693 }
5694 return true;
5695}
5696
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005697bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005698 routing_strategy strategy, uint32_t inPastMs,
5699 nsecs_t sysTime) const
5700{
5701 if ((sysTime == 0) && (inPastMs != 0)) {
5702 sysTime = systemTime();
5703 }
Eric Laurent794fde22016-03-11 09:50:45 -08005704 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005705 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5706 (NUM_STRATEGIES == strategy)) &&
5707 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5708 return true;
5709 }
5710 }
5711 return false;
5712}
5713
François Gaffie2110e042015-03-24 08:41:51 +01005714audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5715{
5716 return mEngine->getForceUse(usage);
5717}
5718
5719bool AudioPolicyManager::isInCall()
5720{
5721 return isStateInCall(mEngine->getPhoneState());
5722}
5723
5724bool AudioPolicyManager::isStateInCall(int state)
5725{
5726 return is_state_in_call(state);
5727}
5728
Eric Laurentd60560a2015-04-10 11:31:20 -07005729void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5730{
5731 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5732 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5733 if (sourceDesc->mDevice->equals(deviceDesc)) {
5734 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5735 stopAudioSource(sourceDesc->getHandle());
5736 }
5737 }
5738
5739 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5740 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5741 bool release = false;
5742 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5743 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5744 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5745 source->ext.device.type == deviceDesc->type()) {
5746 release = true;
5747 }
5748 }
5749 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5750 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5751 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5752 sink->ext.device.type == deviceDesc->type()) {
5753 release = true;
5754 }
5755 }
5756 if (release) {
5757 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5758 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5759 }
5760 }
5761}
5762
Phil Burk09bc4612016-02-24 15:58:15 -08005763// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005764void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5765 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005766 // TODO Set this based on Config properties.
5767 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005768
5769 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5770 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005771 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005772
jiabin81772902018-04-02 17:52:27 -07005773 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5774 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5775 formats.clear();
5776 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5777 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005778 }
jiabin81772902018-04-02 17:52:27 -07005779 // Always enable IEC61937 when in MANUAL mode.
5780 formats.add(AUDIO_FORMAT_IEC61937);
5781 } else { // NEVER, AUTO or ALWAYS
5782 // Analyze original support for various formats.
5783 bool supportsAC3 = false;
5784 bool supportsOtherSurround = false;
5785 bool supportsIEC61937 = false;
5786 mSurroundFormats.clear();
5787 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5788 audio_format_t format = formats[formatIndex];
5789 switch (format) {
5790 case AUDIO_FORMAT_AC3:
5791 supportsAC3 = true;
5792 break;
5793 case AUDIO_FORMAT_E_AC3:
5794 case AUDIO_FORMAT_DTS:
5795 case AUDIO_FORMAT_DTS_HD:
5796 // If ALWAYS, remove all other surround formats here
5797 // since we will add them later.
5798 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5799 formats.removeAt(formatIndex);
5800 formatIndex--;
5801 }
5802 supportsOtherSurround = true;
5803 break;
5804 case AUDIO_FORMAT_IEC61937:
5805 supportsIEC61937 = true;
5806 break;
5807 default:
5808 break;
5809 }
5810 }
Phil Burk09bc4612016-02-24 15:58:15 -08005811
jiabin81772902018-04-02 17:52:27 -07005812 // Modify formats based on surround preferences.
5813 // If NEVER, remove support for surround formats.
5814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5815 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5816 // Remove surround sound related formats.
5817 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5818 audio_format_t format = formats[formatIndex];
5819 switch(format) {
5820 case AUDIO_FORMAT_AC3:
5821 case AUDIO_FORMAT_E_AC3:
5822 case AUDIO_FORMAT_DTS:
5823 case AUDIO_FORMAT_DTS_HD:
5824 case AUDIO_FORMAT_IEC61937:
5825 formats.removeAt(formatIndex);
5826 break;
5827 default:
5828 formatIndex++; // keep it
5829 break;
5830 }
5831 }
5832 supportsAC3 = false;
5833 supportsOtherSurround = false;
5834 supportsIEC61937 = false;
5835 }
5836 } else { // AUTO or ALWAYS
5837 // Most TVs support AC3 even if they do not report it in the EDID.
5838 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5839 && !supportsAC3) {
5840 formats.add(AUDIO_FORMAT_AC3);
5841 supportsAC3 = true;
5842 }
5843
5844 // If ALWAYS, add support for raw surround formats if all are missing.
5845 // This assumes that if any of these formats are reported by the HAL
5846 // then the report is valid and should not be modified.
5847 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5848 formats.add(AUDIO_FORMAT_E_AC3);
5849 formats.add(AUDIO_FORMAT_DTS);
5850 formats.add(AUDIO_FORMAT_DTS_HD);
5851 supportsOtherSurround = true;
5852 }
5853
5854 // Add support for IEC61937 if any raw surround supported.
5855 // The HAL could do this but add it here, just in case.
5856 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5857 formats.add(AUDIO_FORMAT_IEC61937);
5858 supportsIEC61937 = true;
5859 }
5860
5861 // Add reported surround sound formats to enabled surround formats.
5862 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005863 audio_format_t format = formats[formatIndex];
5864 switch(format) {
5865 case AUDIO_FORMAT_AC3:
5866 case AUDIO_FORMAT_E_AC3:
5867 case AUDIO_FORMAT_DTS:
5868 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005869 case AUDIO_FORMAT_AAC_LC:
5870 case AUDIO_FORMAT_DOLBY_TRUEHD:
5871 case AUDIO_FORMAT_E_AC3_JOC:
5872 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005873 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005874 break;
5875 }
Phil Burk09bc4612016-02-24 15:58:15 -08005876 }
Phil Burk07ac1142016-03-25 13:39:29 -07005877 }
Phil Burk09bc4612016-02-24 15:58:15 -08005878 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005879}
5880
5881// Modify the list of channel masks supported.
5882void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5883 ChannelsVector &channelMasks = *channelMasksPtr;
5884 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5885 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5886
5887 // If NEVER, then remove support for channelMasks > stereo.
5888 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5889 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5890 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5891 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5892 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5893 channelMasks.removeAt(maskIndex);
5894 } else {
5895 maskIndex++;
5896 }
5897 }
jiabin81772902018-04-02 17:52:27 -07005898 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5899 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5900 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005901 bool supports5dot1 = false;
5902 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005903 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005904 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5905 supports5dot1 = true;
5906 break;
5907 }
5908 }
5909 // If not then add 5.1 support.
5910 if (!supports5dot1) {
5911 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5912 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5913 }
Phil Burk09bc4612016-02-24 15:58:15 -08005914 }
5915}
5916
Phil Burk00eeb322016-03-31 12:41:00 -07005917void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5918 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005919 AudioProfileVector &profiles)
5920{
5921 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005922
François Gaffie112b0af2015-11-19 16:13:25 +01005923 // Format MUST be checked first to update the list of AudioProfile
5924 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005925 reply = mpClientInterface->getParameters(
5926 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005927 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005928 AudioParameter repliedParameters(reply);
5929 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005930 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005931 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5932 return;
5933 }
Phil Burk09bc4612016-02-24 15:58:15 -08005934 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005935 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005936 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005937 }
Phil Burk09bc4612016-02-24 15:58:15 -08005938 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005939 }
François Gaffie112b0af2015-11-19 16:13:25 +01005940
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005941 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005942 ChannelsVector channelMasks;
5943 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005944 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005945 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005946
5947 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005948 reply = mpClientInterface->getParameters(
5949 ioHandle,
5950 requestedParameters.toString() + ";" +
5951 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005952 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005953 AudioParameter repliedParameters(reply);
5954 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005955 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005956 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005957 }
5958 }
5959 if (profiles.hasDynamicChannelsFor(format)) {
5960 reply = mpClientInterface->getParameters(ioHandle,
5961 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005962 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005963 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005964 AudioParameter repliedParameters(reply);
5965 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005966 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005967 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005968 if (device == AUDIO_DEVICE_OUT_HDMI) {
5969 filterSurroundChannelMasks(&channelMasks);
5970 }
François Gaffie112b0af2015-11-19 16:13:25 +01005971 }
5972 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005973 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005974 }
5975}
Eric Laurentd60560a2015-04-10 11:31:20 -07005976
Mikhail Naganovdc769682018-05-04 15:34:08 -07005977status_t AudioPolicyManager::installPatch(const char *caller,
5978 audio_patch_handle_t *patchHandle,
5979 AudioIODescriptorInterface *ioDescriptor,
5980 const struct audio_patch *patch,
5981 int delayMs)
5982{
5983 ssize_t index = mAudioPatches.indexOfKey(
5984 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5985 *patchHandle : ioDescriptor->getPatchHandle());
5986 sp<AudioPatch> patchDesc;
5987 status_t status = installPatch(
5988 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5989 if (status == NO_ERROR) {
5990 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5991 }
5992 return status;
5993}
5994
5995status_t AudioPolicyManager::installPatch(const char *caller,
5996 ssize_t index,
5997 audio_patch_handle_t *patchHandle,
5998 const struct audio_patch *patch,
5999 int delayMs,
6000 uid_t uid,
6001 sp<AudioPatch> *patchDescPtr)
6002{
6003 sp<AudioPatch> patchDesc;
6004 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6005 if (index >= 0) {
6006 patchDesc = mAudioPatches.valueAt(index);
6007 afPatchHandle = patchDesc->mAfPatchHandle;
6008 }
6009
6010 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6011 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6012 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6013 if (status == NO_ERROR) {
6014 if (index < 0) {
6015 patchDesc = new AudioPatch(patch, uid);
6016 addAudioPatch(patchDesc->mHandle, patchDesc);
6017 } else {
6018 patchDesc->mPatch = *patch;
6019 }
6020 patchDesc->mAfPatchHandle = afPatchHandle;
6021 if (patchHandle) {
6022 *patchHandle = patchDesc->mHandle;
6023 }
6024 nextAudioPortGeneration();
6025 mpClientInterface->onAudioPatchListUpdate();
6026 }
6027 if (patchDescPtr) *patchDescPtr = patchDesc;
6028 return status;
6029}
6030
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006031} // namespace android