blob: 6999ba52e60f42115deb3c439a5e7627e6b26035 [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;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700372 String8 reply;
373 AudioParameter param;
374 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800375
376 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
377 device, device_address, device_name);
378
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800379 // connect/disconnect only 1 device at a time
380 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
381
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800382 // Check if the device is currently connected
383 sp<DeviceDescriptor> devDesc =
384 mHwModules.getDeviceDescriptor(device, device_address, device_name);
385 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
386 if (index < 0) {
387 // Nothing to do: device is not connected
388 return NO_ERROR;
389 }
390
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700391 // For offloaded A2DP, Hw modules may have the capability to
392 // configure codecs. Check if any of the loaded hw modules
393 // supports this.
394 // If supported, send a set parameter to configure A2DP codecs
395 // and return. No need to toggle device state.
396 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
397 reply = mpClientInterface->getParameters(
398 AUDIO_IO_HANDLE_NONE,
399 String8(AudioParameter::keyReconfigA2dpSupported));
400 AudioParameter repliedParameters(reply);
401 repliedParameters.getInt(
402 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
403 if (isReconfigA2dpSupported) {
404 const String8 key(AudioParameter::keyReconfigA2dp);
405 param.add(key, String8("true"));
406 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
407 return NO_ERROR;
408 }
409 }
410
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800411 // Toggle the device state: UNAVAILABLE -> AVAILABLE
412 // This will force reading again the device configuration
413 status = setDeviceConnectionState(device,
414 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
415 device_address, device_name);
416 if (status != NO_ERROR) {
417 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
418 status);
419 return status;
420 }
421
422 status = setDeviceConnectionState(device,
423 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
424 device_address, device_name);
425 if (status != NO_ERROR) {
426 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
427 status);
428 return status;
429 }
430
431 return NO_ERROR;
432}
433
Eric Laurentdc462862016-07-19 12:29:53 -0700434uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435{
436 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700437 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700438
Andy Hunga76c7de2016-12-13 19:14:31 -0800439 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700440 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700441 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800442 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700443 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
444
445 // release existing RX patch if any
446 if (mCallRxPatch != 0) {
447 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
448 mCallRxPatch.clear();
449 }
450 // release TX patch if any
451 if (mCallTxPatch != 0) {
452 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
453 mCallTxPatch.clear();
454 }
455
456 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
457 // via setOutputDevice() on primary output.
458 // Otherwise, create two audio patches for TX and RX path.
459 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700460 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 // If the TX device is also on the primary HW module, setOutputDevice() will take care
462 // of it due to legacy implementation. If not, create a patch.
463 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
464 == AUDIO_DEVICE_NONE) {
465 createTxPatch = true;
466 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700467 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800468 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469 createTxPatch = true;
470 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700471 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800472 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
473 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700474
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800475 return muteWaitMs;
476}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700477
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
479 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700480 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700481
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482 sp<DeviceDescriptor> txSourceDeviceDesc;
483 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700484 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
485 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800486 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700487 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
488 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800489 }
490
491 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
492 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
493 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
494 // request to reuse existing output stream if one is already opened to reach the target device
495 if (output != AUDIO_IO_HANDLE_NONE) {
496 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
497 ALOG_ASSERT(!outputDesc->isDuplicated(),
498 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700499 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800500 }
501
502 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700503 // terminate active capture if on the same HW module as the call TX source device
504 // FIXME: would be better to refine to only inputs whose profile connects to the
505 // call TX device but this information is not in the audio patch and logic here must be
506 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800507 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800508 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
509 AudioSessionCollection activeSessions =
510 activeDesc->getAudioSessions(true /*activeOnly*/);
511 for (size_t j = 0; j < activeSessions.size(); j++) {
512 audio_session_t activeSession = activeSessions.keyAt(j);
513 stopInput(activeDesc->mIoHandle, activeSession);
514 releaseInput(activeDesc->mIoHandle, activeSession);
515 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700516 }
517 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700518 }
Eric Laurentdc462862016-07-19 12:29:53 -0700519
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800520 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700521 status_t status = mpClientInterface->createAudioPatch(
522 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800523 ALOGW_IF(status != NO_ERROR,
524 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
525 sp<AudioPatch> audioPatch;
526 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700527 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800528 audioPatch->mAfPatchHandle = afPatchHandle;
529 audioPatch->mUid = mUidCached;
530 }
531 return audioPatch;
532}
533
Mikhail Naganovdc769682018-05-04 15:34:08 -0700534sp<DeviceDescriptor> AudioPolicyManager::findDevice(
535 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800536 DeviceVector deviceList = devices.getDevicesFromType(device);
537 ALOG_ASSERT(!deviceList.isEmpty(),
538 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700539 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700540}
541
Eric Laurente0720872014-03-11 09:30:41 -0700542void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700543{
544 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100545 // store previous phone state for management of sonification strategy below
546 int oldState = mEngine->getPhoneState();
547
548 if (mEngine->setPhoneState(state) != NO_ERROR) {
549 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700550 return;
551 }
François Gaffie2110e042015-03-24 08:41:51 +0100552 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700553 // if leaving call state, handle special case of active streams
554 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700555 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700556 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800557 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700558 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800560
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700563 }
564
François Gaffie2110e042015-03-24 08:41:51 +0100565 /**
566 * Switching to or from incall state or switching between telephony and VoIP lead to force
567 * routing command.
568 */
569 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
570 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700573 checkA2dpSuspend();
574 checkOutputForAllStrategies();
575 updateDevicesAndOutputs();
576
Eric Laurente552edb2014-03-10 17:42:56 -0700577 int delayMs = 0;
578 if (isStateInCall(state)) {
579 nsecs_t sysTime = systemTime();
580 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700581 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700582 // mute media and sonification strategies and delay device switch by the largest
583 // latency of any output where either strategy is active.
584 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100585 if ((isStrategyActive(desc, STRATEGY_MEDIA,
586 SONIFICATION_HEADSET_MUSIC_DELAY,
587 sysTime) ||
588 isStrategyActive(desc, STRATEGY_SONIFICATION,
589 SONIFICATION_HEADSET_MUSIC_DELAY,
590 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700591 (delayMs < (int)desc->latency()*2)) {
592 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700593 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700594 setStrategyMute(STRATEGY_MEDIA, true, desc);
595 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700596 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700597 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
598 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700599 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
600 }
601 }
602
Eric Laurent87ffa392015-05-22 10:32:38 -0700603 if (hasPrimaryOutput()) {
604 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
605 // the device returned is not necessarily reachable via this output
606 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
607 // force routing command to audio hardware when ending call
608 // even if no device change is needed
609 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
610 rxDevice = mPrimaryOutput->device();
611 }
Eric Laurente552edb2014-03-10 17:42:56 -0700612
Eric Laurent87ffa392015-05-22 10:32:38 -0700613 if (state == AUDIO_MODE_IN_CALL) {
614 updateCallRouting(rxDevice, delayMs);
615 } else if (oldState == AUDIO_MODE_IN_CALL) {
616 if (mCallRxPatch != 0) {
617 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
618 mCallRxPatch.clear();
619 }
620 if (mCallTxPatch != 0) {
621 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
622 mCallTxPatch.clear();
623 }
624 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
625 } else {
626 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700627 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700628 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700629
630 // reevaluate routing on all outputs in case tracks have been started during the call
631 for (size_t i = 0; i < mOutputs.size(); i++) {
632 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
633 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
634 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800635 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700636 }
637 }
638
Eric Laurente552edb2014-03-10 17:42:56 -0700639 // if entering in call state, handle special case of active streams
640 // pertaining to sonification strategy see handleIncallSonification()
641 if (isStateInCall(state)) {
642 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800643 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700645 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700646
647 // force reevaluating accessibility routing when call starts
648 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700649 }
650
651 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700652 if (state == AUDIO_MODE_RINGTONE &&
653 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700654 mLimitRingtoneVolume = true;
655 } else {
656 mLimitRingtoneVolume = false;
657 }
658}
659
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700660audio_mode_t AudioPolicyManager::getPhoneState() {
661 return mEngine->getPhoneState();
662}
663
Eric Laurente0720872014-03-11 09:30:41 -0700664void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700665 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700666{
François Gaffie2110e042015-03-24 08:41:51 +0100667 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700668 if (config == mEngine->getForceUse(usage)) {
669 return;
670 }
Eric Laurente552edb2014-03-10 17:42:56 -0700671
François Gaffie2110e042015-03-24 08:41:51 +0100672 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
673 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
674 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700675 }
François Gaffie2110e042015-03-24 08:41:51 +0100676 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
677 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
678 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700679
680 // check for device and output changes triggered by new force usage
681 checkA2dpSuspend();
682 checkOutputForAllStrategies();
683 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800684
Eric Laurentdc462862016-07-19 12:29:53 -0700685 //FIXME: workaround for truncated touch sounds
686 // to be removed when the problem is handled by system UI
687 uint32_t delayMs = 0;
688 uint32_t waitMs = 0;
689 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
690 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
691 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700692 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700693 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700694 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695 }
Eric Laurente552edb2014-03-10 17:42:56 -0700696 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700697 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
698 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
699 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700700 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
701 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700702 }
Eric Laurente552edb2014-03-10 17:42:56 -0700703 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700704 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700705 }
706 }
707
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800708 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800709 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700710 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800711 if (activeDesc->mProfile->getSupportedDevices().types() &
712 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
713 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700714 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800715 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700716 }
Eric Laurente552edb2014-03-10 17:42:56 -0700717 }
Eric Laurente552edb2014-03-10 17:42:56 -0700718}
719
Eric Laurente0720872014-03-11 09:30:41 -0700720void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700721{
722 ALOGV("setSystemProperty() property %s, value %s", property, value);
723}
724
725// Find a direct output profile compatible with the parameters passed, even if the input flags do
726// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800727sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700728 audio_devices_t device,
729 uint32_t samplingRate,
730 audio_format_t format,
731 audio_channel_mask_t channelMask,
732 audio_output_flags_t flags)
733{
Eric Laurent861a6282015-05-18 15:40:16 -0700734 // only retain flags that will drive the direct output profile selection
735 // if explicitly requested
736 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700737 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
738 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700739 flags =
740 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
741
742 sp<IOProfile> profile;
743
Mikhail Naganovd4120142017-12-06 15:49:22 -0800744 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800745 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700746 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700747 samplingRate, NULL /*updatedSamplingRate*/,
748 format, NULL /*updatedFormat*/,
749 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700750 flags)) {
751 continue;
752 }
753 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100754 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700755 continue;
756 }
757 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100758 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700759 continue;
760 }
761 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100762 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700763 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700764 }
Eric Laurente552edb2014-03-10 17:42:56 -0700765 }
766 }
Eric Laurent861a6282015-05-18 15:40:16 -0700767 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700768}
769
Eric Laurentf4e63452017-11-06 19:31:46 +0000770audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700771{
Eric Laurent3b73df72014-03-11 09:06:29 -0700772 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700773 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800774
775 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
776 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
777 // format, flags, etc. This may result in some discrepancy for functions that utilize
778 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
779 // and AudioSystem::getOutputSamplingRate().
780
Eric Laurentf4e63452017-11-06 19:31:46 +0000781 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
782 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700783
Eric Laurentf4e63452017-11-06 19:31:46 +0000784 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
785 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786}
787
Eric Laurente83b55d2014-11-14 10:06:21 -0800788status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
789 audio_io_handle_t *output,
790 audio_session_t session,
791 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700792 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800793 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200794 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700795 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700797{
Eric Laurente83b55d2014-11-14 10:06:21 -0800798 audio_attributes_t attributes;
799 if (attr != NULL) {
800 if (!isValidAttributes(attr)) {
801 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
802 attr->usage, attr->content_type, attr->flags,
803 attr->tags);
804 return BAD_VALUE;
805 }
806 attributes = *attr;
807 } else {
808 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
809 ALOGE("getOutputForAttr(): invalid stream type");
810 return BAD_VALUE;
811 }
812 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700813 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800814
815 // TODO: check for existing client for this port ID
816 if (*portId == AUDIO_PORT_HANDLE_NONE) {
817 *portId = AudioPort::getNextUniqueId();
818 }
819
Eric Laurentc75307b2015-03-17 15:29:32 -0700820 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800821 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100822 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800823 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100824 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800825 }
François Gaffie036e1e92015-03-19 10:16:24 +0100826 *stream = streamTypefromAttributesInt(&attributes);
827 *output = desc->mIoHandle;
828 ALOGV("getOutputForAttr() returns output %d", *output);
829 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800830 }
831 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
832 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
833 return BAD_VALUE;
834 }
835
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700836 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
837 " session %d selectedDeviceId %d",
838 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700839 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700840
841 *stream = streamTypefromAttributesInt(&attributes);
842
843 // Explicit routing?
844 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700845 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800846 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700847 }
848 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700851 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852
Eric Laurente83b55d2014-11-14 10:06:21 -0800853 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200854 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700855 }
856
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800857 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
858 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200859 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700860
Andy Hungc88b0642018-04-27 15:42:35 -0700861 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800862 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700863 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800864 return INVALID_OPERATION;
865 }
Paul McLeanaa981192015-03-21 09:55:15 -0700866
Eric Laurent2ac76942017-06-22 17:17:09 -0700867 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
868 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
869 : AUDIO_PORT_HANDLE_NONE;
870
871 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
872
Eric Laurente83b55d2014-11-14 10:06:21 -0800873 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700874}
875
876audio_io_handle_t AudioPolicyManager::getOutputForDevice(
877 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800878 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800880 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200881 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882{
Andy Hungc88b0642018-04-27 15:42:35 -0700883 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700884 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886 // open a direct output if required by specified parameters
887 //force direct flag if offload flag is set: offloading implies a direct output stream
888 // and all common behaviors are driven by checking only the direct flag
889 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200890 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
891 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700892 }
Nadav Bar766fb022018-01-07 12:18:03 +0200893 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
894 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700895 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800896 // only allow deep buffering for music stream type
897 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200898 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700899 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200900 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700901 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
902 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200903 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800904 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700905 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200906 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700907 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800908 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200909 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700910 AUDIO_OUTPUT_FLAG_DIRECT);
911 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200912 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
913 stream == AUDIO_STREAM_MUSIC &&
914 audio_is_linear_pcm(config->format) &&
915 isInCall()) {
916 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700917 }
Eric Laurente552edb2014-03-10 17:42:56 -0700918
Nadav Bar766fb022018-01-07 12:18:03 +0200919
Eric Laurentb732cf52014-09-24 19:08:21 -0700920 sp<IOProfile> profile;
921
922 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700923 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200924 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800925 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
926 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700927 goto non_direct_output;
928 }
929
Andy Hung2ddee192015-12-18 17:34:44 -0800930 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
931 // This prevents creating an offloaded track and tearing it down immediately after start
932 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700933 // FIXME: We should check the audio session here but we do not have it in this context.
934 // This may prevent offloading in rare situations where effects are left active by apps
935 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700936
Nadav Bar766fb022018-01-07 12:18:03 +0200937 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800938 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700939 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800940 config->sample_rate,
941 config->format,
942 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200943 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 }
945
Eric Laurent1c333e22014-05-20 10:48:17 -0700946 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700947 // exclusive outputs for MMAP and Offload are enforced by different session ids.
948 for (size_t i = 0; i < mOutputs.size(); i++) {
949 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
950 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
951 // reuse direct output if currently open by the same client
952 // and configured with same parameters
953 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700954 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700955 (config->channel_mask == desc->mChannelMask) &&
956 (session == desc->mDirectClientSession)) {
957 desc->mDirectOpenCount++;
958 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
959 mOutputs.keyAt(i), session);
960 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 }
963 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800964
965 if (!profile->canOpenNewIo()) {
966 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
Eric Laurent861a6282015-05-18 15:40:16 -0700968
Eric Laurent3974e3b2017-12-07 17:58:43 -0800969 sp<SwAudioOutputDescriptor> outputDesc =
970 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800971
972 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
973 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
974 : String8("");
975
Nadav Bar766fb022018-01-07 12:18:03 +0200976 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700977
978 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800980 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700981 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800982 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
983 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
984 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
985 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
986 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700987 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800988 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700989 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800990 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800991 if (audio_is_linear_pcm(config->format) &&
992 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800993 goto non_direct_output;
994 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700995 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700996 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700997 outputDesc->mRefCount[stream] = 0;
998 outputDesc->mStopTime[stream] = 0;
999 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001000 outputDesc->mDirectClientSession = session;
1001
Eric Laurente552edb2014-03-10 17:42:56 -07001002 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001003 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001004 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001005 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001006 return output;
1007 }
1008
Eric Laurentb732cf52014-09-24 19:08:21 -07001009non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001010
1011 // A request for HW A/V sync cannot fallback to a mixed output because time
1012 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001013 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001014 return AUDIO_IO_HANDLE_NONE;
1015 }
1016
Eric Laurente552edb2014-03-10 17:42:56 -07001017 // ignoring channel mask due to downmix capability in mixer
1018
1019 // open a non direct output
1020
1021 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001022 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001023 // get which output is suitable for the specified stream. The actual
1024 // routing change will happen when startOutput() will be called
1025 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1026
Eric Laurent8838a382014-09-08 16:44:28 -07001027 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001028 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1029 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001031 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001032 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001033 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
Eric Laurente552edb2014-03-10 17:42:56 -07001035 return output;
1036}
1037
Eric Laurente0720872014-03-11 09:30:41 -07001038audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001039 audio_output_flags_t flags,
1040 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001041{
1042 // select one output among several that provide a path to a particular device or set of
1043 // devices (the list was previously build by getOutputsForDevice()).
1044 // The priority is as follows:
1045 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001046 // 2: the output with the bit depth the closest to the requested one
1047 // 3: the primary output
1048 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001049
1050 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001051 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
1053 if (outputs.size() == 1) {
1054 return outputs[0];
1055 }
1056
1057 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001058 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1059 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1060 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001061 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1062 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001063
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001064 for (audio_io_handle_t output : outputs) {
1065 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001066 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001067 // if a valid format is specified, skip output if not compatible
1068 if (format != AUDIO_FORMAT_INVALID) {
1069 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001070 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001071 continue;
1072 }
1073 } else if (!audio_is_linear_pcm(format)) {
1074 continue;
1075 }
Eric Laurente6930022016-02-11 10:20:40 -08001076 if (AudioPort::isBetterFormatMatch(
1077 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001078 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001079 bestFormat = outputDesc->mFormat;
1080 }
Eric Laurent8838a382014-09-08 16:44:28 -07001081 }
1082
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001083 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001084 if (commonFlags >= maxCommonFlags) {
1085 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001086 if (format != AUDIO_FORMAT_INVALID
1087 && AudioPort::isBetterFormatMatch(
1088 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001089 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001090 bestFormatForFlags = outputDesc->mFormat;
1091 }
1092 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001093 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001094 maxCommonFlags = commonFlags;
1095 bestFormatForFlags = outputDesc->mFormat;
1096 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001097 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001098 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001099 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001100 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001101 }
1102 }
1103 }
1104
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001105 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001106 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001107 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001108 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001109 return outputForFormat;
1110 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001111 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001112 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001113 }
1114
1115 return outputs[0];
1116}
1117
Eric Laurente0720872014-03-11 09:30:41 -07001118status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001119 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001120 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001121{
Paul McLeanaa981192015-03-21 09:55:15 -07001122 ALOGV("startOutput() output %d, stream %d, session %d",
1123 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001124 ssize_t index = mOutputs.indexOfKey(output);
1125 if (index < 0) {
1126 ALOGW("startOutput() unknown output %d", output);
1127 return BAD_VALUE;
1128 }
1129
Eric Laurentc75307b2015-03-17 15:29:32 -07001130 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1131
Eric Laurent733ce942017-12-07 12:18:25 -08001132 status_t status = outputDesc->start();
1133 if (status != NO_ERROR) {
1134 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001135 }
1136
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001137 // Routing?
1138 mOutputRoutes.incRouteActivity(session);
1139
Eric Laurentc75307b2015-03-17 15:29:32 -07001140 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001141 AudioMix *policyMix = NULL;
1142 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001143 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001144 policyMix = outputDesc->mPolicyMix;
1145 address = policyMix->mDeviceAddress.string();
1146 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1147 newDevice = policyMix->mDeviceType;
1148 } else {
1149 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1150 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001151 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001152 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001153 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001154 } else {
1155 newDevice = AUDIO_DEVICE_NONE;
1156 }
1157
1158 uint32_t delayMs = 0;
1159
Eric Laurent733ce942017-12-07 12:18:25 -08001160 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001161
1162 if (status != NO_ERROR) {
1163 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001164 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001165 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001166 }
1167 // Automatically enable the remote submix input when output is started on a re routing mix
1168 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001169 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1170 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001171 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1172 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001173 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001174 "remote-submix");
1175 }
1176
1177 if (delayMs != 0) {
1178 usleep(delayMs * 1000);
1179 }
1180
1181 return status;
1182}
1183
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001184status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001185 audio_stream_type_t stream,
1186 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001187 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001188 uint32_t *delayMs)
1189{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001190 // cannot start playback of STREAM_TTS if any other output is being used
1191 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001192
1193 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001194 if (stream == AUDIO_STREAM_TTS) {
1195 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001196 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001197 return INVALID_OPERATION;
1198 } else {
1199 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1200 }
1201 } else {
1202 // some playback other than beacon starts
1203 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1204 }
1205
Eric Laurent77305a62016-07-25 16:39:22 -07001206 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001207 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001208 bool force = !outputDesc->isActive() &&
1209 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001210
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001211 // requiresMuteCheck is false when we can bypass mute strategy.
1212 // It covers a common case when there is no materially active audio
1213 // and muting would result in unnecessary delay and dropped audio.
1214 const uint32_t outputLatencyMs = outputDesc->latency();
1215 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1216
Eric Laurente552edb2014-03-10 17:42:56 -07001217 // increment usage count for this stream on the requested output:
1218 // NOTE that the usage count is the same for duplicated output and hardware output which is
1219 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1220 outputDesc->changeRefCount(stream, 1);
1221
Eric Laurent36829f92017-04-07 19:04:42 -07001222 if (stream == AUDIO_STREAM_MUSIC) {
1223 selectOutputForMusicEffects();
1224 }
1225
Eric Laurent493404d2015-04-21 15:07:36 -07001226 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001227 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001228 if (device == AUDIO_DEVICE_NONE) {
1229 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001230 }
Eric Laurent36829f92017-04-07 19:04:42 -07001231
Eric Laurente552edb2014-03-10 17:42:56 -07001232 routing_strategy strategy = getStrategy(stream);
1233 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001234 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1235 (beaconMuteLatency > 0);
1236 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001237 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001238 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001239 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001240 // An output has a shared device if
1241 // - managed by the same hw module
1242 // - supports the currently selected device
1243 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1244 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1245
Eric Laurent77305a62016-07-25 16:39:22 -07001246 // force a device change if any other output is:
1247 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001248 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001249 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001250 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001251 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001252 // change the device currently selected by the other output.
1253 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001254 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001255 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001256 force = true;
1257 }
1258 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001259 // a notification so that audio focus effect can propagate, or that a mute/unmute
1260 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001261 const uint32_t latencyMs = desc->latency();
1262 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1263
1264 if (shouldWait && isActive && (waitMs < latencyMs)) {
1265 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001266 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001267
1268 // Require mute check if another output is on a shared device
1269 // and currently active to have proper drain and avoid pops.
1270 // Note restoring AudioTracks onto this output needs to invoke
1271 // a volume ramp if there is no mute.
1272 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001273 }
1274 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001275
1276 const uint32_t muteWaitMs =
1277 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001278
1279 // handle special case for sonification while in call
1280 if (isInCall()) {
1281 handleIncallSonification(stream, true, false);
1282 }
1283
1284 // apply volume rules for current stream and device if necessary
1285 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001286 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001287 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001288 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001289
1290 // update the outputs if starting an output with a stream that can affect notification
1291 // routing
1292 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001293
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001294 // force reevaluating accessibility routing when ringtone or alarm starts
1295 if (strategy == STRATEGY_SONIFICATION) {
1296 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1297 }
Eric Laurentdc462862016-07-19 12:29:53 -07001298
1299 if (waitMs > muteWaitMs) {
1300 *delayMs = waitMs - muteWaitMs;
1301 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001302
1303 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1304 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1305 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1306 // change occurs after the MixerThread starts and causes a stream volume
1307 // glitch.
1308 //
1309 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001310 }
Eric Laurentdc462862016-07-19 12:29:53 -07001311
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001312 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1313 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1314 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1315 }
1316
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001317 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1318 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1319 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1320 }
1321
Eric Laurente552edb2014-03-10 17:42:56 -07001322 return NO_ERROR;
1323}
1324
1325
Eric Laurente0720872014-03-11 09:30:41 -07001326status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001327 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001328 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001329{
1330 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1331 ssize_t index = mOutputs.indexOfKey(output);
1332 if (index < 0) {
1333 ALOGW("stopOutput() unknown output %d", output);
1334 return BAD_VALUE;
1335 }
1336
Eric Laurentc75307b2015-03-17 15:29:32 -07001337 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001338
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (outputDesc->mRefCount[stream] == 1) {
1340 // Automatically disable the remote submix input when output is stopped on a
1341 // re routing mix of type MIX_TYPE_RECORDERS
1342 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1343 outputDesc->mPolicyMix != NULL &&
1344 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1345 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1346 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001347 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001348 "remote-submix");
1349 }
1350 }
1351
1352 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001353 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001354 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 int activityCount = mOutputRoutes.decRouteActivity(session);
1356 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1357
1358 if (forceDeviceUpdate) {
1359 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1360 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001361 }
1362
Eric Laurent3974e3b2017-12-07 17:58:43 -08001363 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1364
Eric Laurent733ce942017-12-07 12:18:25 -08001365 if (status == NO_ERROR ) {
1366 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001367 }
1368 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001369}
1370
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001371status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 audio_stream_type_t stream,
1373 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001374{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001375 // always handle stream stop, check which stream type is stopping
1376 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1377
Eric Laurente552edb2014-03-10 17:42:56 -07001378 // handle special case for sonification while in call
1379 if (isInCall()) {
1380 handleIncallSonification(stream, false, false);
1381 }
1382
1383 if (outputDesc->mRefCount[stream] > 0) {
1384 // decrement usage count of this stream on the output
1385 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001386
Eric Laurente552edb2014-03-10 17:42:56 -07001387 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001388 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001389 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001390 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001391 // delay the device switch by twice the latency because stopOutput() is executed when
1392 // the track stop() command is received and at that time the audio track buffer can
1393 // still contain data that needs to be drained. The latency only covers the audio HAL
1394 // and kernel buffers. Also the latency does not always include additional delay in the
1395 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001396 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001397
1398 // force restoring the device selection on other active outputs if it differs from the
1399 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001400 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001401 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001402 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001403 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001404 desc->isActive() &&
1405 outputDesc->sharesHwModuleWith(desc) &&
1406 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001407 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1408 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001410 newDevice2,
1411 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001412 delayMs);
1413 // re-apply device specific volume if not done by setOutputDevice()
1414 if (!force) {
1415 applyStreamVolumes(desc, newDevice2, delayMs);
1416 }
Eric Laurente552edb2014-03-10 17:42:56 -07001417 }
1418 }
1419 // update the outputs if stopping one with a stream that can affect notification routing
1420 handleNotificationRoutingForStream(stream);
1421 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001422
1423 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1424 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1425 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1426 }
1427
Eric Laurent36829f92017-04-07 19:04:42 -07001428 if (stream == AUDIO_STREAM_MUSIC) {
1429 selectOutputForMusicEffects();
1430 }
Eric Laurente552edb2014-03-10 17:42:56 -07001431 return NO_ERROR;
1432 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001434 return INVALID_OPERATION;
1435 }
1436}
1437
Eric Laurente83b55d2014-11-14 10:06:21 -08001438void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001439 audio_stream_type_t stream __unused,
1440 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001441{
1442 ALOGV("releaseOutput() %d", output);
1443 ssize_t index = mOutputs.indexOfKey(output);
1444 if (index < 0) {
1445 ALOGW("releaseOutput() releasing unknown output %d", output);
1446 return;
1447 }
1448
Paul McLeanaa981192015-03-21 09:55:15 -07001449 // Routing
1450 mOutputRoutes.removeRoute(session);
1451
Eric Laurentc75307b2015-03-17 15:29:32 -07001452 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001453 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001454 if (desc->mDirectOpenCount <= 0) {
1455 ALOGW("releaseOutput() invalid open count %d for output %d",
1456 desc->mDirectOpenCount, output);
1457 return;
1458 }
1459 if (--desc->mDirectOpenCount == 0) {
1460 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001461 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001462 }
1463 }
1464}
1465
1466
Eric Laurentcaf7f482014-11-25 17:50:47 -08001467status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1468 audio_io_handle_t *input,
1469 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001470 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001471 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001472 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001473 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001474 input_type_t *inputType,
1475 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001476{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001477 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001478 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001479 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
Eric Laurentad2e7b92017-09-14 20:06:42 -07001481 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001482 // handle legacy remote submix case where the address was not always specified
1483 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001484 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001485 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001486 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001487 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001488
Eric Laurentfe231122017-11-17 17:48:06 -08001489 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1490 inputSource = AUDIO_SOURCE_MIC;
1491 }
1492
Paul McLean466dc8e2015-04-17 13:15:36 -06001493 // Explicit routing?
1494 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001495 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001496 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001497 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001498 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001499
Eric Laurentad2e7b92017-09-14 20:06:42 -07001500 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1501 // possible
1502 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1503 *input != AUDIO_IO_HANDLE_NONE) {
1504 ssize_t index = mInputs.indexOfKey(*input);
1505 if (index < 0) {
1506 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1507 status = BAD_VALUE;
1508 goto error;
1509 }
1510 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1511 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1512 if (audioSession == 0) {
1513 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1514 status = BAD_VALUE;
1515 goto error;
1516 }
1517 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1518 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001519 // corresponds to a new client and is only permitted from the same UID.
1520 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001521 if (audioSession->openCount() == 1) {
1522 audioSession->setUid(uid);
1523 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001524 if (!audioSession->isSilenced()) {
1525 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1526 uid, session, audioSession->uid());
1527 status = INVALID_OPERATION;
1528 goto error;
1529 }
1530 audioSession->setUid(uid);
1531 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001532 }
1533 audioSession->changeOpenCount(1);
1534 *inputType = API_INPUT_LEGACY;
1535 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1536 *portId = AudioPort::getNextUniqueId();
1537 }
1538 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1539 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1540 : AUDIO_PORT_HANDLE_NONE;
1541 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1542
1543 return NO_ERROR;
1544 }
1545
1546 *input = AUDIO_IO_HANDLE_NONE;
1547 *inputType = API_INPUT_INVALID;
1548
Eric Laurentad2e7b92017-09-14 20:06:42 -07001549 halInputSource = inputSource;
1550
1551 // TODO: check for existing client for this port ID
1552 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1553 *portId = AudioPort::getNextUniqueId();
1554 }
1555
1556 audio_devices_t device;
1557
Eric Laurentc447ded2015-01-06 08:47:05 -08001558 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001559 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001560 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1561 if (status != NO_ERROR) {
1562 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001563 }
1564 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001565 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1566 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001567 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001568 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001569 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001570 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001571 status = BAD_VALUE;
1572 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 }
Eric Laurentc722f302014-12-10 11:21:49 -08001574 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001575 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001576 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1577 // there is an external policy, but this input is attached to a mix of recorders,
1578 // meaning it receives audio injected into the framework, so the recorder doesn't
1579 // know about it and is therefore considered "legacy"
1580 *inputType = API_INPUT_LEGACY;
1581 } else {
1582 // recording a mix of players defined by an external policy, we're rerouting for
1583 // an external policy
1584 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1585 }
Eric Laurentc722f302014-12-10 11:21:49 -08001586 } else if (audio_is_remote_submix_device(device)) {
1587 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001588 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001589 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1590 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001591 } else {
1592 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001593 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001594
Eric Laurent599c7582015-12-07 18:05:55 -08001595 }
1596
1597 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001598 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001599 policyMix);
1600 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001601 status = INVALID_OPERATION;
1602 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001603 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001604
Eric Laurentad2e7b92017-09-14 20:06:42 -07001605 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001606 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1607 : AUDIO_PORT_HANDLE_NONE;
1608
1609 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1610 *input, *inputType, *selectedDeviceId);
1611
Eric Laurent599c7582015-12-07 18:05:55 -08001612 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001613
1614error:
1615 mInputRoutes.removeRoute(session);
1616 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001617}
1618
1619
1620audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1621 String8 address,
1622 audio_session_t session,
1623 uid_t uid,
1624 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001625 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001626 audio_input_flags_t flags,
1627 AudioMix *policyMix)
1628{
1629 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1630 audio_source_t halInputSource = inputSource;
1631 bool isSoundTrigger = false;
1632
1633 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1634 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1635 if (index >= 0) {
1636 input = mSoundTriggerSessions.valueFor(session);
1637 isSoundTrigger = true;
1638 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1639 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1640 } else {
1641 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001642 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001643 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001644 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001645 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001646 }
1647
Andy Hungf129b032015-04-07 13:45:50 -07001648 // find a compatible input profile (not necessarily identical in parameters)
1649 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001650 // sampling rate and flags may be updated by getInputProfile
1651 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1652 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001653 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001654 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001655 audio_input_flags_t profileFlags = flags;
1656 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001657 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001658 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001659 profileSamplingRate, profileFormat, profileChannelMask,
1660 profileFlags);
1661 if (profile != 0) {
1662 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001663 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1664 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001665 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1666 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1667 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001668 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001669 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1670 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001671 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001672 }
Eric Laurente552edb2014-03-10 17:42:56 -07001673 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001674 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001675 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001676 if (samplingRate == 0) {
1677 samplingRate = profileSamplingRate;
1678 }
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurent322b4d22015-04-03 15:57:54 -07001680 if (profile->getModuleHandle() == 0) {
1681 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001682 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001683 }
1684
Eric Laurent599c7582015-12-07 18:05:55 -08001685 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001686 inputSource,
1687 config->format,
1688 samplingRate,
1689 config->channel_mask,
1690 flags,
1691 uid,
1692 isSoundTrigger,
1693 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001694
Eric Laurent74708e72017-04-07 17:13:42 -07001695// FIXME: disable concurrent capture until UI is ready
1696#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001697 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001698 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001699 for (size_t i = 0; i < mInputs.size(); i++) {
1700 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001701 // reuse input if:
1702 // - it shares the same profile
1703 // AND
1704 // - it is not a reroute submix input
1705 // AND
1706 // - it is: not used for sound trigger
1707 // OR
1708 // used for sound trigger and all clients use the same session ID
1709 //
1710 if ((profile == desc->mProfile) &&
1711 (isSoundTrigger == desc->isSoundTrigger()) &&
1712 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001713
1714 sp<AudioSession> as = desc->getAudioSession(session);
1715 if (as != 0) {
1716 // do not allow unmatching properties on same session
1717 if (as->matches(audioSession)) {
1718 as->changeOpenCount(1);
1719 } else {
1720 ALOGW("getInputForDevice() record with different attributes"
1721 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001722 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001723 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001724 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001725 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001726 }
Eric Laurentbb948092017-01-23 18:33:30 -08001727
Eric Laurent555530a2017-02-07 18:17:24 -08001728 // Reuse the already opened input stream on this profile if:
1729 // - the new capture source is background OR
1730 // - the path requested configurations match OR
1731 // - the new source priority is less than the highest source priority on this input
1732 // If the input stream cannot be reused, close it before opening a new stream
1733 // on the same profile for the new client so that the requested path configuration
1734 // can be selected.
1735 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001736 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001737 desc->mChannelMask != config->channel_mask ||
1738 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001739 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001740 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001741 reusedInputDesc = desc;
1742 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001743 } else {
1744 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001745 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1746 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001747 }
Eric Laurent599c7582015-12-07 18:05:55 -08001748 }
1749 }
Eric Laurent599c7582015-12-07 18:05:55 -08001750
Eric Laurent555530a2017-02-07 18:17:24 -08001751 if (reusedInputDesc != 0) {
1752 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1753 for (size_t j = 0; j < sessions.size(); j++) {
1754 audio_session_t currentSession = sessions.keyAt(j);
1755 stopInput(reusedInputDesc->mIoHandle, currentSession);
1756 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1757 }
1758 }
Eric Laurent74708e72017-04-07 17:13:42 -07001759#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001760
Eric Laurent3974e3b2017-12-07 17:58:43 -08001761 if (!profile->canOpenNewIo()) {
1762 return AUDIO_IO_HANDLE_NONE;
1763 }
1764
Eric Laurentfe231122017-11-17 17:48:06 -08001765 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001766
Eric Laurentfe231122017-11-17 17:48:06 -08001767 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1768 lConfig.sample_rate = profileSamplingRate;
1769 lConfig.channel_mask = profileChannelMask;
1770 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001771
Eric Laurent53b810e2017-12-10 17:25:10 -08001772 if (address == "") {
1773 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1774 // the inputs vector must be of size >= 1, but we don't want to crash here
1775 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1776 }
1777
Eric Laurentfe231122017-11-17 17:48:06 -08001778 status_t status = inputDesc->open(&lConfig, device, address,
1779 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001780
1781 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001782 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001783 (profileSamplingRate != lConfig.sample_rate) ||
1784 !audio_formats_match(profileFormat, lConfig.format) ||
1785 (profileChannelMask != lConfig.channel_mask)) {
1786 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001787 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001788 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001789 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001790 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001791 }
Eric Laurent599c7582015-12-07 18:05:55 -08001792 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001793 }
1794
Eric Laurentc722f302014-12-10 11:21:49 -08001795 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001796 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001797
Eric Laurent599c7582015-12-07 18:05:55 -08001798 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001799 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001800
Eric Laurent599c7582015-12-07 18:05:55 -08001801 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001802}
1803
Eric Laurentbb948092017-01-23 18:33:30 -08001804//static
1805bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1806{
1807 return (source == AUDIO_SOURCE_HOTWORD) ||
1808 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1809 (source == AUDIO_SOURCE_FM_TUNER);
1810}
1811
Eric Laurentfb66dd92016-01-28 18:32:03 -08001812bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1813 const sp<AudioSession>& audioSession)
1814{
1815 // Do not allow capture if an active voice call is using a software patch and
1816 // the call TX source device is on the same HW module.
1817 // FIXME: would be better to refine to only inputs whose profile connects to the
1818 // call TX device but this information is not in the audio patch
1819 if (mCallTxPatch != 0 &&
1820 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1821 return false;
1822 }
1823
1824 // starting concurrent capture is enabled if:
1825 // 1) capturing for re-routing
1826 // 2) capturing for HOTWORD source
1827 // 3) capturing for FM TUNER source
1828 // 3) All other active captures are either for re-routing or HOTWORD
1829
1830 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001831 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001832 return true;
1833 }
1834
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001835 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001836 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001837 !is_virtual_input_device(activeInput->mDevice)) {
1838 return false;
1839 }
1840 }
1841
1842 return true;
1843}
1844
Chris Thornton2b864642017-06-27 21:26:07 -07001845// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1846bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1847 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1848 bool soundTriggerSupportsConcurrentCapture = false;
1849 unsigned int numModules = 0;
1850 struct sound_trigger_module_descriptor* nModules = NULL;
1851
1852 status_t status = SoundTrigger::listModules(nModules, &numModules);
1853 if (status == NO_ERROR && numModules != 0) {
1854 nModules = (struct sound_trigger_module_descriptor*) calloc(
1855 numModules, sizeof(struct sound_trigger_module_descriptor));
1856 if (nModules == NULL) {
1857 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1858 // ram the next time this function is called.
1859 ALOGE("Failed to allocate buffer for module descriptors");
1860 return false;
1861 }
1862
1863 status = SoundTrigger::listModules(nModules, &numModules);
1864 if (status == NO_ERROR) {
1865 soundTriggerSupportsConcurrentCapture = true;
1866 for (size_t i = 0; i < numModules; ++i) {
1867 soundTriggerSupportsConcurrentCapture &=
1868 nModules[i].properties.concurrent_capture;
1869 }
1870 }
1871 free(nModules);
1872 }
1873 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1874 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1875 }
1876 return mSoundTriggerSupportsConcurrentCapture;
1877}
1878
Eric Laurentfb66dd92016-01-28 18:32:03 -08001879
Eric Laurent4dc68062014-07-28 17:26:49 -07001880status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001881 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001882 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001883 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001884{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001885
1886 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1887 input, session, silenced, *concurrency);
1888
Eric Laurentfb66dd92016-01-28 18:32:03 -08001889 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001890
Eric Laurente552edb2014-03-10 17:42:56 -07001891 ssize_t index = mInputs.indexOfKey(input);
1892 if (index < 0) {
1893 ALOGW("startInput() unknown input %d", input);
1894 return BAD_VALUE;
1895 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001896 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001897
Eric Laurent599c7582015-12-07 18:05:55 -08001898 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1899 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001900 ALOGW("startInput() unknown session %d on input %d", session, input);
1901 return BAD_VALUE;
1902 }
1903
Eric Laurent74708e72017-04-07 17:13:42 -07001904// FIXME: disable concurrent capture until UI is ready
1905#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001906 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1907 ALOGW("startInput(%d) failed: other input already started", input);
1908 return INVALID_OPERATION;
1909 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001910
Eric Laurentfb66dd92016-01-28 18:32:03 -08001911 if (isInCall()) {
1912 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1913 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001914 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001915 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001916 }
Eric Laurent74708e72017-04-07 17:13:42 -07001917#else
1918 if (!is_virtual_input_device(inputDesc->mDevice)) {
1919 if (mCallTxPatch != 0 &&
1920 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1921 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001922 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001923 return INVALID_OPERATION;
1924 }
1925
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001926 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001927
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001928 // If a UID is idle and records silence and another not silenced recording starts
1929 // from another UID (idle or active) we stop the current idle UID recording in
1930 // favor of the new one - "There can be only one" TM
1931 if (!silenced) {
1932 for (const auto& activeDesc : activeInputs) {
1933 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1934 activeDesc->getId() == inputDesc->getId()) {
1935 continue;
1936 }
1937
1938 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1939 true /*activeOnly*/);
1940 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1941 if (activeSession->isSilenced()) {
1942 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1943 audio_session_t activeSessionId = activeSession->session();
1944 stopInput(activeInput, activeSessionId);
1945 releaseInput(activeInput, activeSessionId);
1946 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1947 activeInputs = mInputs.getActiveInputs();
1948 }
1949 }
1950 }
1951
1952 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001953 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1954 activeDesc->getId() == inputDesc->getId()) {
1955 continue;
1956 }
1957
Eric Laurent74708e72017-04-07 17:13:42 -07001958 audio_source_t activeSource = activeDesc->inputSource(true);
1959 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1960 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1961 if (activeDesc->hasPreemptedSession(session)) {
1962 ALOGW("startInput(%d) failed for HOTWORD: "
1963 "other input %d already started for HOTWORD",
1964 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001965 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001966 return INVALID_OPERATION;
1967 }
1968 } else {
1969 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1970 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001971 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001972 return INVALID_OPERATION;
1973 }
1974 } else {
1975 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1976 ALOGW("startInput(%d) failed: other input %d already started",
1977 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001978 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001979 return INVALID_OPERATION;
1980 }
1981 }
1982 }
1983
Chris Thornton2b864642017-06-27 21:26:07 -07001984 // We only need to check if the sound trigger session supports concurrent capture if the
1985 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1986 // that's running.
1987 const bool allowConcurrentWithSoundTrigger =
1988 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1989
Eric Laurent74708e72017-04-07 17:13:42 -07001990 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001991 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001992 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1993 continue;
1994 }
1995
Eric Laurent74708e72017-04-07 17:13:42 -07001996 audio_source_t activeSource = activeDesc->inputSource(true);
1997 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1998 AudioSessionCollection activeSessions =
1999 activeDesc->getAudioSessions(true /*activeOnly*/);
2000 audio_session_t activeSession = activeSessions.keyAt(0);
2001 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2002 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002003 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002004 sessions.add(activeSession);
2005 inputDesc->setPreemptedSessions(sessions);
2006 stopInput(activeHandle, activeSession);
2007 releaseInput(activeHandle, activeSession);
2008 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2009 input, activeDesc->mIoHandle);
2010 }
2011 }
2012 }
2013#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002014
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002015 // Make sure we start with the correct silence state
2016 audioSession->setSilenced(silenced);
2017
Eric Laurent313d1e72016-01-29 09:56:57 -08002018 // increment activity count before calling getNewInputDevice() below as only active sessions
2019 // are considered for device selection
2020 audioSession->changeActiveCount(1);
2021
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002022 // Routing?
2023 mInputRoutes.incRouteActivity(session);
2024
Eric Laurent2157f5b2018-04-25 18:33:02 -07002025 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002026 // indicate active capture to sound trigger service if starting capture from a mic on
2027 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002028 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002029 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002030
Eric Laurent733ce942017-12-07 12:18:25 -08002031 status_t status = inputDesc->start();
2032 if (status != NO_ERROR) {
2033 mInputRoutes.decRouteActivity(session);
2034 audioSession->changeActiveCount(-1);
2035 return status;
2036 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002037
Eric Laurent733ce942017-12-07 12:18:25 -08002038 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002039 // if input maps to a dynamic policy with an activity listener, notify of state change
2040 if ((inputDesc->mPolicyMix != NULL)
2041 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2042 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2043 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002044 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002045
Eric Laurentf7c50102016-09-30 15:19:43 -07002046 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2047 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002048 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002049 SoundTrigger::setCaptureState(true);
2050 }
2051
2052 // automatically enable the remote submix output when input is started if not
2053 // used by a policy mix of type MIX_TYPE_RECORDERS
2054 // For remote submix (a virtual device), we open only one input per capture request.
2055 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2056 String8 address = String8("");
2057 if (inputDesc->mPolicyMix == NULL) {
2058 address = String8("0");
2059 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2060 address = inputDesc->mPolicyMix->mDeviceAddress;
2061 }
2062 if (address != "") {
2063 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2064 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2065 address, "remote-submix");
2066 }
Eric Laurentc722f302014-12-10 11:21:49 -08002067 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002068 }
Eric Laurente552edb2014-03-10 17:42:56 -07002069 }
2070
Eric Laurent599c7582015-12-07 18:05:55 -08002071 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002072
Eric Laurente552edb2014-03-10 17:42:56 -07002073 return NO_ERROR;
2074}
2075
Eric Laurent4dc68062014-07-28 17:26:49 -07002076status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2077 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002078{
2079 ALOGV("stopInput() input %d", input);
2080 ssize_t index = mInputs.indexOfKey(input);
2081 if (index < 0) {
2082 ALOGW("stopInput() unknown input %d", input);
2083 return BAD_VALUE;
2084 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002085 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Eric Laurent599c7582015-12-07 18:05:55 -08002087 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002088 if (index < 0) {
2089 ALOGW("stopInput() unknown session %d on input %d", session, input);
2090 return BAD_VALUE;
2091 }
2092
Eric Laurent599c7582015-12-07 18:05:55 -08002093 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002094 ALOGW("stopInput() input %d already stopped", input);
2095 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002096 }
2097
Eric Laurent599c7582015-12-07 18:05:55 -08002098 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002099
2100 // Routing?
2101 mInputRoutes.decRouteActivity(session);
2102
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002103 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002104 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002105 if (inputDesc->isActive()) {
2106 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2107 } else {
2108 // if input maps to a dynamic policy with an activity listener, notify of state change
2109 if ((inputDesc->mPolicyMix != NULL)
2110 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2111 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2112 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002113 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002114
2115 // automatically disable the remote submix output when input is stopped if not
2116 // used by a policy mix of type MIX_TYPE_RECORDERS
2117 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2118 String8 address = String8("");
2119 if (inputDesc->mPolicyMix == NULL) {
2120 address = String8("0");
2121 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2122 address = inputDesc->mPolicyMix->mDeviceAddress;
2123 }
2124 if (address != "") {
2125 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2126 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2127 address, "remote-submix");
2128 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002129 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002130
Eric Laurentf7c50102016-09-30 15:19:43 -07002131 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002132 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002133
Eric Laurentf7c50102016-09-30 15:19:43 -07002134 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2135 // primary HW module
2136 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2137 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2138 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002139 SoundTrigger::setCaptureState(false);
2140 }
2141 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002142 }
Eric Laurente552edb2014-03-10 17:42:56 -07002143 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002144 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002145}
2146
Eric Laurent4dc68062014-07-28 17:26:49 -07002147void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2148 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002149{
2150 ALOGV("releaseInput() %d", input);
2151 ssize_t index = mInputs.indexOfKey(input);
2152 if (index < 0) {
2153 ALOGW("releaseInput() releasing unknown input %d", input);
2154 return;
2155 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002156
2157 // Routing
2158 mInputRoutes.removeRoute(session);
2159
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002160 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2161 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002162
Eric Laurent599c7582015-12-07 18:05:55 -08002163 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002164 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002165 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2166 return;
2167 }
Eric Laurent599c7582015-12-07 18:05:55 -08002168
2169 if (audioSession->openCount() == 0) {
2170 ALOGW("releaseInput() invalid open count %d on session %d",
2171 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002172 return;
2173 }
Eric Laurent599c7582015-12-07 18:05:55 -08002174
2175 if (audioSession->changeOpenCount(-1) == 0) {
2176 inputDesc->removeAudioSession(session);
2177 }
2178
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002179 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002180 ALOGV("releaseInput() exit > 0");
2181 return;
2182 }
2183
Eric Laurent05b90f82014-08-27 15:32:29 -07002184 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002185 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002186 ALOGV("releaseInput() exit");
2187}
2188
Eric Laurentd4692962014-05-05 18:13:44 -07002189void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002190 bool patchRemoved = false;
2191
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002192 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002193 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002194 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002195 if (patch_index >= 0) {
2196 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002197 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002198 mAudioPatches.removeItemsAt(patch_index);
2199 patchRemoved = true;
2200 }
Eric Laurentfe231122017-11-17 17:48:06 -08002201 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002202 }
jiabin829a00b2018-04-04 16:28:32 -07002203 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002204 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002205 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002206 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002207
2208 if (patchRemoved) {
2209 mpClientInterface->onAudioPatchListUpdate();
2210 }
Eric Laurentd4692962014-05-05 18:13:44 -07002211}
2212
Eric Laurente0720872014-03-11 09:30:41 -07002213void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002214 int indexMin,
2215 int indexMax)
2216{
2217 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002218 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002219
2220 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002221 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2222 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002223 continue;
2224 }
2225 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002226 }
Eric Laurente552edb2014-03-10 17:42:56 -07002227}
2228
Eric Laurente0720872014-03-11 09:30:41 -07002229status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002230 int index,
2231 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002232{
2233
Nadav Bar7c605f62017-12-25 00:01:52 +02002234 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2235 // app that has MODIFY_PHONE_STATE permission.
2236 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2237 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002238 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002239 return BAD_VALUE;
2240 }
2241 if (!audio_is_output_device(device)) {
2242 return BAD_VALUE;
2243 }
2244
2245 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002246 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002247
Eric Laurent1fd372e2016-04-06 14:23:53 -07002248 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002249 stream, device, index);
2250
Eric Laurent28d09f02016-03-08 10:43:05 -08002251 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002252 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2253 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002254 continue;
2255 }
2256 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2257 }
Eric Laurente552edb2014-03-10 17:42:56 -07002258
Eric Laurent1fd372e2016-04-06 14:23:53 -07002259 // update volume on all outputs and streams matching the following:
2260 // - The requested stream (or a stream matching for volume control) is active on the output
2261 // - The device (or devices) selected by the strategy corresponding to this stream includes
2262 // the requested device
2263 // - For non default requested device, currently selected device on the output is either the
2264 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002265 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2266 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002267 status_t status = NO_ERROR;
2268 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2270 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002271 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2272 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002273 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002274 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002275 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2276 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002277 continue;
2278 }
Eric Laurent794fde22016-03-11 09:50:45 -08002279 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002280 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2281 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002282 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2283 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002284 continue;
2285 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002286 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002287 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002288 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002289 applyVolume = (curDevice & curStreamDevice) != 0;
2290 } else {
2291 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002292 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002293 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002294
Eric Laurente76f29c2016-09-14 17:17:53 -07002295 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002296 //FIXME: workaround for truncated touch sounds
2297 // delayed volume change for system stream to be removed when the problem is
2298 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002300 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2301 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002302 if (volStatus != NO_ERROR) {
2303 status = volStatus;
2304 }
2305 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002306 }
Eric Laurente552edb2014-03-10 17:42:56 -07002307 }
2308 return status;
2309}
2310
Eric Laurente0720872014-03-11 09:30:41 -07002311status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002312 int *index,
2313 audio_devices_t device)
2314{
2315 if (index == NULL) {
2316 return BAD_VALUE;
2317 }
2318 if (!audio_is_output_device(device)) {
2319 return BAD_VALUE;
2320 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002321 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002322 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002323 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002324 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2325 }
François Gaffiedfd74092015-03-19 12:10:59 +01002326 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002327
François Gaffied1ab2bd2015-12-02 18:20:06 +01002328 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002329 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2330 return NO_ERROR;
2331}
2332
Eric Laurent36829f92017-04-07 19:04:42 -07002333audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002334{
2335 // select one output among several suitable for global effects.
2336 // The priority is as follows:
2337 // 1: An offloaded output. If the effect ends up not being offloadable,
2338 // AudioFlinger will invalidate the track and the offloaded output
2339 // will be closed causing the effect to be moved to a PCM output.
2340 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002341 // 3: The primary output
2342 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002343
Eric Laurent3b73df72014-03-11 09:06:29 -07002344 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002345 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002346 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Eric Laurent36829f92017-04-07 19:04:42 -07002348 if (outputs.size() == 0) {
2349 return AUDIO_IO_HANDLE_NONE;
2350 }
Eric Laurente552edb2014-03-10 17:42:56 -07002351
Eric Laurent36829f92017-04-07 19:04:42 -07002352 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2353 bool activeOnly = true;
2354
2355 while (output == AUDIO_IO_HANDLE_NONE) {
2356 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2357 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2358 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2359
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002360 for (audio_io_handle_t output : outputs) {
2361 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002362 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2363 continue;
2364 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002365 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2366 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002367 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002368 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002369 }
2370 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002371 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002372 }
2373 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002374 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002375 }
2376 }
2377 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2378 output = outputOffloaded;
2379 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2380 output = outputDeepBuffer;
2381 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2382 output = outputPrimary;
2383 } else {
2384 output = outputs[0];
2385 }
2386 activeOnly = false;
2387 }
2388
2389 if (output != mMusicEffectOutput) {
2390 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2391 mMusicEffectOutput = output;
2392 }
2393
2394 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002395 return output;
2396}
2397
Eric Laurent36829f92017-04-07 19:04:42 -07002398audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2399{
2400 return selectOutputForMusicEffects();
2401}
2402
Eric Laurente0720872014-03-11 09:30:41 -07002403status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002404 audio_io_handle_t io,
2405 uint32_t strategy,
2406 int session,
2407 int id)
2408{
2409 ssize_t index = mOutputs.indexOfKey(io);
2410 if (index < 0) {
2411 index = mInputs.indexOfKey(io);
2412 if (index < 0) {
2413 ALOGW("registerEffect() unknown io %d", io);
2414 return INVALID_OPERATION;
2415 }
2416 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002417 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002418}
2419
Eric Laurentc75307b2015-03-17 15:29:32 -07002420bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2421{
Eric Laurent28d09f02016-03-08 10:43:05 -08002422 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002423 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2424 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002425 continue;
2426 }
2427 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2428 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002429 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002430}
2431
2432bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2433{
2434 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2435}
2436
Eric Laurente0720872014-03-11 09:30:41 -07002437bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002438{
2439 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002440 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002441 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002442 return true;
2443 }
2444 }
2445 return false;
2446}
2447
Eric Laurent275e8e92014-11-30 15:14:47 -08002448// Register a list of custom mixes with their attributes and format.
2449// When a mix is registered, corresponding input and output profiles are
2450// added to the remote submix hw module. The profile contains only the
2451// parameters (sampling rate, format...) specified by the mix.
2452// The corresponding input remote submix device is also connected.
2453//
2454// When a remote submix device is connected, the address is checked to select the
2455// appropriate profile and the corresponding input or output stream is opened.
2456//
2457// When capture starts, getInputForAttr() will:
2458// - 1 look for a mix matching the address passed in attribtutes tags if any
2459// - 2 if none found, getDeviceForInputSource() will:
2460// - 2.1 look for a mix matching the attributes source
2461// - 2.2 if none found, default to device selection by policy rules
2462// At this time, the corresponding output remote submix device is also connected
2463// and active playback use cases can be transferred to this mix if needed when reconnecting
2464// after AudioTracks are invalidated
2465//
2466// When playback starts, getOutputForAttr() will:
2467// - 1 look for a mix matching the address passed in attribtutes tags if any
2468// - 2 if none found, look for a mix matching the attributes usage
2469// - 3 if none found, default to device and output selection by policy rules.
2470
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002471status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002472{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002473 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2474 status_t res = NO_ERROR;
2475
2476 sp<HwModule> rSubmixModule;
2477 // examine each mix's route type
2478 for (size_t i = 0; i < mixes.size(); i++) {
2479 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2480 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2481 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002482 break;
2483 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002484 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002487 rSubmixModule = mHwModules.getModuleFromName(
2488 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2489 if (rSubmixModule == 0) {
2490 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2491 i);
2492 res = INVALID_OPERATION;
2493 break;
2494 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002495 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002496
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002497 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002498
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002499 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002500 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 res = INVALID_OPERATION;
2502 break;
2503 }
2504 audio_config_t outputConfig = mixes[i].mFormat;
2505 audio_config_t inputConfig = mixes[i].mFormat;
2506 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2507 // stereo and let audio flinger do the channel conversion if needed.
2508 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2509 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2510 rSubmixModule->addOutputProfile(address, &outputConfig,
2511 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2512 rSubmixModule->addInputProfile(address, &inputConfig,
2513 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002514
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2516 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2518 address.string(), "remote-submix");
2519 } else {
2520 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2522 address.string(), "remote-submix");
2523 }
2524 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002525 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002526 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2528 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002530 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002531 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2532 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2533 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2534 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2535 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2536 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002537 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2538 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2540 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002541 } else {
2542 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002543 }
2544 break;
2545 }
2546 }
2547
2548 if (res != NO_ERROR) {
2549 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002550 i, device, address.string());
2551 res = INVALID_OPERATION;
2552 break;
2553 } else if (!foundOutput) {
2554 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2555 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556 res = INVALID_OPERATION;
2557 break;
2558 }
Eric Laurentc722f302014-12-10 11:21:49 -08002559 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002560 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 if (res != NO_ERROR) {
2562 unregisterPolicyMixes(mixes);
2563 }
2564 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002565}
2566
2567status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2568{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002569 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002570 status_t res = NO_ERROR;
2571 sp<HwModule> rSubmixModule;
2572 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002573 for (const auto& mix : mixes) {
2574 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002575
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002577 rSubmixModule = mHwModules.getModuleFromName(
2578 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2579 if (rSubmixModule == 0) {
2580 res = INVALID_OPERATION;
2581 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002582 }
2583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002584
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002585 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002586
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002587 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2588 res = INVALID_OPERATION;
2589 continue;
2590 }
2591
2592 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2593 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2594 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2595 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2596 address.string(), "remote-submix");
2597 }
2598 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2599 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2600 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2601 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2602 address.string(), "remote-submix");
2603 }
2604 rSubmixModule->removeOutputProfile(address);
2605 rSubmixModule->removeInputProfile(address);
2606
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002607 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2608 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 res = INVALID_OPERATION;
2610 continue;
2611 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002612 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002613 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002614 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002615}
2616
Eric Laurente552edb2014-03-10 17:42:56 -07002617
Eric Laurente0720872014-03-11 09:30:41 -07002618status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002619{
Eric Laurente552edb2014-03-10 17:42:56 -07002620 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002621 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2622 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002623 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002624 std::string stateLiteral;
2625 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002626 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2627 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2628 "communications", "media", "record", "dock", "system",
2629 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2630 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2631 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2632 result.appendFormat(" Force use for %s: %d\n",
2633 forceUses[i], mEngine->getForceUse(i));
2634 }
2635 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2636 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2637 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002638 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002639
François Gaffie112b0af2015-11-19 16:13:25 +01002640 mAvailableOutputDevices.dump(fd, String8("Available output"));
2641 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002642 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002643 mOutputs.dump(fd);
2644 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002645 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002646 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002647 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002648 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002649
2650 return NO_ERROR;
2651}
2652
2653// This function checks for the parameters which can be offloaded.
2654// This can be enhanced depending on the capability of the DSP and policy
2655// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002656bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002657{
2658 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002659 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002660 offloadInfo.sample_rate, offloadInfo.channel_mask,
2661 offloadInfo.format,
2662 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2663 offloadInfo.has_video);
2664
Andy Hung2ddee192015-12-18 17:34:44 -08002665 if (mMasterMono) {
2666 return false; // no offloading if mono is set.
2667 }
2668
Eric Laurente552edb2014-03-10 17:42:56 -07002669 // Check if offload has been disabled
2670 char propValue[PROPERTY_VALUE_MAX];
2671 if (property_get("audio.offload.disable", propValue, "0")) {
2672 if (atoi(propValue) != 0) {
2673 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2674 return false;
2675 }
2676 }
2677
2678 // Check if stream type is music, then only allow offload as of now.
2679 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2680 {
2681 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2682 return false;
2683 }
2684
2685 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002686 const bool allowOffloadWithVideo =
2687 property_get_bool("audio.offload.video", false /* default_value */);
2688 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002689 ALOGV("isOffloadSupported: has_video == true, returning false");
2690 return false;
2691 }
2692
2693 //If duration is less than minimum value defined in property, return false
2694 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2695 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2696 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2697 return false;
2698 }
2699 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2700 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2701 return false;
2702 }
2703
2704 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2705 // creating an offloaded track and tearing it down immediately after start when audioflinger
2706 // detects there is an active non offloadable effect.
2707 // FIXME: We should check the audio session here but we do not have it in this context.
2708 // This may prevent offloading in rare situations where effects are left active by apps
2709 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002710 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002711 return false;
2712 }
2713
2714 // See if there is a profile to support this.
2715 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002716 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002717 offloadInfo.sample_rate,
2718 offloadInfo.format,
2719 offloadInfo.channel_mask,
2720 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002721 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2722 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002723}
2724
Eric Laurent6a94d692014-05-20 11:18:06 -07002725status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2726 audio_port_type_t type,
2727 unsigned int *num_ports,
2728 struct audio_port *ports,
2729 unsigned int *generation)
2730{
2731 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2732 generation == NULL) {
2733 return BAD_VALUE;
2734 }
2735 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2736 if (ports == NULL) {
2737 *num_ports = 0;
2738 }
2739
2740 size_t portsWritten = 0;
2741 size_t portsMax = *num_ports;
2742 *num_ports = 0;
2743 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002744 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2745 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002746 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002747 for (const auto& dev : mAvailableOutputDevices) {
2748 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002749 continue;
2750 }
2751 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002752 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002753 }
2754 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002755 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 }
2757 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002758 for (const auto& dev : mAvailableInputDevices) {
2759 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002760 continue;
2761 }
2762 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002763 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002764 }
2765 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002766 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002767 }
2768 }
2769 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2770 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2771 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2772 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2773 }
2774 *num_ports += mInputs.size();
2775 }
2776 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002777 size_t numOutputs = 0;
2778 for (size_t i = 0; i < mOutputs.size(); i++) {
2779 if (!mOutputs[i]->isDuplicated()) {
2780 numOutputs++;
2781 if (portsWritten < portsMax) {
2782 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2783 }
2784 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002785 }
Eric Laurent84c70242014-06-23 08:46:27 -07002786 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002787 }
2788 }
2789 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002790 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002791 return NO_ERROR;
2792}
2793
Eric Laurent99fcae42018-05-17 16:59:18 -07002794status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002795{
Eric Laurent99fcae42018-05-17 16:59:18 -07002796 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2797 return BAD_VALUE;
2798 }
2799 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2800 if (dev != 0) {
2801 dev->toAudioPort(port);
2802 return NO_ERROR;
2803 }
2804 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2805 if (dev != 0) {
2806 dev->toAudioPort(port);
2807 return NO_ERROR;
2808 }
2809 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2810 if (out != 0) {
2811 out->toAudioPort(port);
2812 return NO_ERROR;
2813 }
2814 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2815 if (in != 0) {
2816 in->toAudioPort(port);
2817 return NO_ERROR;
2818 }
2819 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002820}
2821
Eric Laurent6a94d692014-05-20 11:18:06 -07002822status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2823 audio_patch_handle_t *handle,
2824 uid_t uid)
2825{
2826 ALOGV("createAudioPatch()");
2827
2828 if (handle == NULL || patch == NULL) {
2829 return BAD_VALUE;
2830 }
2831 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2832
Eric Laurent874c42872014-08-08 15:13:39 -07002833 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2834 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2835 return BAD_VALUE;
2836 }
2837 // only one source per audio patch supported for now
2838 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002839 return INVALID_OPERATION;
2840 }
Eric Laurent874c42872014-08-08 15:13:39 -07002841
2842 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 return INVALID_OPERATION;
2844 }
Eric Laurent874c42872014-08-08 15:13:39 -07002845 for (size_t i = 0; i < patch->num_sinks; i++) {
2846 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2847 return INVALID_OPERATION;
2848 }
2849 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002850
2851 sp<AudioPatch> patchDesc;
2852 ssize_t index = mAudioPatches.indexOfKey(*handle);
2853
Eric Laurent6a94d692014-05-20 11:18:06 -07002854 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2855 patch->sources[0].role,
2856 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002857#if LOG_NDEBUG == 0
2858 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002859 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002860 patch->sinks[i].role,
2861 patch->sinks[i].type);
2862 }
2863#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002864
2865 if (index >= 0) {
2866 patchDesc = mAudioPatches.valueAt(index);
2867 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2868 mUidCached, patchDesc->mUid, uid);
2869 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2870 return INVALID_OPERATION;
2871 }
2872 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002873 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 }
2875
2876 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002877 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002878 if (outputDesc == NULL) {
2879 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2880 return BAD_VALUE;
2881 }
Eric Laurent84c70242014-06-23 08:46:27 -07002882 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2883 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 if (patchDesc != 0) {
2885 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2886 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2887 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2888 return BAD_VALUE;
2889 }
2890 }
Eric Laurent874c42872014-08-08 15:13:39 -07002891 DeviceVector devices;
2892 for (size_t i = 0; i < patch->num_sinks; i++) {
2893 // Only support mix to devices connection
2894 // TODO add support for mix to mix connection
2895 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2896 ALOGV("createAudioPatch() source mix but sink is not a device");
2897 return INVALID_OPERATION;
2898 }
2899 sp<DeviceDescriptor> devDesc =
2900 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2901 if (devDesc == 0) {
2902 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2903 return BAD_VALUE;
2904 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002905
François Gaffie53615e22015-03-19 09:24:12 +01002906 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002907 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002908 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002909 NULL, // updatedSamplingRate
2910 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002911 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002912 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002913 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002914 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002915 ALOGV("createAudioPatch() profile not supported for device %08x",
2916 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002917 return INVALID_OPERATION;
2918 }
2919 devices.add(devDesc);
2920 }
2921 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002922 return INVALID_OPERATION;
2923 }
Eric Laurent874c42872014-08-08 15:13:39 -07002924
Eric Laurent6a94d692014-05-20 11:18:06 -07002925 // TODO: reconfigure output format and channels here
2926 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002927 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002928 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 index = mAudioPatches.indexOfKey(*handle);
2930 if (index >= 0) {
2931 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2932 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2933 }
2934 patchDesc = mAudioPatches.valueAt(index);
2935 patchDesc->mUid = uid;
2936 ALOGV("createAudioPatch() success");
2937 } else {
2938 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2939 return INVALID_OPERATION;
2940 }
2941 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2942 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2943 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002944 // only one sink supported when connecting an input device to a mix
2945 if (patch->num_sinks > 1) {
2946 return INVALID_OPERATION;
2947 }
François Gaffie53615e22015-03-19 09:24:12 +01002948 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 if (inputDesc == NULL) {
2950 return BAD_VALUE;
2951 }
2952 if (patchDesc != 0) {
2953 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2954 return BAD_VALUE;
2955 }
2956 }
2957 sp<DeviceDescriptor> devDesc =
2958 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2959 if (devDesc == 0) {
2960 return BAD_VALUE;
2961 }
2962
François Gaffie53615e22015-03-19 09:24:12 +01002963 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002964 devDesc->mAddress,
2965 patch->sinks[0].sample_rate,
2966 NULL, /*updatedSampleRate*/
2967 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002968 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002969 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002970 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002971 // FIXME for the parameter type,
2972 // and the NONE
2973 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002974 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002975 return INVALID_OPERATION;
2976 }
2977 // TODO: reconfigure output format and channels here
2978 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002979 devDesc->type(), inputDesc->mIoHandle);
2980 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002981 index = mAudioPatches.indexOfKey(*handle);
2982 if (index >= 0) {
2983 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2984 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2985 }
2986 patchDesc = mAudioPatches.valueAt(index);
2987 patchDesc->mUid = uid;
2988 ALOGV("createAudioPatch() success");
2989 } else {
2990 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2991 return INVALID_OPERATION;
2992 }
2993 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2994 // device to device connection
2995 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002996 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002997 return BAD_VALUE;
2998 }
2999 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003000 sp<DeviceDescriptor> srcDeviceDesc =
3001 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003002 if (srcDeviceDesc == 0) {
3003 return BAD_VALUE;
3004 }
Eric Laurent874c42872014-08-08 15:13:39 -07003005
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 //update source and sink with our own data as the data passed in the patch may
3007 // be incomplete.
3008 struct audio_patch newPatch = *patch;
3009 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003010
Eric Laurent874c42872014-08-08 15:13:39 -07003011 for (size_t i = 0; i < patch->num_sinks; i++) {
3012 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3013 ALOGV("createAudioPatch() source device but one sink is not a device");
3014 return INVALID_OPERATION;
3015 }
3016
3017 sp<DeviceDescriptor> sinkDeviceDesc =
3018 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3019 if (sinkDeviceDesc == 0) {
3020 return BAD_VALUE;
3021 }
3022 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3023
Eric Laurent3bcf8592015-04-03 12:13:24 -07003024 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003025 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003026 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003027 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003028 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003029 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003030 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003031 return INVALID_OPERATION;
3032 }
Eric Laurent874c42872014-08-08 15:13:39 -07003033 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003034 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003035 // if the sink device is reachable via an opened output stream, request to go via
3036 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003037 audio_io_handle_t output = selectOutput(outputs,
3038 AUDIO_OUTPUT_FLAG_NONE,
3039 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003040 if (output != AUDIO_IO_HANDLE_NONE) {
3041 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3042 if (outputDesc->isDuplicated()) {
3043 return INVALID_OPERATION;
3044 }
3045 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003046 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003047 newPatch.num_sources = 2;
3048 }
Eric Laurent83b88082014-06-20 18:31:16 -07003049 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003050 }
3051 // TODO: check from routing capabilities in config file and other conflicting patches
3052
Mikhail Naganovdc769682018-05-04 15:34:08 -07003053 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3054 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003055 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3056 status);
3057 return INVALID_OPERATION;
3058 }
3059 } else {
3060 return BAD_VALUE;
3061 }
3062 } else {
3063 return BAD_VALUE;
3064 }
3065 return NO_ERROR;
3066}
3067
3068status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3069 uid_t uid)
3070{
3071 ALOGV("releaseAudioPatch() patch %d", handle);
3072
3073 ssize_t index = mAudioPatches.indexOfKey(handle);
3074
3075 if (index < 0) {
3076 return BAD_VALUE;
3077 }
3078 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3079 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3080 mUidCached, patchDesc->mUid, uid);
3081 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3082 return INVALID_OPERATION;
3083 }
3084
3085 struct audio_patch *patch = &patchDesc->mPatch;
3086 patchDesc->mUid = mUidCached;
3087 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003088 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003089 if (outputDesc == NULL) {
3090 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3091 return BAD_VALUE;
3092 }
3093
Eric Laurentc75307b2015-03-17 15:29:32 -07003094 setOutputDevice(outputDesc,
3095 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003096 true,
3097 0,
3098 NULL);
3099 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3100 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003101 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003102 if (inputDesc == NULL) {
3103 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3104 return BAD_VALUE;
3105 }
3106 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003107 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003108 true,
3109 NULL);
3110 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3112 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3113 status, patchDesc->mAfPatchHandle);
3114 removeAudioPatch(patchDesc->mHandle);
3115 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003116 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003117 } else {
3118 return BAD_VALUE;
3119 }
3120 } else {
3121 return BAD_VALUE;
3122 }
3123 return NO_ERROR;
3124}
3125
3126status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3127 struct audio_patch *patches,
3128 unsigned int *generation)
3129{
François Gaffie53615e22015-03-19 09:24:12 +01003130 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003131 return BAD_VALUE;
3132 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003133 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003134 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003135}
3136
Eric Laurente1715a42014-05-20 11:30:42 -07003137status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003138{
Eric Laurente1715a42014-05-20 11:30:42 -07003139 ALOGV("setAudioPortConfig()");
3140
3141 if (config == NULL) {
3142 return BAD_VALUE;
3143 }
3144 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3145 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003146 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3147 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003148 }
3149
Eric Laurenta121f902014-06-03 13:32:54 -07003150 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003151 if (config->type == AUDIO_PORT_TYPE_MIX) {
3152 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003154 if (outputDesc == NULL) {
3155 return BAD_VALUE;
3156 }
Eric Laurent84c70242014-06-23 08:46:27 -07003157 ALOG_ASSERT(!outputDesc->isDuplicated(),
3158 "setAudioPortConfig() called on duplicated output %d",
3159 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003160 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003161 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003162 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003163 if (inputDesc == NULL) {
3164 return BAD_VALUE;
3165 }
Eric Laurenta121f902014-06-03 13:32:54 -07003166 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003167 } else {
3168 return BAD_VALUE;
3169 }
3170 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3171 sp<DeviceDescriptor> deviceDesc;
3172 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3173 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3174 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3175 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3176 } else {
3177 return BAD_VALUE;
3178 }
3179 if (deviceDesc == NULL) {
3180 return BAD_VALUE;
3181 }
Eric Laurenta121f902014-06-03 13:32:54 -07003182 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003183 } else {
3184 return BAD_VALUE;
3185 }
3186
Eric Laurenta121f902014-06-03 13:32:54 -07003187 struct audio_port_config backupConfig;
3188 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3189 if (status == NO_ERROR) {
3190 struct audio_port_config newConfig;
3191 audioPortConfig->toAudioPortConfig(&newConfig, config);
3192 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003193 }
Eric Laurenta121f902014-06-03 13:32:54 -07003194 if (status != NO_ERROR) {
3195 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003196 }
Eric Laurente1715a42014-05-20 11:30:42 -07003197
3198 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003199}
3200
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003201void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3202{
Eric Laurentd60560a2015-04-10 11:31:20 -07003203 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003204 clearAudioPatches(uid);
3205 clearSessionRoutes(uid);
3206}
3207
Eric Laurent6a94d692014-05-20 11:18:06 -07003208void AudioPolicyManager::clearAudioPatches(uid_t uid)
3209{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003210 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003211 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3212 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003213 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003214 }
3215 }
3216}
3217
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003218void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3219 audio_io_handle_t ouptutToSkip)
3220{
3221 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3222 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3223 for (size_t j = 0; j < mOutputs.size(); j++) {
3224 if (mOutputs.keyAt(j) == ouptutToSkip) {
3225 continue;
3226 }
3227 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3228 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3229 continue;
3230 }
3231 // If the default device for this strategy is on another output mix,
3232 // invalidate all tracks in this strategy to force re connection.
3233 // Otherwise select new device on the output mix.
3234 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003235 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003236 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3237 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3238 }
3239 }
3240 } else {
3241 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3242 setOutputDevice(outputDesc, newDevice, false);
3243 }
3244 }
3245}
3246
3247void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3248{
3249 // remove output routes associated with this uid
3250 SortedVector<routing_strategy> affectedStrategies;
3251 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3252 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3253 if (route->mUid == uid) {
3254 mOutputRoutes.removeItemsAt(i);
3255 if (route->mDeviceDescriptor != 0) {
3256 affectedStrategies.add(getStrategy(route->mStreamType));
3257 }
3258 }
3259 }
3260 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003261 for (const auto& strategy : affectedStrategies) {
3262 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003263 }
3264
3265 // remove input routes associated with this uid
3266 SortedVector<audio_source_t> affectedSources;
3267 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3268 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3269 if (route->mUid == uid) {
3270 mInputRoutes.removeItemsAt(i);
3271 if (route->mDeviceDescriptor != 0) {
3272 affectedSources.add(route->mSource);
3273 }
3274 }
3275 }
3276 // reroute inputs if necessary
3277 SortedVector<audio_io_handle_t> inputsToClose;
3278 for (size_t i = 0; i < mInputs.size(); i++) {
3279 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003280 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003281 inputsToClose.add(inputDesc->mIoHandle);
3282 }
3283 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003284 for (const auto& input : inputsToClose) {
3285 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003286 }
3287}
3288
Eric Laurentd60560a2015-04-10 11:31:20 -07003289void AudioPolicyManager::clearAudioSources(uid_t uid)
3290{
3291 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3292 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3293 if (sourceDesc->mUid == uid) {
3294 stopAudioSource(mAudioSources.keyAt(i));
3295 }
3296 }
3297}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003298
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003299status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3300 audio_io_handle_t *ioHandle,
3301 audio_devices_t *device)
3302{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003303 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3304 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003305 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003306
François Gaffiedf372692015-03-19 10:43:27 +01003307 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003308}
3309
Eric Laurentd60560a2015-04-10 11:31:20 -07003310status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3311 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003312 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003313 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003314{
Eric Laurentd60560a2015-04-10 11:31:20 -07003315 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3316 if (source == NULL || attributes == NULL || handle == NULL) {
3317 return BAD_VALUE;
3318 }
3319
Glenn Kasten559d4392016-03-29 13:42:57 -07003320 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003321
3322 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3323 source->type != AUDIO_PORT_TYPE_DEVICE) {
3324 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3325 return INVALID_OPERATION;
3326 }
3327
3328 sp<DeviceDescriptor> srcDeviceDesc =
3329 mAvailableInputDevices.getDevice(source->ext.device.type,
3330 String8(source->ext.device.address));
3331 if (srcDeviceDesc == 0) {
3332 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3333 return BAD_VALUE;
3334 }
3335 sp<AudioSourceDescriptor> sourceDesc =
3336 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3337
3338 struct audio_patch dummyPatch;
3339 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3340 sourceDesc->mPatchDesc = patchDesc;
3341
3342 status_t status = connectAudioSource(sourceDesc);
3343 if (status == NO_ERROR) {
3344 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3345 *handle = sourceDesc->getHandle();
3346 }
3347 return status;
3348}
3349
3350status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3351{
3352 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3353
3354 // make sure we only have one patch per source.
3355 disconnectAudioSource(sourceDesc);
3356
3357 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003358 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003359 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3360
3361 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3362 sp<DeviceDescriptor> sinkDeviceDesc =
3363 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3364
3365 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003366
3367 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3368 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003369 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003370 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3371 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3372 // create patch between src device and output device
3373 // create Hwoutput and add to mHwOutputs
3374 } else {
3375 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3376 audio_io_handle_t output =
3377 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3378 if (output == AUDIO_IO_HANDLE_NONE) {
3379 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3380 return INVALID_OPERATION;
3381 }
3382 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3383 if (outputDesc->isDuplicated()) {
3384 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3385 return INVALID_OPERATION;
3386 }
Eric Laurent733ce942017-12-07 12:18:25 -08003387 status_t status = outputDesc->start();
3388 if (status != NO_ERROR) {
3389 return status;
3390 }
3391
Eric Laurentd60560a2015-04-10 11:31:20 -07003392 // create a special patch with no sink and two sources:
3393 // - the second source indicates to PatchPanel through which output mix this patch should
3394 // be connected as well as the stream type for volume control
3395 // - the sink is defined by whatever output device is currently selected for the output
3396 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003397 PatchBuilder patchBuilder;
3398 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3399 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003400 &afPatchHandle,
3401 0);
3402 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3403 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003404 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003405 if (status != NO_ERROR) {
3406 ALOGW("%s patch panel could not connect device patch, error %d",
3407 __FUNCTION__, status);
3408 return INVALID_OPERATION;
3409 }
3410 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003411 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003412
3413 if (status != NO_ERROR) {
3414 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3415 return status;
3416 }
3417 sourceDesc->mSwOutput = outputDesc;
3418 if (delayMs != 0) {
3419 usleep(delayMs * 1000);
3420 }
3421 }
3422
3423 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3424 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3425
3426 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003427}
3428
Glenn Kasten559d4392016-03-29 13:42:57 -07003429status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003430{
Eric Laurentd60560a2015-04-10 11:31:20 -07003431 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3432 ALOGV("%s handle %d", __FUNCTION__, handle);
3433 if (sourceDesc == 0) {
3434 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3435 return BAD_VALUE;
3436 }
3437 status_t status = disconnectAudioSource(sourceDesc);
3438
3439 mAudioSources.removeItem(handle);
3440 return status;
3441}
3442
Andy Hung2ddee192015-12-18 17:34:44 -08003443status_t AudioPolicyManager::setMasterMono(bool mono)
3444{
3445 if (mMasterMono == mono) {
3446 return NO_ERROR;
3447 }
3448 mMasterMono = mono;
3449 // if enabling mono we close all offloaded devices, which will invalidate the
3450 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3451 // for recreating the new AudioTrack as non-offloaded PCM.
3452 //
3453 // If disabling mono, we leave all tracks as is: we don't know which clients
3454 // and tracks are able to be recreated as offloaded. The next "song" should
3455 // play back offloaded.
3456 if (mMasterMono) {
3457 Vector<audio_io_handle_t> offloaded;
3458 for (size_t i = 0; i < mOutputs.size(); ++i) {
3459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3460 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3461 offloaded.push(desc->mIoHandle);
3462 }
3463 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003464 for (const auto& handle : offloaded) {
3465 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003466 }
3467 }
3468 // update master mono for all remaining outputs
3469 for (size_t i = 0; i < mOutputs.size(); ++i) {
3470 updateMono(mOutputs.keyAt(i));
3471 }
3472 return NO_ERROR;
3473}
3474
3475status_t AudioPolicyManager::getMasterMono(bool *mono)
3476{
3477 *mono = mMasterMono;
3478 return NO_ERROR;
3479}
3480
Eric Laurentac9cef52017-06-09 15:46:26 -07003481float AudioPolicyManager::getStreamVolumeDB(
3482 audio_stream_type_t stream, int index, audio_devices_t device)
3483{
3484 return computeVolume(stream, index, device);
3485}
3486
jiabin81772902018-04-02 17:52:27 -07003487status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3488 FormatVector& formats) {
3489 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3490 return BAD_VALUE;
3491 }
3492 String8 reply;
3493 reply = mpClientInterface->getParameters(
3494 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3495 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3496 AudioParameter repliedParameters(reply);
3497 if (repliedParameters.get(
3498 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3499 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3500 return BAD_VALUE;
3501 }
3502 for (auto format : formatsFromString(reply.string())) {
3503 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3504 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3505 if (format == AAC_FORMATS[i]) {
3506 format = AUDIO_FORMAT_AAC_LC;
3507 break;
3508 }
3509 }
3510 bool exist = false;
3511 for (size_t i = 0; i < formats.size(); i++) {
3512 if (format == formats[i]) {
3513 exist = true;
3514 break;
3515 }
3516 }
3517 bool isSurroundFormat = false;
3518 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3519 if (SURROUND_FORMATS[i] == format) {
3520 isSurroundFormat = true;
3521 break;
3522 }
3523 }
3524 if (!exist && isSurroundFormat) {
3525 formats.add(format);
3526 }
3527 }
3528 return NO_ERROR;
3529}
3530
3531status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3532 audio_format_t *surroundFormats,
3533 bool *surroundFormatsEnabled,
3534 bool reported)
3535{
3536 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3537 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3538 return BAD_VALUE;
3539 }
3540 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3541 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3542
3543 // Only return value if there is HDMI output.
3544 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3545 return INVALID_OPERATION;
3546 }
3547
3548 size_t formatsWritten = 0;
3549 size_t formatsMax = *numSurroundFormats;
3550 *numSurroundFormats = 0;
3551 FormatVector formats;
3552 if (reported) {
3553 // Only get surround formats which are reported by device.
3554 // First list already open outputs that can be routed to this device
3555 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3556 SortedVector<audio_io_handle_t> outputs;
3557 bool reportedFormatFound = false;
3558 status_t status;
3559 sp<SwAudioOutputDescriptor> desc;
3560 for (size_t i = 0; i < mOutputs.size(); i++) {
3561 desc = mOutputs.valueAt(i);
3562 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3563 outputs.add(mOutputs.keyAt(i));
3564 }
3565 }
3566 // Open an output to query dynamic parameters.
3567 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3568 AUDIO_DEVICE_OUT_HDMI);
3569 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3570 String8 address = hdmiOutputDevices[i]->mAddress;
3571 for (const auto& hwModule : mHwModules) {
3572 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3573 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3574 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3575 profile->supportDeviceAddress(address)) {
3576 size_t j;
3577 for (j = 0; j < outputs.size(); j++) {
3578 desc = mOutputs.valueFor(outputs.itemAt(j));
3579 if (!desc->isDuplicated() && desc->mProfile == profile) {
3580 break;
3581 }
3582 }
3583 if (j != outputs.size()) {
3584 status = getSupportedFormats(outputs.itemAt(j), formats);
3585 reportedFormatFound |= (status == NO_ERROR);
3586 continue;
3587 }
3588
3589 if (!profile->canOpenNewIo()) {
3590 ALOGW("Max Output number %u already opened for this profile %s",
3591 profile->maxOpenCount, profile->getTagName().c_str());
3592 continue;
3593 }
3594
3595 ALOGV("opening output for device %08x with params %s profile %p name %s",
3596 device, address.string(), profile.get(), profile->getName().string());
3597 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3598 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3599 status_t status = desc->open(nullptr, device, address,
3600 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3601 &output);
3602
3603 if (status == NO_ERROR) {
3604 status = getSupportedFormats(output, formats);
3605 reportedFormatFound |= (status == NO_ERROR);
3606 desc->close();
3607 output = AUDIO_IO_HANDLE_NONE;
3608 }
3609 }
3610 }
3611 }
3612 }
3613
3614 if (!reportedFormatFound) {
3615 return UNKNOWN_ERROR;
3616 }
3617 } else {
3618 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3619 formats.add(SURROUND_FORMATS[i]);
3620 }
3621 }
3622 for (size_t i = 0; i < formats.size(); i++) {
3623 if (formatsWritten < formatsMax) {
3624 surroundFormats[formatsWritten] = formats[i];
3625 bool formatEnabled = false;
3626 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3627 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3628 formatEnabled =
3629 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3630 break;
3631 }
3632 } else {
3633 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3634 }
3635 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3636 }
3637 (*numSurroundFormats)++;
3638 }
3639 return NO_ERROR;
3640}
3641
3642status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3643{
3644 // Check if audio format is a surround formats.
3645 bool isSurroundFormat = false;
3646 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3647 if (audioFormat == SURROUND_FORMATS[i]) {
3648 isSurroundFormat = true;
3649 break;
3650 }
3651 }
3652 if (!isSurroundFormat) {
3653 return BAD_VALUE;
3654 }
3655
3656 // Should only be called when MANUAL.
3657 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3658 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3659 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3660 return INVALID_OPERATION;
3661 }
3662
3663 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3664 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3665 return NO_ERROR;
3666 }
3667
3668 // The operation is valid only when there is HDMI output available.
3669 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3670 return INVALID_OPERATION;
3671 }
3672
3673 if (enabled) {
3674 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3675 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3676 mSurroundFormats.insert(AAC_FORMATS[i]);
3677 }
3678 } else {
3679 mSurroundFormats.insert(audioFormat);
3680 }
3681 } else {
3682 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3683 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3684 mSurroundFormats.erase(AAC_FORMATS[i]);
3685 }
3686 } else {
3687 mSurroundFormats.erase(audioFormat);
3688 }
3689 }
3690
3691 sp<SwAudioOutputDescriptor> outputDesc;
3692 bool profileUpdated = false;
3693 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3694 AUDIO_DEVICE_OUT_HDMI);
3695 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3696 // Simulate reconnection to update enabled surround sound formats.
3697 String8 address = hdmiOutputDevices[i]->mAddress;
3698 String8 name = hdmiOutputDevices[i]->getName();
3699 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 if (status != NO_ERROR) {
3704 continue;
3705 }
3706 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3707 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3708 address.c_str(),
3709 name.c_str());
3710 profileUpdated |= (status == NO_ERROR);
3711 }
3712 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3713 AUDIO_DEVICE_IN_HDMI);
3714 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3715 // Simulate reconnection to update enabled surround sound formats.
3716 String8 address = hdmiInputDevices[i]->mAddress;
3717 String8 name = hdmiInputDevices[i]->getName();
3718 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3719 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3720 address.c_str(),
3721 name.c_str());
3722 if (status != NO_ERROR) {
3723 continue;
3724 }
3725 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3726 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3727 address.c_str(),
3728 name.c_str());
3729 profileUpdated |= (status == NO_ERROR);
3730 }
3731
3732 // Undo the surround formats change due to no audio profiles updated.
3733 if (!profileUpdated) {
3734 if (enabled) {
3735 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3736 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3737 mSurroundFormats.erase(AAC_FORMATS[i]);
3738 }
3739 } else {
3740 mSurroundFormats.erase(audioFormat);
3741 }
3742 } else {
3743 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3744 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3745 mSurroundFormats.insert(AAC_FORMATS[i]);
3746 }
3747 } else {
3748 mSurroundFormats.insert(audioFormat);
3749 }
3750 }
3751 }
3752
3753 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3754}
3755
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003756void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3757{
3758 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3759
3760 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3761 for (size_t i = 0; i < activeInputs.size(); i++) {
3762 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3763 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3764 for (size_t j = 0; j < activeSessions.size(); j++) {
3765 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3766 if (activeSession->uid() == uid) {
3767 activeSession->setSilenced(silenced);
3768 }
3769 }
3770 }
3771}
3772
Eric Laurentd60560a2015-04-10 11:31:20 -07003773status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3774{
3775 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3776
3777 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3778 if (patchDesc == 0) {
3779 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3780 sourceDesc->mPatchDesc->mHandle);
3781 return BAD_VALUE;
3782 }
3783 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3784
Eric Laurent28d09f02016-03-08 10:43:05 -08003785 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003786 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3787 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003788 status_t status = stopSource(swOutputDesc, stream, false);
3789 if (status == NO_ERROR) {
3790 swOutputDesc->stop();
3791 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003792 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3793 } else {
3794 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3795 if (hwOutputDesc != 0) {
3796 // release patch between src device and output device
3797 // close Hwoutput and remove from mHwOutputs
3798 } else {
3799 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3800 }
3801 }
3802 return NO_ERROR;
3803}
3804
3805sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3806 audio_io_handle_t output, routing_strategy strategy)
3807{
3808 sp<AudioSourceDescriptor> source;
3809 for (size_t i = 0; i < mAudioSources.size(); i++) {
3810 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3811 routing_strategy sourceStrategy =
3812 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3813 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3814 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3815 source = sourceDesc;
3816 break;
3817 }
3818 }
3819 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003820}
3821
Eric Laurente552edb2014-03-10 17:42:56 -07003822// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003823// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003824// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003825uint32_t AudioPolicyManager::nextAudioPortGeneration()
3826{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003827 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003828}
3829
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003830#ifdef USE_XML_AUDIO_POLICY_CONF
3831// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3832static const char *kConfigLocationList[] =
3833 {"/odm/etc", "/vendor/etc", "/system/etc"};
3834static const int kConfigLocationListSize =
3835 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3836
3837static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3838 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003839 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003840 status_t ret;
3841
Petri Gyntherf497f292018-04-17 18:46:10 -07003842 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3843 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3844 // A2DP offload supported but disabled: try to use special XML file
3845 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3846 }
3847 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3848
3849 for (const char* fileName : fileNames) {
3850 for (int i = 0; i < kConfigLocationListSize; i++) {
3851 PolicySerializer serializer;
3852 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3853 "%s/%s", kConfigLocationList[i], fileName);
3854 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3855 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003856 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003857 return ret;
3858 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003859 }
3860 }
3861 return ret;
3862}
3863#endif
3864
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3866 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003867 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003868 mUidCached(getuid()),
3869 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003870 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003871 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003872#ifdef USE_XML_AUDIO_POLICY_CONF
3873 mVolumeCurves(new VolumeCurvesCollection()),
3874 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003875 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003876#else
3877 mVolumeCurves(new StreamDescriptorCollection()),
3878 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3879 mDefaultOutputDevice),
3880#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003881 mAudioPortGeneration(1),
3882 mBeaconMuteRefCount(0),
3883 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003884 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003885 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003886 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003887 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3888 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003889{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003891
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3893 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3894{
3895 loadConfig();
3896 initialize();
3897}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003898
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003900#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003901 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003902#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003903 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3904 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003905#endif
3906 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003907 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003908 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003909}
3910
3911status_t AudioPolicyManager::initialize() {
3912 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003913
3914 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003915 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3916 if (!engineInstance) {
3917 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003918 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003919 }
3920 // Retrieve the Policy Manager Interface
3921 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3922 if (mEngine == NULL) {
3923 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003924 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003925 }
3926 mEngine->setObserver(this);
3927 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003928 if (status != NO_ERROR) {
3929 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3930 return status;
3931 }
François Gaffie2110e042015-03-24 08:41:51 +01003932
Eric Laurent3a4311c2014-03-17 12:00:47 -07003933 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003934 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3936 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003937 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003938 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3940 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003941 continue;
3942 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003943 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003944 // open all output streams needed to access attached devices
3945 // except for direct output streams that are only opened when they are actually
3946 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003947 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003948 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003949 if (!outProfile->canOpenNewIo()) {
3950 ALOGE("Invalid Output profile max open count %u for profile %s",
3951 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3952 continue;
3953 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003954 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003955 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003956 continue;
3957 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003959 mTtsOutputAvailable = true;
3960 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003961
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003962 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 continue;
3964 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003965 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003966 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3967 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003968 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003969 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003970 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003971 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003972 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003973 if ((profileType & outputDeviceTypes) == 0) {
3974 continue;
3975 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003976 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3977 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003978 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3979 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3980 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3981 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003982 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003983 status_t status = outputDesc->open(nullptr, profileType, address,
3984 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003985
3986 if (status != NO_ERROR) {
3987 ALOGW("Cannot open output stream for device %08x on hw module %s",
3988 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003989 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003990 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003991 for (const auto& dev : supportedDevices) {
3992 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003993 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003994 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003995 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003996 }
3997 }
3998 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003999 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004001 }
4002 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004003 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004004 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004005 true,
4006 0,
4007 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004008 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004009 }
Eric Laurente552edb2014-03-10 17:42:56 -07004010 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004011 // open input streams needed to access attached devices to validate
4012 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004013 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004014 if (!inProfile->canOpenNewIo()) {
4015 ALOGE("Invalid Input profile max open count %u for profile %s",
4016 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4017 continue;
4018 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004019 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004020 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 continue;
4022 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004023 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004024 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004025 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4026
Eric Laurentd78f1532014-09-16 16:38:20 -07004027 if ((profileType & inputDeviceTypes) == 0) {
4028 continue;
4029 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004030 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004031 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004032
Eric Laurent53b810e2017-12-10 17:25:10 -08004033 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4034 // the inputs vector must be of size >= 1, but we don't want to crash here
4035 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4036 : String8("");
4037 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4038 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4039
Eric Laurentd78f1532014-09-16 16:38:20 -07004040 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004041 status_t status = inputDesc->open(nullptr,
4042 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004043 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004044 AUDIO_SOURCE_MIC,
4045 AUDIO_INPUT_FLAG_NONE,
4046 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004047
4048 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004049 for (const auto& dev : inProfile->getSupportedDevices()) {
4050 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004051 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004052 if (index >= 0) {
4053 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4054 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004055 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004056 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004057 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004058 }
4059 }
Eric Laurentfe231122017-11-17 17:48:06 -08004060 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004061 } else {
4062 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004063 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004064 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004065 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004066 }
4067 }
4068 // make sure all attached devices have been allocated a unique ID
4069 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004070 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004071 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004072 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4073 continue;
4074 }
François Gaffie2110e042015-03-24 08:41:51 +01004075 // The device is now validated and can be appended to the available devices of the engine
4076 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4077 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004078 i++;
4079 }
4080 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004081 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004082 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004083 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4084 continue;
4085 }
François Gaffie2110e042015-03-24 08:41:51 +01004086 // The device is now validated and can be appended to the available devices of the engine
4087 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4088 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 i++;
4090 }
4091 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004092 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004093 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004094 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004095 }
jiabin9ff780e2018-03-19 18:19:52 -07004096 // If microphones address is empty, set it according to device type
4097 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4098 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4099 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4100 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4101 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4102 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4103 }
4104 }
4105 }
Eric Laurente552edb2014-03-10 17:42:56 -07004106
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004107 if (mPrimaryOutput == 0) {
4108 ALOGE("Failed to open primary output");
4109 status = NO_INIT;
4110 }
Eric Laurente552edb2014-03-10 17:42:56 -07004111
4112 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004113 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004114}
4115
Eric Laurente0720872014-03-11 09:30:41 -07004116AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004117{
Eric Laurente552edb2014-03-10 17:42:56 -07004118 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004119 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004122 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004123 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004124 mAvailableOutputDevices.clear();
4125 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004126 mOutputs.clear();
4127 mInputs.clear();
4128 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004129 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004130 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004131}
4132
Eric Laurente0720872014-03-11 09:30:41 -07004133status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004134{
Eric Laurent87ffa392015-05-22 10:32:38 -07004135 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004136}
4137
Eric Laurente552edb2014-03-10 17:42:56 -07004138// ---
4139
Eric Laurent98e38192018-02-15 18:31:53 -08004140void AudioPolicyManager::addOutput(audio_io_handle_t output,
4141 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004142{
Eric Laurent1c333e22014-05-20 10:48:17 -07004143 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004144 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004145 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004146 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004147 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004148}
4149
François Gaffie53615e22015-03-19 09:24:12 +01004150void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4151{
4152 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004153 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004154}
4155
Eric Laurent98e38192018-02-15 18:31:53 -08004156void AudioPolicyManager::addInput(audio_io_handle_t input,
4157 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004158{
Eric Laurent1c333e22014-05-20 10:48:17 -07004159 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004160 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004161}
Eric Laurente552edb2014-03-10 17:42:56 -07004162
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004163void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004164 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004165 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004166 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004167 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004168 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004169 if (devDesc != 0) {
4170 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4171 desc->mIoHandle, address.string());
4172 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004173 }
4174}
4175
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004176status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004177 audio_policy_dev_state_t state,
4178 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004179 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004180{
François Gaffie53615e22015-03-19 09:24:12 +01004181 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004182 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004183
4184 if (audio_device_is_digital(device)) {
4185 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004186 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004187 }
Eric Laurente552edb2014-03-10 17:42:56 -07004188
Eric Laurent3b73df72014-03-11 09:06:29 -07004189 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004190 // first list already open outputs that can be routed to this device
4191 for (size_t i = 0; i < mOutputs.size(); i++) {
4192 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004193 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004194 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004195 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4196 outputs.add(mOutputs.keyAt(i));
4197 } else {
4198 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004199 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004200 }
Eric Laurente552edb2014-03-10 17:42:56 -07004201 }
4202 }
4203 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004204 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004205 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004206 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4207 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004208 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004209 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004210 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004211 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004212 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4213 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004214 }
Eric Laurente552edb2014-03-10 17:42:56 -07004215 }
4216 }
4217 }
4218
Eric Laurent7b279bb2015-12-14 10:18:23 -08004219 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004220
Eric Laurente552edb2014-03-10 17:42:56 -07004221 if (profiles.isEmpty() && outputs.isEmpty()) {
4222 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4223 return BAD_VALUE;
4224 }
4225
4226 // open outputs for matching profiles if needed. Direct outputs are also opened to
4227 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4228 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004229 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004230
4231 // nothing to do if one output is already opened for this profile
4232 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004233 for (j = 0; j < outputs.size(); j++) {
4234 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004235 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004236 // matching profile: save the sample rates, format and channel masks supported
4237 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004238 if (audio_device_is_digital(device)) {
4239 devDesc->importAudioPort(profile);
4240 }
Eric Laurente552edb2014-03-10 17:42:56 -07004241 break;
4242 }
4243 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004244 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004245 continue;
4246 }
4247
Eric Laurent3974e3b2017-12-07 17:58:43 -08004248 if (!profile->canOpenNewIo()) {
4249 ALOGW("Max Output number %u already opened for this profile %s",
4250 profile->maxOpenCount, profile->getTagName().c_str());
4251 continue;
4252 }
4253
Eric Laurent83efe1c2017-07-09 16:51:08 -07004254 ALOGV("opening output for device %08x with params %s profile %p name %s",
4255 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004256 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004257 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004258 status_t status = desc->open(nullptr, device, address,
4259 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004260
Eric Laurentfe231122017-11-17 17:48:06 -08004261 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004262 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004263 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004264 char *param = audio_device_address_to_parameter(device, address);
4265 mpClientInterface->setParameters(output, String8(param));
4266 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004267 }
Phil Burk00eeb322016-03-31 12:41:00 -07004268 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004269 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004270 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004271 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004272 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004273 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004274 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004275 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004276 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4277 profile->pickAudioProfile(
4278 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004279 config.offload_info.sample_rate = config.sample_rate;
4280 config.offload_info.channel_mask = config.channel_mask;
4281 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004282
4283 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4284 AUDIO_OUTPUT_FLAG_NONE, &output);
4285 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004286 output = AUDIO_IO_HANDLE_NONE;
4287 }
Eric Laurentd4692962014-05-05 18:13:44 -07004288 }
4289
Eric Laurentcf2c0212014-07-25 16:20:43 -07004290 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004291 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004292 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004293 sp<AudioPolicyMix> policyMix;
4294 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004295 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4296 address.string());
4297 }
François Gaffie036e1e92015-03-19 10:16:24 +01004298 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004299 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004300
Eric Laurent87ffa392015-05-22 10:32:38 -07004301 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4302 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004303 // no duplicated output for direct outputs and
4304 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004305 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004306
Eric Laurentd4692962014-05-05 18:13:44 -07004307 //TODO: configure audio effect output stage here
4308
4309 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004310 sp<SwAudioOutputDescriptor> dupOutputDesc =
4311 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4312 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4313 &duplicatedOutput);
4314 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004315 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004316 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004317 } else {
4318 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004319 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004320 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004321 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004322 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004323 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004324 }
Eric Laurente552edb2014-03-10 17:42:56 -07004325 }
4326 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004327 } else {
4328 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004329 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004330 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004331 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004332 profiles.removeAt(profile_index);
4333 profile_index--;
4334 } else {
4335 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004336 // Load digital format info only for digital devices
4337 if (audio_device_is_digital(device)) {
4338 devDesc->importAudioPort(profile);
4339 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004340
François Gaffie53615e22015-03-19 09:24:12 +01004341 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004342 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4343 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004344 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004345 NULL/*patch handle*/, address.string());
4346 }
Eric Laurente552edb2014-03-10 17:42:56 -07004347 ALOGV("checkOutputsForDevice(): adding output %d", output);
4348 }
4349 }
4350
4351 if (profiles.isEmpty()) {
4352 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4353 return BAD_VALUE;
4354 }
Eric Laurentd4692962014-05-05 18:13:44 -07004355 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004356 // check if one opened output is not needed any more after disconnecting one device
4357 for (size_t i = 0; i < mOutputs.size(); i++) {
4358 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004359 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004360 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004361 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004362 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004363 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004364 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004365 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4366 mOutputs.keyAt(i));
4367 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004368 }
Eric Laurente552edb2014-03-10 17:42:56 -07004369 }
4370 }
Eric Laurentd4692962014-05-05 18:13:44 -07004371 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004372 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004373 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4374 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004375 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004376 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004377 "clearing direct output profile %zu on module %s",
4378 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004379 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004380 }
4381 }
4382 }
4383 }
4384 return NO_ERROR;
4385}
4386
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004387status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004388 audio_policy_dev_state_t state,
4389 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004390 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004391{
Paul McLean9080a4c2015-06-18 08:24:02 -07004392 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004393 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004394
4395 if (audio_device_is_digital(device)) {
4396 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004397 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004398 }
4399
Eric Laurentd4692962014-05-05 18:13:44 -07004400 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4401 // first list already open inputs that can be routed to this device
4402 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4403 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004404 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004405 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4406 inputs.add(mInputs.keyAt(input_index));
4407 }
4408 }
4409
4410 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004411 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004412 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004413 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004414 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004415 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004416 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004417
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004418 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004419 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004420 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004421 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004422 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4423 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004424 }
Eric Laurentd4692962014-05-05 18:13:44 -07004425 }
4426 }
4427 }
4428
4429 if (profiles.isEmpty() && inputs.isEmpty()) {
4430 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4431 return BAD_VALUE;
4432 }
4433
4434 // open inputs for matching profiles if needed. Direct inputs are also opened to
4435 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4436 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4437
Eric Laurent1c333e22014-05-20 10:48:17 -07004438 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004439
Eric Laurentd4692962014-05-05 18:13:44 -07004440 // nothing to do if one input is already opened for this profile
4441 size_t input_index;
4442 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4443 desc = mInputs.valueAt(input_index);
4444 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004445 if (audio_device_is_digital(device)) {
4446 devDesc->importAudioPort(profile);
4447 }
Eric Laurentd4692962014-05-05 18:13:44 -07004448 break;
4449 }
4450 }
4451 if (input_index != mInputs.size()) {
4452 continue;
4453 }
4454
Eric Laurent3974e3b2017-12-07 17:58:43 -08004455 if (!profile->canOpenNewIo()) {
4456 ALOGW("Max Input number %u already opened for this profile %s",
4457 profile->maxOpenCount, profile->getTagName().c_str());
4458 continue;
4459 }
4460
Eric Laurentfe231122017-11-17 17:48:06 -08004461 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004462 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004463 status_t status = desc->open(nullptr,
4464 device,
4465 address,
4466 AUDIO_SOURCE_MIC,
4467 AUDIO_INPUT_FLAG_NONE,
4468 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004469
Eric Laurentcf2c0212014-07-25 16:20:43 -07004470 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004471 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004472 char *param = audio_device_address_to_parameter(device, address);
4473 mpClientInterface->setParameters(input, String8(param));
4474 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004475 }
Phil Burk00eeb322016-03-31 12:41:00 -07004476 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004477 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004478 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004479 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004480 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004481 }
4482
4483 if (input != 0) {
4484 addInput(input, desc);
4485 }
4486 } // endif input != 0
4487
Eric Laurentcf2c0212014-07-25 16:20:43 -07004488 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004489 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004490 profiles.removeAt(profile_index);
4491 profile_index--;
4492 } else {
4493 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004494 if (audio_device_is_digital(device)) {
4495 devDesc->importAudioPort(profile);
4496 }
Eric Laurentd4692962014-05-05 18:13:44 -07004497 ALOGV("checkInputsForDevice(): adding input %d", input);
4498 }
4499 } // end scan profiles
4500
4501 if (profiles.isEmpty()) {
4502 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4503 return BAD_VALUE;
4504 }
4505 } else {
4506 // Disconnect
4507 // check if one opened input is not needed any more after disconnecting one device
4508 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4509 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004510 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004511 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4512 mInputs.keyAt(input_index));
4513 inputs.add(mInputs.keyAt(input_index));
4514 }
4515 }
4516 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004517 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004518 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004519 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004520 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004521 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004522 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004523 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4524 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004525 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004526 }
4527 }
4528 }
4529 } // end disconnect
4530
4531 return NO_ERROR;
4532}
4533
4534
Eric Laurente0720872014-03-11 09:30:41 -07004535void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004536{
4537 ALOGV("closeOutput(%d)", output);
4538
Eric Laurentc75307b2015-03-17 15:29:32 -07004539 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (outputDesc == NULL) {
4541 ALOGW("closeOutput() unknown output %d", output);
4542 return;
4543 }
François Gaffie036e1e92015-03-19 10:16:24 +01004544 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004545
Eric Laurente552edb2014-03-10 17:42:56 -07004546 // look for duplicated outputs connected to the output being removed.
4547 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004548 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004549 if (dupOutputDesc->isDuplicated() &&
4550 (dupOutputDesc->mOutput1 == outputDesc ||
4551 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004552 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004553 if (dupOutputDesc->mOutput1 == outputDesc) {
4554 outputDesc2 = dupOutputDesc->mOutput2;
4555 } else {
4556 outputDesc2 = dupOutputDesc->mOutput1;
4557 }
4558 // As all active tracks on duplicated output will be deleted,
4559 // and as they were also referenced on the other output, the reference
4560 // count for their stream type must be adjusted accordingly on
4561 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004562 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004563 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004564 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004565 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004566 }
Eric Laurent733ce942017-12-07 12:18:25 -08004567 // stop() will be a no op if the output is still active but is needed in case all
4568 // active streams refcounts where cleared above
4569 if (wasActive) {
4570 outputDesc2->stop();
4571 }
Eric Laurente552edb2014-03-10 17:42:56 -07004572 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4573 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4574
4575 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004576 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004577 }
4578 }
4579
Eric Laurent05b90f82014-08-27 15:32:29 -07004580 nextAudioPortGeneration();
4581
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004582 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004583 if (index >= 0) {
4584 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004585 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004586 mAudioPatches.removeItemsAt(index);
4587 mpClientInterface->onAudioPatchListUpdate();
4588 }
4589
Eric Laurentfe231122017-11-17 17:48:06 -08004590 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004591
François Gaffie53615e22015-03-19 09:24:12 +01004592 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004593 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004594}
4595
4596void AudioPolicyManager::closeInput(audio_io_handle_t input)
4597{
4598 ALOGV("closeInput(%d)", input);
4599
4600 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4601 if (inputDesc == NULL) {
4602 ALOGW("closeInput() unknown input %d", input);
4603 return;
4604 }
4605
Eric Laurent6a94d692014-05-20 11:18:06 -07004606 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004607
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004608 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004609 if (index >= 0) {
4610 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004611 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004612 mAudioPatches.removeItemsAt(index);
4613 mpClientInterface->onAudioPatchListUpdate();
4614 }
4615
Eric Laurentfe231122017-11-17 17:48:06 -08004616 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004617 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004618}
4619
Eric Laurentc75307b2015-03-17 15:29:32 -07004620SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4621 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004622 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004623{
4624 SortedVector<audio_io_handle_t> outputs;
4625
4626 ALOGVV("getOutputsForDevice() device %04x", device);
4627 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004628 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004629 i, openOutputs.valueAt(i)->isDuplicated(),
4630 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004631 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4632 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4633 outputs.add(openOutputs.keyAt(i));
4634 }
4635 }
4636 return outputs;
4637}
4638
Eric Laurente0720872014-03-11 09:30:41 -07004639bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004640 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004641{
4642 if (outputs1.size() != outputs2.size()) {
4643 return false;
4644 }
4645 for (size_t i = 0; i < outputs1.size(); i++) {
4646 if (outputs1[i] != outputs2[i]) {
4647 return false;
4648 }
4649 }
4650 return true;
4651}
4652
Eric Laurente0720872014-03-11 09:30:41 -07004653void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004654{
4655 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4656 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4657 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4658 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4659
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004660 // also take into account external policy-related changes: add all outputs which are
4661 // associated with policies in the "before" and "after" output vectors
4662 ALOGVV("checkOutputForStrategy(): policy related outputs");
4663 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004664 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004665 if (desc != 0 && desc->mPolicyMix != NULL) {
4666 srcOutputs.add(desc->mIoHandle);
4667 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4668 }
4669 }
4670 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004671 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004672 if (desc != 0 && desc->mPolicyMix != NULL) {
4673 dstOutputs.add(desc->mIoHandle);
4674 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4675 }
4676 }
4677
Eric Laurente552edb2014-03-10 17:42:56 -07004678 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004679 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4680 // audio from invalidated tracks will be rendered when unmuting
4681 uint32_t maxLatency = 0;
4682 for (audio_io_handle_t srcOut : srcOutputs) {
4683 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4684 if (desc != 0 && maxLatency < desc->latency()) {
4685 maxLatency = desc->latency();
4686 }
4687 }
Eric Laurente552edb2014-03-10 17:42:56 -07004688 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4689 strategy, srcOutputs[0], dstOutputs[0]);
4690 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004691 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004692 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4693 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004694 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004695 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004696 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004697 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004698 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004699 if (source != 0){
4700 connectAudioSource(source);
4701 }
Eric Laurente552edb2014-03-10 17:42:56 -07004702 }
4703
4704 // Move effects associated to this strategy from previous output to new output
4705 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004706 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004707 }
4708 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004709 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004710 if (getStrategy((audio_stream_type_t)i) == strategy) {
4711 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 }
4714 }
4715}
4716
Eric Laurente0720872014-03-11 09:30:41 -07004717void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
François Gaffie2110e042015-03-24 08:41:51 +01004719 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004720 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004721 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004722 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004723 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004724 checkOutputForStrategy(STRATEGY_SONIFICATION);
4725 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004726 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004727 checkOutputForStrategy(STRATEGY_MEDIA);
4728 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004729 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004730}
4731
Eric Laurente0720872014-03-11 09:30:41 -07004732void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004733{
François Gaffie53615e22015-03-19 09:24:12 +01004734 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004735 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004736 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004737 return;
4738 }
4739
Eric Laurent3a4311c2014-03-17 12:00:47 -07004740 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004741 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4742 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4743 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004744
4745 // if suspended, restore A2DP output if:
4746 // ((SCO device is NOT connected) ||
4747 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4748 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004749 //
Eric Laurentf732e072016-08-03 19:30:28 -07004750 // if not suspended, suspend A2DP output if:
4751 // (SCO device is connected) &&
4752 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4753 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004754 //
4755 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004756 if (!isScoConnected ||
4757 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4758 AUDIO_POLICY_FORCE_BT_SCO) &&
4759 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4760 AUDIO_POLICY_FORCE_BT_SCO) &&
4761 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004762 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004763
4764 mpClientInterface->restoreOutput(a2dpOutput);
4765 mA2dpSuspended = false;
4766 }
4767 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004768 if (isScoConnected &&
4769 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4770 AUDIO_POLICY_FORCE_BT_SCO) ||
4771 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4772 AUDIO_POLICY_FORCE_BT_SCO) ||
4773 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004774 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004775
4776 mpClientInterface->suspendOutput(a2dpOutput);
4777 mA2dpSuspended = true;
4778 }
4779 }
4780}
4781
Eric Laurentc75307b2015-03-17 15:29:32 -07004782audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4783 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004784{
4785 audio_devices_t device = AUDIO_DEVICE_NONE;
4786
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004787 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 if (index >= 0) {
4789 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4790 if (patchDesc->mUid != mUidCached) {
4791 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004792 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 return outputDesc->device();
4794 }
4795 }
4796
Eric Laurente552edb2014-03-10 17:42:56 -07004797 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004798 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004799 // use device for strategy enforced audible
4800 // 2: we are in call or the strategy phone is active on the output:
4801 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004802 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004803 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004804 // 4: the strategy for enforced audible is active but not enforced on the output:
4805 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004806 // 5: the strategy accessibility is active on the output:
4807 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004808 // 6: the strategy "respectful" sonification is active on the output:
4809 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004810 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004811 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004812 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004813 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004814 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004815 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004816 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004817 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004818 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4819 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004820 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004821 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004822 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004823 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004824 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4825 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004826 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4827 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004828 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004829 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004830 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004831 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004832 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004833 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004834 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004835 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004836 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004837 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004838 }
4839
Eric Laurent1c333e22014-05-20 10:48:17 -07004840 ALOGV("getNewOutputDevice() selected device %x", device);
4841 return device;
4842}
4843
Eric Laurentfb66dd92016-01-28 18:32:03 -08004844audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004845{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004846 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004847
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004848 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 if (index >= 0) {
4850 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4851 if (patchDesc->mUid != mUidCached) {
4852 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004853 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 return inputDesc->mDevice;
4855 }
4856 }
4857
Eric Laurentdc95a252018-04-12 12:46:56 -07004858 // If we are not in call and no client is active on this input, this methods returns
4859 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004860 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004861 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4862 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4863 }
4864 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004865 device = getDeviceAndMixForInputSource(source);
4866 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004867
Eric Laurente552edb2014-03-10 17:42:56 -07004868 return device;
4869}
4870
Eric Laurent794fde22016-03-11 09:50:45 -08004871bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4872 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004873 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004874}
4875
Eric Laurente0720872014-03-11 09:30:41 -07004876uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004877 return (uint32_t)getStrategy(stream);
4878}
4879
Eric Laurente0720872014-03-11 09:30:41 -07004880audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004881 // By checking the range of stream before calling getStrategy, we avoid
4882 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4883 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004884 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004885 return AUDIO_DEVICE_NONE;
4886 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004887 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004888 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4889 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004890 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 }
Eric Laurent794fde22016-03-11 09:50:45 -08004892 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004893 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004894 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004895 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4896 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004897 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004898 curDevices |= outputDesc->device();
4899 }
4900 }
4901 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004902 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004903
4904 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4905 and doesn't really need to.*/
4906 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4907 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4908 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4909 }
Eric Laurente552edb2014-03-10 17:42:56 -07004910 return devices;
4911}
4912
François Gaffie2110e042015-03-24 08:41:51 +01004913routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4914{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004915 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004916 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004917}
4918
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004919uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4920 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004921 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4922 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4923 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004924 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4925 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4926 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004927 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004928 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004929}
4930
Eric Laurente0720872014-03-11 09:30:41 -07004931void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004932 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004933 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004934 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4935 updateDevicesAndOutputs();
4936 break;
4937 default:
4938 break;
4939 }
4940}
4941
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004942uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004943
4944 // skip beacon mute management if a dedicated TTS output is available
4945 if (mTtsOutputAvailable) {
4946 return 0;
4947 }
4948
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004949 switch(event) {
4950 case STARTING_OUTPUT:
4951 mBeaconMuteRefCount++;
4952 break;
4953 case STOPPING_OUTPUT:
4954 if (mBeaconMuteRefCount > 0) {
4955 mBeaconMuteRefCount--;
4956 }
4957 break;
4958 case STARTING_BEACON:
4959 mBeaconPlayingRefCount++;
4960 break;
4961 case STOPPING_BEACON:
4962 if (mBeaconPlayingRefCount > 0) {
4963 mBeaconPlayingRefCount--;
4964 }
4965 break;
4966 }
4967
4968 if (mBeaconMuteRefCount > 0) {
4969 // any playback causes beacon to be muted
4970 return setBeaconMute(true);
4971 } else {
4972 // no other playback: unmute when beacon starts playing, mute when it stops
4973 return setBeaconMute(mBeaconPlayingRefCount == 0);
4974 }
4975}
4976
4977uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4978 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4979 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4980 // keep track of muted state to avoid repeating mute/unmute operations
4981 if (mBeaconMuted != mute) {
4982 // mute/unmute AUDIO_STREAM_TTS on all outputs
4983 ALOGV("\t muting %d", mute);
4984 uint32_t maxLatency = 0;
4985 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004986 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004987 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004989 0 /*delay*/, AUDIO_DEVICE_NONE);
4990 const uint32_t latency = desc->latency() * 2;
4991 if (latency > maxLatency) {
4992 maxLatency = latency;
4993 }
4994 }
4995 mBeaconMuted = mute;
4996 return maxLatency;
4997 }
4998 return 0;
4999}
5000
Eric Laurente0720872014-03-11 09:30:41 -07005001audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005002 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005003{
Paul McLeanaa981192015-03-21 09:55:15 -07005004 // Routing
5005 // see if we have an explicit route
5006 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
5007 // (getStrategy(stream)).
5008 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07005009 // and activity count is non-zero and the device in the route descriptor is available
5010 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07005011 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
5012 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08005013 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005014 if ((routeStrategy == strategy) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005015 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07005016 return route->mDeviceDescriptor->type();
5017 }
5018 }
5019
Eric Laurente552edb2014-03-10 17:42:56 -07005020 if (fromCache) {
5021 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5022 strategy, mDeviceForStrategy[strategy]);
5023 return mDeviceForStrategy[strategy];
5024 }
François Gaffie2110e042015-03-24 08:41:51 +01005025 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005026}
5027
Eric Laurente0720872014-03-11 09:30:41 -07005028void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005029{
5030 for (int i = 0; i < NUM_STRATEGIES; i++) {
5031 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5032 }
5033 mPreviousOutputs = mOutputs;
5034}
5035
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005036uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005037 audio_devices_t prevDevice,
5038 uint32_t delayMs)
5039{
5040 // mute/unmute strategies using an incompatible device combination
5041 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5042 // if unmuting, unmute only after the specified delay
5043 if (outputDesc->isDuplicated()) {
5044 return 0;
5045 }
5046
5047 uint32_t muteWaitMs = 0;
5048 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005049 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005050
5051 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5052 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005054 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5055 bool doMute = false;
5056
5057 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5058 doMute = true;
5059 outputDesc->mStrategyMutedByDevice[i] = true;
5060 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5061 doMute = true;
5062 outputDesc->mStrategyMutedByDevice[i] = false;
5063 }
Eric Laurent99401132014-05-07 19:48:15 -07005064 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005065 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005066 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005067 // skip output if it does not share any device with current output
5068 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5069 == AUDIO_DEVICE_NONE) {
5070 continue;
5071 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005072 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005073 mute ? "muting" : "unmuting", i, curDevice);
5074 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005075 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005076 if (mute) {
5077 // FIXME: should not need to double latency if volume could be applied
5078 // immediately by the audioflinger mixer. We must account for the delay
5079 // between now and the next time the audioflinger thread for this output
5080 // will process a buffer (which corresponds to one buffer size,
5081 // usually 1/2 or 1/4 of the latency).
5082 if (muteWaitMs < desc->latency() * 2) {
5083 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005084 }
5085 }
5086 }
5087 }
5088 }
5089 }
5090
Eric Laurent99401132014-05-07 19:48:15 -07005091 // temporary mute output if device selection changes to avoid volume bursts due to
5092 // different per device volumes
5093 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005094 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5095 // temporary mute duration is conservatively set to 4 times the reported latency
5096 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5097 if (muteWaitMs < tempMuteWaitMs) {
5098 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005099 }
Eric Laurentdc462862016-07-19 12:29:53 -07005100
Eric Laurent99401132014-05-07 19:48:15 -07005101 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005102 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005103 // make sure that we do not start the temporary mute period too early in case of
5104 // delayed device change
5105 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005106 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005107 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005108 }
5109 }
5110 }
5111
Eric Laurente552edb2014-03-10 17:42:56 -07005112 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5113 if (muteWaitMs > delayMs) {
5114 muteWaitMs -= delayMs;
5115 usleep(muteWaitMs * 1000);
5116 return muteWaitMs;
5117 }
5118 return 0;
5119}
5120
Eric Laurentc75307b2015-03-17 15:29:32 -07005121uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005122 audio_devices_t device,
5123 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005125 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005126 const char *address,
5127 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005128{
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 AudioParameter param;
5131 uint32_t muteWaitMs;
5132
5133 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005134 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5135 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5136 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5137 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005138 return muteWaitMs;
5139 }
5140 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5141 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005142 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005143 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005144 return 0;
5145 }
5146
5147 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005148 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005149
5150 audio_devices_t prevDevice = outputDesc->mDevice;
5151
Paul McLeanaa981192015-03-21 09:55:15 -07005152 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005153
5154 if (device != AUDIO_DEVICE_NONE) {
5155 outputDesc->mDevice = device;
5156 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005157
5158 // if the outputs are not materially active, there is no need to mute.
5159 if (requiresMuteCheck) {
5160 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5161 } else {
5162 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5163 muteWaitMs = 0;
5164 }
Eric Laurente552edb2014-03-10 17:42:56 -07005165
5166 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005167 // the requested device is AUDIO_DEVICE_NONE
5168 // OR the requested device is the same as current device
5169 // AND force is not specified
5170 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005171 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005172 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5173 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005174 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005175 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005176 return muteWaitMs;
5177 }
5178
5179 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005180
Eric Laurente552edb2014-03-10 17:42:56 -07005181 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005182 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005183 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005184 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005185 DeviceVector deviceList;
5186 if ((address == NULL) || (strlen(address) == 0)) {
5187 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5188 } else {
5189 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5190 }
5191
Eric Laurent1c333e22014-05-20 10:48:17 -07005192 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005193 PatchBuilder patchBuilder;
5194 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005195 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005196 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005197 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005198 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005199 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005200
5201 // inform all input as well
5202 for (size_t i = 0; i < mInputs.size(); i++) {
5203 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005204 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005205 AudioParameter inputCmd = AudioParameter();
5206 ALOGV("%s: inform input %d of device:%d", __func__,
5207 inputDescriptor->mIoHandle, device);
5208 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5209 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5210 inputCmd.toString(),
5211 delayMs);
5212 }
5213 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005214 }
Eric Laurente552edb2014-03-10 17:42:56 -07005215
5216 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005218
5219 return muteWaitMs;
5220}
5221
Eric Laurentc75307b2015-03-17 15:29:32 -07005222status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 int delayMs,
5224 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005225{
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 ssize_t index;
5227 if (patchHandle) {
5228 index = mAudioPatches.indexOfKey(*patchHandle);
5229 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005230 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 }
5232 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 return INVALID_OPERATION;
5234 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5236 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005237 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005238 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 removeAudioPatch(patchDesc->mHandle);
5240 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005241 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 return status;
5243}
5244
5245status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5246 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 bool force,
5248 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005249{
5250 status_t status = NO_ERROR;
5251
Eric Laurent1f2f2232014-06-02 12:01:23 -07005252 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005253 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5254 inputDesc->mDevice = device;
5255
5256 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5257 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005258 PatchBuilder patchBuilder;
5259 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005260 // AUDIO_SOURCE_HOTWORD is for internal use only:
5261 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005262 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5263 auto result = usecase;
5264 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5265 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5266 }
5267 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005268 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005269 addSource(deviceList.itemAt(0));
5270 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005271 }
5272 }
5273 return status;
5274}
5275
Eric Laurent6a94d692014-05-20 11:18:06 -07005276status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5277 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005278{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005279 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 ssize_t index;
5281 if (patchHandle) {
5282 index = mAudioPatches.indexOfKey(*patchHandle);
5283 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005284 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 }
5286 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005287 return INVALID_OPERATION;
5288 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5290 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005291 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005292 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 removeAudioPatch(patchDesc->mHandle);
5294 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005295 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 return status;
5297}
5298
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005299sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005300 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005301 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005302 audio_format_t& format,
5303 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005304 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005305{
5306 // Choose an input profile based on the requested capture parameters: select the first available
5307 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005308 //
5309 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5310 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005311
Glenn Kasten730b9262018-03-29 15:01:26 -07005312 sp<IOProfile> firstInexact;
5313 uint32_t updatedSamplingRate = 0;
5314 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5315 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005316 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005317 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005318 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005319 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005320 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005321 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005322 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005323 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005324 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005325 &channelMask /*updatedChannelMask*/,
5326 // FIXME ugly cast
5327 (audio_output_flags_t) flags,
5328 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005329 return profile;
5330 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005331 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5332 samplingRate,
5333 &updatedSamplingRate,
5334 format,
5335 &updatedFormat,
5336 channelMask,
5337 &updatedChannelMask,
5338 // FIXME ugly cast
5339 (audio_output_flags_t) flags,
5340 false /*exactMatchRequiredForInputFlags*/)) {
5341 firstInexact = profile;
5342 }
5343
Eric Laurente552edb2014-03-10 17:42:56 -07005344 }
5345 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005346 if (firstInexact != nullptr) {
5347 samplingRate = updatedSamplingRate;
5348 format = updatedFormat;
5349 channelMask = updatedChannelMask;
5350 return firstInexact;
5351 }
Eric Laurente552edb2014-03-10 17:42:56 -07005352 return NULL;
5353}
5354
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005355
5356audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005357 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005358{
François Gaffie036e1e92015-03-19 10:16:24 +01005359 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5360 audio_devices_t selectedDeviceFromMix =
5361 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005362
François Gaffie036e1e92015-03-19 10:16:24 +01005363 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5364 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005365 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005366 return getDeviceForInputSource(inputSource);
5367}
5368
5369audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5370{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005371 // Routing
5372 // Scan the whole RouteMap to see if we have an explicit route:
5373 // if the input source in the RouteMap is the same as the argument above,
5374 // and activity count is non-zero and the device in the route descriptor is available
5375 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005376 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5377 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005378 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005379 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005380 return route->mDeviceDescriptor->type();
5381 }
5382 }
5383
5384 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005385}
5386
Eric Laurente0720872014-03-11 09:30:41 -07005387float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005388 int index,
5389 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005390{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005391 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005392
5393 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5394 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5395 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5396 // the ringtone volume
5397 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5398 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5399 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5400 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5401 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5402 }
5403
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005404 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005405 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5406 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005407 switch (stream) {
5408 case AUDIO_STREAM_SYSTEM:
5409 case AUDIO_STREAM_RING:
5410 case AUDIO_STREAM_MUSIC:
5411 case AUDIO_STREAM_ALARM:
5412 case AUDIO_STREAM_NOTIFICATION:
5413 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5414 case AUDIO_STREAM_DTMF:
5415 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005416 int voiceVolumeIndex =
5417 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5418 const float maxVoiceVolDb =
5419 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5420 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005421 if (volumeDB > maxVoiceVolDb) {
5422 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5423 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5424 volumeDB = maxVoiceVolDb;
5425 }
5426 } break;
5427 default:
5428 break;
5429 }
5430 }
5431
Eric Laurente552edb2014-03-10 17:42:56 -07005432 // if a headset is connected, apply the following rules to ring tones and notifications
5433 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005434 // - always attenuate notifications volume by 6dB
5435 // - attenuate ring tones volume by 6dB unless music is not playing and
5436 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005437 // - if music is playing, always limit the volume to current music volume,
5438 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005439 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005440 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5441 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5442 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005443 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005444 AUDIO_DEVICE_OUT_USB_HEADSET |
5445 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005446 ((stream_strategy == STRATEGY_SONIFICATION)
5447 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005448 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005449 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005450 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005451 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005452 // when the phone is ringing we must consider that music could have been paused just before
5453 // by the music application and behave as if music was active if the last music track was
5454 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005455 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005456 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005457 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005458 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005459 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005460 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5461 musicDevice),
5462 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005463 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5464 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005465 if (volumeDB > minVolDB) {
5466 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005467 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005468 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005469 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5470 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5471 // on A2DP, also ensure notification volume is not too low compared to media when
5472 // intended to be played
5473 if ((volumeDB > -96.0f) &&
5474 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5475 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5476 stream, device,
5477 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5478 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5479 }
5480 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005481 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5482 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005483 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005484 }
5485 }
5486
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005488}
5489
Eric Laurente0720872014-03-11 09:30:41 -07005490status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005491 int index,
5492 const sp<AudioOutputDescriptor>& outputDesc,
5493 audio_devices_t device,
5494 int delayMs,
5495 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005496{
Eric Laurente552edb2014-03-10 17:42:56 -07005497 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005498 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005499 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005500 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005501 return NO_ERROR;
5502 }
François Gaffie2110e042015-03-24 08:41:51 +01005503 audio_policy_forced_cfg_t forceUseForComm =
5504 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005505 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005506 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5507 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005508 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005509 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005510 return INVALID_OPERATION;
5511 }
5512
Eric Laurentc75307b2015-03-17 15:29:32 -07005513 if (device == AUDIO_DEVICE_NONE) {
5514 device = outputDesc->device();
5515 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005516
Eric Laurentffbc80f2015-03-18 18:30:19 -07005517 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005518 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005519 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005520 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005521
Eric Laurentffbc80f2015-03-18 18:30:19 -07005522 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005523
Eric Laurent3b73df72014-03-11 09:06:29 -07005524 if (stream == AUDIO_STREAM_VOICE_CALL ||
5525 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005526 float voiceVolume;
5527 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005528 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005529 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005530 } else {
5531 voiceVolume = 1.0;
5532 }
5533
Eric Laurent18fba842016-03-31 14:41:26 -07005534 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005535 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5536 mLastVoiceVolume = voiceVolume;
5537 }
5538 }
5539
5540 return NO_ERROR;
5541}
5542
Eric Laurentc75307b2015-03-17 15:29:32 -07005543void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5544 audio_devices_t device,
5545 int delayMs,
5546 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005547{
Eric Laurentc75307b2015-03-17 15:29:32 -07005548 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005549
Eric Laurent794fde22016-03-11 09:50:45 -08005550 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005551 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005552 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005554 device,
5555 delayMs,
5556 force);
5557 }
5558}
5559
Eric Laurente0720872014-03-11 09:30:41 -07005560void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005561 bool on,
5562 const sp<AudioOutputDescriptor>& outputDesc,
5563 int delayMs,
5564 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005565{
Eric Laurent72249d52015-06-08 11:12:15 -07005566 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5567 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005568 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005569 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005570 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005571 }
5572 }
5573}
5574
Eric Laurente0720872014-03-11 09:30:41 -07005575void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005576 bool on,
5577 const sp<AudioOutputDescriptor>& outputDesc,
5578 int delayMs,
5579 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005580{
Eric Laurente552edb2014-03-10 17:42:56 -07005581 if (device == AUDIO_DEVICE_NONE) {
5582 device = outputDesc->device();
5583 }
5584
Eric Laurentc75307b2015-03-17 15:29:32 -07005585 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5586 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005587
5588 if (on) {
5589 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005590 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005592 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005594 }
5595 }
5596 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5597 outputDesc->mMuteCount[stream]++;
5598 } else {
5599 if (outputDesc->mMuteCount[stream] == 0) {
5600 ALOGV("setStreamMute() unmuting non muted stream!");
5601 return;
5602 }
5603 if (--outputDesc->mMuteCount[stream] == 0) {
5604 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005605 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005606 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005607 device,
5608 delayMs);
5609 }
5610 }
5611}
5612
Eric Laurente0720872014-03-11 09:30:41 -07005613void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005614 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005615{
Eric Laurent87ffa392015-05-22 10:32:38 -07005616 if(!hasPrimaryOutput()) {
5617 return;
5618 }
5619
Eric Laurente552edb2014-03-10 17:42:56 -07005620 // if the stream pertains to sonification strategy and we are in call we must
5621 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5622 // in the device used for phone strategy and play the tone if the selected device does not
5623 // interfere with the device used for phone strategy
5624 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5625 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005626 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005627 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5628 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005629 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005630 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5631 stream, starting, outputDesc->mDevice, stateChange);
5632 if (outputDesc->mRefCount[stream]) {
5633 int muteCount = 1;
5634 if (stateChange) {
5635 muteCount = outputDesc->mRefCount[stream];
5636 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005637 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005638 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5639 for (int i = 0; i < muteCount; i++) {
5640 setStreamMute(stream, starting, mPrimaryOutput);
5641 }
5642 } else {
5643 ALOGV("handleIncallSonification() high visibility");
5644 if (outputDesc->device() &
5645 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5646 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5647 for (int i = 0; i < muteCount; i++) {
5648 setStreamMute(stream, starting, mPrimaryOutput);
5649 }
5650 }
5651 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005652 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5653 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005654 } else {
5655 mpClientInterface->stopTone();
5656 }
5657 }
5658 }
5659 }
5660}
5661
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005662audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5663{
5664 // flags to stream type mapping
5665 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5666 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5667 }
5668 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5669 return AUDIO_STREAM_BLUETOOTH_SCO;
5670 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005671 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5672 return AUDIO_STREAM_TTS;
5673 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005674
5675 // usage to stream type mapping
5676 switch (attr->usage) {
5677 case AUDIO_USAGE_MEDIA:
5678 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005679 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005680 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5681 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005682 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5683 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005684 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5685 return AUDIO_STREAM_SYSTEM;
5686 case AUDIO_USAGE_VOICE_COMMUNICATION:
5687 return AUDIO_STREAM_VOICE_CALL;
5688
5689 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5690 return AUDIO_STREAM_DTMF;
5691
5692 case AUDIO_USAGE_ALARM:
5693 return AUDIO_STREAM_ALARM;
5694 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5695 return AUDIO_STREAM_RING;
5696
5697 case AUDIO_USAGE_NOTIFICATION:
5698 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5699 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5700 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5701 case AUDIO_USAGE_NOTIFICATION_EVENT:
5702 return AUDIO_STREAM_NOTIFICATION;
5703
5704 case AUDIO_USAGE_UNKNOWN:
5705 default:
5706 return AUDIO_STREAM_MUSIC;
5707 }
5708}
Eric Laurente83b55d2014-11-14 10:06:21 -08005709
François Gaffie53615e22015-03-19 09:24:12 +01005710bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5711{
Eric Laurente83b55d2014-11-14 10:06:21 -08005712 // has flags that map to a strategy?
5713 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5714 return true;
5715 }
5716
5717 // has known usage?
5718 switch (paa->usage) {
5719 case AUDIO_USAGE_UNKNOWN:
5720 case AUDIO_USAGE_MEDIA:
5721 case AUDIO_USAGE_VOICE_COMMUNICATION:
5722 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5723 case AUDIO_USAGE_ALARM:
5724 case AUDIO_USAGE_NOTIFICATION:
5725 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5726 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5727 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5728 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5729 case AUDIO_USAGE_NOTIFICATION_EVENT:
5730 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5731 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5732 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5733 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005734 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005735 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005736 break;
5737 default:
5738 return false;
5739 }
5740 return true;
5741}
5742
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005743bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005744 routing_strategy strategy, uint32_t inPastMs,
5745 nsecs_t sysTime) const
5746{
5747 if ((sysTime == 0) && (inPastMs != 0)) {
5748 sysTime = systemTime();
5749 }
Eric Laurent794fde22016-03-11 09:50:45 -08005750 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005751 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5752 (NUM_STRATEGIES == strategy)) &&
5753 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5754 return true;
5755 }
5756 }
5757 return false;
5758}
5759
François Gaffie2110e042015-03-24 08:41:51 +01005760audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5761{
5762 return mEngine->getForceUse(usage);
5763}
5764
5765bool AudioPolicyManager::isInCall()
5766{
5767 return isStateInCall(mEngine->getPhoneState());
5768}
5769
5770bool AudioPolicyManager::isStateInCall(int state)
5771{
5772 return is_state_in_call(state);
5773}
5774
Eric Laurentd60560a2015-04-10 11:31:20 -07005775void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5776{
5777 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5778 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5779 if (sourceDesc->mDevice->equals(deviceDesc)) {
5780 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5781 stopAudioSource(sourceDesc->getHandle());
5782 }
5783 }
5784
5785 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5786 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5787 bool release = false;
5788 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5789 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5790 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5791 source->ext.device.type == deviceDesc->type()) {
5792 release = true;
5793 }
5794 }
5795 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5796 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5797 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5798 sink->ext.device.type == deviceDesc->type()) {
5799 release = true;
5800 }
5801 }
5802 if (release) {
5803 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5804 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5805 }
5806 }
5807}
5808
Phil Burk09bc4612016-02-24 15:58:15 -08005809// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005810void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5811 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005812 // TODO Set this based on Config properties.
5813 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005814
5815 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5816 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005817 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005818
jiabin81772902018-04-02 17:52:27 -07005819 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5820 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5821 formats.clear();
5822 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5823 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005824 }
jiabin81772902018-04-02 17:52:27 -07005825 // Always enable IEC61937 when in MANUAL mode.
5826 formats.add(AUDIO_FORMAT_IEC61937);
5827 } else { // NEVER, AUTO or ALWAYS
5828 // Analyze original support for various formats.
5829 bool supportsAC3 = false;
5830 bool supportsOtherSurround = false;
5831 bool supportsIEC61937 = false;
5832 mSurroundFormats.clear();
5833 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5834 audio_format_t format = formats[formatIndex];
5835 switch (format) {
5836 case AUDIO_FORMAT_AC3:
5837 supportsAC3 = true;
5838 break;
5839 case AUDIO_FORMAT_E_AC3:
5840 case AUDIO_FORMAT_DTS:
5841 case AUDIO_FORMAT_DTS_HD:
5842 // If ALWAYS, remove all other surround formats here
5843 // since we will add them later.
5844 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5845 formats.removeAt(formatIndex);
5846 formatIndex--;
5847 }
5848 supportsOtherSurround = true;
5849 break;
5850 case AUDIO_FORMAT_IEC61937:
5851 supportsIEC61937 = true;
5852 break;
5853 default:
5854 break;
5855 }
5856 }
Phil Burk09bc4612016-02-24 15:58:15 -08005857
jiabin81772902018-04-02 17:52:27 -07005858 // Modify formats based on surround preferences.
5859 // If NEVER, remove support for surround formats.
5860 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5861 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5862 // Remove surround sound related formats.
5863 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5864 audio_format_t format = formats[formatIndex];
5865 switch(format) {
5866 case AUDIO_FORMAT_AC3:
5867 case AUDIO_FORMAT_E_AC3:
5868 case AUDIO_FORMAT_DTS:
5869 case AUDIO_FORMAT_DTS_HD:
5870 case AUDIO_FORMAT_IEC61937:
5871 formats.removeAt(formatIndex);
5872 break;
5873 default:
5874 formatIndex++; // keep it
5875 break;
5876 }
5877 }
5878 supportsAC3 = false;
5879 supportsOtherSurround = false;
5880 supportsIEC61937 = false;
5881 }
5882 } else { // AUTO or ALWAYS
5883 // Most TVs support AC3 even if they do not report it in the EDID.
5884 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5885 && !supportsAC3) {
5886 formats.add(AUDIO_FORMAT_AC3);
5887 supportsAC3 = true;
5888 }
5889
5890 // If ALWAYS, add support for raw surround formats if all are missing.
5891 // This assumes that if any of these formats are reported by the HAL
5892 // then the report is valid and should not be modified.
5893 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5894 formats.add(AUDIO_FORMAT_E_AC3);
5895 formats.add(AUDIO_FORMAT_DTS);
5896 formats.add(AUDIO_FORMAT_DTS_HD);
5897 supportsOtherSurround = true;
5898 }
5899
5900 // Add support for IEC61937 if any raw surround supported.
5901 // The HAL could do this but add it here, just in case.
5902 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5903 formats.add(AUDIO_FORMAT_IEC61937);
5904 supportsIEC61937 = true;
5905 }
5906
5907 // Add reported surround sound formats to enabled surround formats.
5908 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005909 audio_format_t format = formats[formatIndex];
5910 switch(format) {
5911 case AUDIO_FORMAT_AC3:
5912 case AUDIO_FORMAT_E_AC3:
5913 case AUDIO_FORMAT_DTS:
5914 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005915 case AUDIO_FORMAT_AAC_LC:
5916 case AUDIO_FORMAT_DOLBY_TRUEHD:
5917 case AUDIO_FORMAT_E_AC3_JOC:
5918 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005919 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005920 break;
5921 }
Phil Burk09bc4612016-02-24 15:58:15 -08005922 }
Phil Burk07ac1142016-03-25 13:39:29 -07005923 }
Phil Burk09bc4612016-02-24 15:58:15 -08005924 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005925}
5926
5927// Modify the list of channel masks supported.
5928void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5929 ChannelsVector &channelMasks = *channelMasksPtr;
5930 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5931 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5932
5933 // If NEVER, then remove support for channelMasks > stereo.
5934 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5935 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5936 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5937 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5938 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5939 channelMasks.removeAt(maskIndex);
5940 } else {
5941 maskIndex++;
5942 }
5943 }
jiabin81772902018-04-02 17:52:27 -07005944 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5945 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5946 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005947 bool supports5dot1 = false;
5948 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005949 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005950 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5951 supports5dot1 = true;
5952 break;
5953 }
5954 }
5955 // If not then add 5.1 support.
5956 if (!supports5dot1) {
5957 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5958 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5959 }
Phil Burk09bc4612016-02-24 15:58:15 -08005960 }
5961}
5962
Phil Burk00eeb322016-03-31 12:41:00 -07005963void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5964 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005965 AudioProfileVector &profiles)
5966{
5967 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005968
François Gaffie112b0af2015-11-19 16:13:25 +01005969 // Format MUST be checked first to update the list of AudioProfile
5970 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005971 reply = mpClientInterface->getParameters(
5972 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005973 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005974 AudioParameter repliedParameters(reply);
5975 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005976 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005977 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5978 return;
5979 }
Phil Burk09bc4612016-02-24 15:58:15 -08005980 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005981 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005982 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005983 }
Phil Burk09bc4612016-02-24 15:58:15 -08005984 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005985 }
François Gaffie112b0af2015-11-19 16:13:25 +01005986
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005987 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005988 ChannelsVector channelMasks;
5989 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005990 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005991 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005992
5993 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005994 reply = mpClientInterface->getParameters(
5995 ioHandle,
5996 requestedParameters.toString() + ";" +
5997 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005998 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005999 AudioParameter repliedParameters(reply);
6000 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006001 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006002 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006003 }
6004 }
6005 if (profiles.hasDynamicChannelsFor(format)) {
6006 reply = mpClientInterface->getParameters(ioHandle,
6007 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006008 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006009 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006010 AudioParameter repliedParameters(reply);
6011 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006012 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006013 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006014 if (device == AUDIO_DEVICE_OUT_HDMI) {
6015 filterSurroundChannelMasks(&channelMasks);
6016 }
François Gaffie112b0af2015-11-19 16:13:25 +01006017 }
6018 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006019 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006020 }
6021}
Eric Laurentd60560a2015-04-10 11:31:20 -07006022
Mikhail Naganovdc769682018-05-04 15:34:08 -07006023status_t AudioPolicyManager::installPatch(const char *caller,
6024 audio_patch_handle_t *patchHandle,
6025 AudioIODescriptorInterface *ioDescriptor,
6026 const struct audio_patch *patch,
6027 int delayMs)
6028{
6029 ssize_t index = mAudioPatches.indexOfKey(
6030 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6031 *patchHandle : ioDescriptor->getPatchHandle());
6032 sp<AudioPatch> patchDesc;
6033 status_t status = installPatch(
6034 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6035 if (status == NO_ERROR) {
6036 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6037 }
6038 return status;
6039}
6040
6041status_t AudioPolicyManager::installPatch(const char *caller,
6042 ssize_t index,
6043 audio_patch_handle_t *patchHandle,
6044 const struct audio_patch *patch,
6045 int delayMs,
6046 uid_t uid,
6047 sp<AudioPatch> *patchDescPtr)
6048{
6049 sp<AudioPatch> patchDesc;
6050 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6051 if (index >= 0) {
6052 patchDesc = mAudioPatches.valueAt(index);
6053 afPatchHandle = patchDesc->mAfPatchHandle;
6054 }
6055
6056 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6057 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6058 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6059 if (status == NO_ERROR) {
6060 if (index < 0) {
6061 patchDesc = new AudioPatch(patch, uid);
6062 addAudioPatch(patchDesc->mHandle, patchDesc);
6063 } else {
6064 patchDesc->mPatch = *patch;
6065 }
6066 patchDesc->mAfPatchHandle = afPatchHandle;
6067 if (patchHandle) {
6068 *patchHandle = patchDesc->mHandle;
6069 }
6070 nextAudioPortGeneration();
6071 mpClientInterface->onAudioPatchListUpdate();
6072 }
6073 if (patchDescPtr) *patchDescPtr = patchDesc;
6074 return status;
6075}
6076
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006077} // namespace android