blob: 94090230e82948d8968609156a45ac479f880517 [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>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Eric Laurente552edb2014-03-10 17:42:56 -070085// ----------------------------------------------------------------------------
86// AudioPolicyInterface implementation
87// ----------------------------------------------------------------------------
88
Eric Laurente0720872014-03-11 09:30:41 -070089status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080090 audio_policy_dev_state_t state,
91 const char *device_address,
92 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070093{
jiabina7b43792018-02-15 16:04:46 -080094 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
95 nextAudioPortGeneration();
96 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080097}
98
François Gaffie44481e72016-04-20 07:49:57 +020099void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
100 audio_policy_dev_state_t state,
101 const String8 &device_address)
102{
103 AudioParameter param(device_address);
104 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700105 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200106 param.addInt(key, device);
107 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
108}
109
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800111 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800112 const char *device_address,
113 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114{
Paul McLeane743a472015-01-28 11:07:31 -0800115 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800116 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700117
118 // connect/disconnect only 1 device at a time
119 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
120
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<DeviceDescriptor> devDesc =
122 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
125 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700138 ALOGW("setDeviceConnectionState() device already connected: %x", device);
139 return INVALID_OPERATION;
140 }
141 ALOGV("setDeviceConnectionState() connecting device %x", device);
142
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 index = mAvailableOutputDevices.add(devDesc);
145 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100146 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700147 if (module == 0) {
148 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
149 device);
150 mAvailableOutputDevices.remove(devDesc);
151 return INVALID_OPERATION;
152 }
Paul McLeane743a472015-01-28 11:07:31 -0800153 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 } else {
155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
160 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200164
165 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
166 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 return INVALID_OPERATION;
168 }
François Gaffie2110e042015-03-24 08:41:51 +0100169 // Propagate device availability to Engine
170 mEngine->setDeviceConnectionState(devDesc, state);
171
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 // outputs should never be empty here
173 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
174 "checkOutputsForDevice() returned no outputs but status OK");
175 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
176 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700182 ALOGW("setDeviceConnectionState() device not connected: %x", device);
183 return INVALID_OPERATION;
184 }
185
Paul McLean5c477aa2014-08-20 16:47:57 -0700186 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200189 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Eric Laurenta1d525f2015-01-29 13:36:45 -0800194 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100195
196 // Propagate device availability to Engine
197 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700198 } break;
199
200 default:
201 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 return BAD_VALUE;
203 }
204
Mikhail Naganov37977152018-07-11 15:54:44 -0700205 checkForDeviceAndOutputChanges([&]() {
206 // outputs must be closed after checkOutputForAllStrategies() is executed
207 if (!outputs.isEmpty()) {
208 for (audio_io_handle_t output : outputs) {
209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
210 // close unused outputs after device disconnection or direct outputs that have been
211 // opened by checkOutputsForDevice() to query dynamic parameters
212 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
213 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
214 (desc->mDirectOpenCount == 0))) {
215 closeOutput(output);
216 }
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700218 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
219 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 return false;
222 });
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent87ffa392015-05-22 10:32:38 -0700224 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
226 updateCallRouting(newDevice);
227 }
Eric Laurente552edb2014-03-10 17:42:56 -0700228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
230 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
231 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // do not force device change on duplicated output because if device is 0, it will
233 // also force a device 0 for the two outputs it is duplicated to which may override
234 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700235 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100236 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 // always force when disconnecting (a non-duplicated device)
238 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700239 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700240 }
Eric Laurente552edb2014-03-10 17:42:56 -0700241 }
242
Eric Laurentd60560a2015-04-10 11:31:20 -0700243 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
244 cleanUpForDevice(devDesc);
245 }
246
Eric Laurent72aa32f2014-05-30 18:51:48 -0700247 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700248 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700249 } // end if is output device
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // handle input devices
252 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700253 SortedVector <audio_io_handle_t> inputs;
254
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700256 switch (state)
257 {
258 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700259 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700261 ALOGW("setDeviceConnectionState() device already connected: %d", device);
262 return INVALID_OPERATION;
263 }
François Gaffie53615e22015-03-19 09:24:12 +0100264 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700265 if (module == NULL) {
266 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
267 device);
268 return INVALID_OPERATION;
269 }
François Gaffie44481e72016-04-20 07:49:57 +0200270
271 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
272 // parameters on newly connected devices (instead of opening the inputs...)
273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
274
Paul McLean9080a4c2015-06-18 08:24:02 -0700275 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200276 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
277 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700278 return INVALID_OPERATION;
279 }
280
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 index = mAvailableInputDevices.add(devDesc);
282 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800283 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700284 } else {
285 return NO_MEMORY;
286 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800287
François Gaffie2110e042015-03-24 08:41:51 +0100288 // Propagate device availability to Engine
289 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700291
292 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700293 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700295 ALOGW("setDeviceConnectionState() device not connected: %d", device);
296 return INVALID_OPERATION;
297 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
299 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
300
301 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200302 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
Paul McLean9080a4c2015-06-18 08:24:02 -0700304 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700306
François Gaffie2110e042015-03-24 08:41:51 +0100307 // Propagate device availability to Engine
308 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 default:
312 ALOGE("setDeviceConnectionState() invalid state: %x", state);
313 return BAD_VALUE;
314 }
315
Eric Laurentd4692962014-05-05 18:13:44 -0700316 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700317 // As the input device list can impact the output device selection, update
318 // getDeviceForStrategy() cache
319 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700320
Eric Laurent87ffa392015-05-22 10:32:38 -0700321 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
323 updateCallRouting(newDevice);
324 }
325
Eric Laurentd60560a2015-04-10 11:31:20 -0700326 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
327 cleanUpForDevice(devDesc);
328 }
329
Eric Laurentb52c1522014-05-20 11:27:36 -0700330 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700332 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700333
334 ALOGW("setDeviceConnectionState() invalid device: %x", device);
335 return BAD_VALUE;
336}
337
Eric Laurente0720872014-03-11 09:30:41 -0700338audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100339 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700340{
Eric Laurent634b7142016-04-20 13:48:02 -0700341 sp<DeviceDescriptor> devDesc =
342 mHwModules.getDeviceDescriptor(device, device_address, "",
343 (strlen(device_address) != 0)/*matchAddress*/);
344
345 if (devDesc == 0) {
346 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
347 device, device_address);
348 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
349 }
François Gaffie53615e22015-03-19 09:24:12 +0100350
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 DeviceVector *deviceVector;
352
Eric Laurente552edb2014-03-10 17:42:56 -0700353 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 deviceVector = &mAvailableInputDevices;
357 } else {
358 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
359 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
Eric Laurent634b7142016-04-20 13:48:02 -0700361
362 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800364}
365
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
367 const char *device_address,
368 const char *device_name)
369{
370 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431}
432
Eric Laurentdc462862016-07-19 12:29:53 -0700433uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434{
435 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700436 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437
Andy Hunga76c7de2016-12-13 19:14:31 -0800438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700439 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 createTxPatch = true;
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 return muteWaitMs;
475}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 sp<DeviceDescriptor> txSourceDeviceDesc;
482 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700483 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
484 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700486 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
487 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 }
489
490 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
491 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
492 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
493 // request to reuse existing output stream if one is already opened to reach the target device
494 if (output != AUDIO_IO_HANDLE_NONE) {
495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
496 ALOG_ASSERT(!outputDesc->isDuplicated(),
497 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800499 }
500
501 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 // terminate active capture if on the same HW module as the call TX source device
503 // FIXME: would be better to refine to only inputs whose profile connects to the
504 // call TX device but this information is not in the audio patch and logic here must be
505 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800506 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800507 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
508 AudioSessionCollection activeSessions =
509 activeDesc->getAudioSessions(true /*activeOnly*/);
510 for (size_t j = 0; j < activeSessions.size(); j++) {
511 audio_session_t activeSession = activeSessions.keyAt(j);
512 stopInput(activeDesc->mIoHandle, activeSession);
513 releaseInput(activeDesc->mIoHandle, activeSession);
514 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700515 }
516 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 }
Eric Laurentdc462862016-07-19 12:29:53 -0700518
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800519 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520 status_t status = mpClientInterface->createAudioPatch(
521 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800522 ALOGW_IF(status != NO_ERROR,
523 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
524 sp<AudioPatch> audioPatch;
525 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 audioPatch->mAfPatchHandle = afPatchHandle;
528 audioPatch->mUid = mUidCached;
529 }
530 return audioPatch;
531}
532
Mikhail Naganovdc769682018-05-04 15:34:08 -0700533sp<DeviceDescriptor> AudioPolicyManager::findDevice(
534 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700535 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700538 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700539}
540
Eric Laurente0720872014-03-11 09:30:41 -0700541void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700542{
543 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100544 // store previous phone state for management of sonification strategy below
545 int oldState = mEngine->getPhoneState();
546
547 if (mEngine->setPhoneState(state) != NO_ERROR) {
548 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700549 return;
550 }
François Gaffie2110e042015-03-24 08:41:51 +0100551 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700552 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700553 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700554 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800555 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 }
557
François Gaffie2110e042015-03-24 08:41:51 +0100558 /**
559 * Switching to or from incall state or switching between telephony and VoIP lead to force
560 * routing command.
561 */
562 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
563 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700564
565 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700566 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700567
Eric Laurente552edb2014-03-10 17:42:56 -0700568 int delayMs = 0;
569 if (isStateInCall(state)) {
570 nsecs_t sysTime = systemTime();
571 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700573 // mute media and sonification strategies and delay device switch by the largest
574 // latency of any output where either strategy is active.
575 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100576 if ((isStrategyActive(desc, STRATEGY_MEDIA,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime) ||
579 isStrategyActive(desc, STRATEGY_SONIFICATION,
580 SONIFICATION_HEADSET_MUSIC_DELAY,
581 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 (delayMs < (int)desc->latency()*2)) {
583 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700584 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_MEDIA, true, desc);
586 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
589 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700590 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
591 }
592 }
593
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 if (hasPrimaryOutput()) {
595 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
596 // the device returned is not necessarily reachable via this output
597 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
598 // force routing command to audio hardware when ending call
599 // even if no device change is needed
600 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
601 rxDevice = mPrimaryOutput->device();
602 }
Eric Laurente552edb2014-03-10 17:42:56 -0700603
Eric Laurent87ffa392015-05-22 10:32:38 -0700604 if (state == AUDIO_MODE_IN_CALL) {
605 updateCallRouting(rxDevice, delayMs);
606 } else if (oldState == AUDIO_MODE_IN_CALL) {
607 if (mCallRxPatch != 0) {
608 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
609 mCallRxPatch.clear();
610 }
611 if (mCallTxPatch != 0) {
612 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
613 mCallTxPatch.clear();
614 }
615 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
616 } else {
617 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700618 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700620
621 // reevaluate routing on all outputs in case tracks have been started during the call
622 for (size_t i = 0; i < mOutputs.size(); i++) {
623 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
624 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
625 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800626 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627 }
628 }
629
Eric Laurente552edb2014-03-10 17:42:56 -0700630 if (isStateInCall(state)) {
631 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700632 // force reevaluating accessibility routing when call starts
633 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 }
635
636 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 if (state == AUDIO_MODE_RINGTONE &&
638 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700639 mLimitRingtoneVolume = true;
640 } else {
641 mLimitRingtoneVolume = false;
642 }
643}
644
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700645audio_mode_t AudioPolicyManager::getPhoneState() {
646 return mEngine->getPhoneState();
647}
648
Eric Laurente0720872014-03-11 09:30:41 -0700649void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700651{
François Gaffie2110e042015-03-24 08:41:51 +0100652 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700653 if (config == mEngine->getForceUse(usage)) {
654 return;
655 }
Eric Laurente552edb2014-03-10 17:42:56 -0700656
François Gaffie2110e042015-03-24 08:41:51 +0100657 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
658 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
659 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700660 }
François Gaffie2110e042015-03-24 08:41:51 +0100661 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
662 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
663 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700664
665 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700666 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800667
Eric Laurentdc462862016-07-19 12:29:53 -0700668 //FIXME: workaround for truncated touch sounds
669 // to be removed when the problem is handled by system UI
670 uint32_t delayMs = 0;
671 uint32_t waitMs = 0;
672 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
673 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
674 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700677 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700680 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
681 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
682 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
684 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700687 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
689 }
690
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800691 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800694 if (activeDesc->mProfile->getSupportedDevices().types() &
695 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
696 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700697 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 }
Eric Laurente552edb2014-03-10 17:42:56 -0700700 }
Eric Laurente552edb2014-03-10 17:42:56 -0700701}
702
Eric Laurente0720872014-03-11 09:30:41 -0700703void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700704{
705 ALOGV("setSystemProperty() property %s, value %s", property, value);
706}
707
708// Find a direct output profile compatible with the parameters passed, even if the input flags do
709// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800710sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700711 audio_devices_t device,
712 uint32_t samplingRate,
713 audio_format_t format,
714 audio_channel_mask_t channelMask,
715 audio_output_flags_t flags)
716{
Eric Laurent861a6282015-05-18 15:40:16 -0700717 // only retain flags that will drive the direct output profile selection
718 // if explicitly requested
719 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700720 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
721 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700722 flags =
723 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
724
725 sp<IOProfile> profile;
726
Mikhail Naganovd4120142017-12-06 15:49:22 -0800727 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800728 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700730 samplingRate, NULL /*updatedSamplingRate*/,
731 format, NULL /*updatedFormat*/,
732 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700733 flags)) {
734 continue;
735 }
736 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 continue;
739 }
740 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100741 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700742 continue;
743 }
744 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100745 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700746 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700747 }
Eric Laurente552edb2014-03-10 17:42:56 -0700748 }
749 }
Eric Laurent861a6282015-05-18 15:40:16 -0700750 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700751}
752
Eric Laurentf4e63452017-11-06 19:31:46 +0000753audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700754{
Eric Laurent3b73df72014-03-11 09:06:29 -0700755 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700756 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800757
758 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
759 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
760 // format, flags, etc. This may result in some discrepancy for functions that utilize
761 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
762 // and AudioSystem::getOutputSamplingRate().
763
Eric Laurentf4e63452017-11-06 19:31:46 +0000764 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
765 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700766
Eric Laurentf4e63452017-11-06 19:31:46 +0000767 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
768 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769}
770
Eric Laurente83b55d2014-11-14 10:06:21 -0800771status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
772 audio_io_handle_t *output,
773 audio_session_t session,
774 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700775 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800776 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200777 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700778 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800779 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780{
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 audio_attributes_t attributes;
782 if (attr != NULL) {
783 if (!isValidAttributes(attr)) {
784 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
785 attr->usage, attr->content_type, attr->flags,
786 attr->tags);
787 return BAD_VALUE;
788 }
789 attributes = *attr;
790 } else {
791 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
792 ALOGE("getOutputForAttr(): invalid stream type");
793 return BAD_VALUE;
794 }
795 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800797
798 // TODO: check for existing client for this port ID
799 if (*portId == AUDIO_PORT_HANDLE_NONE) {
800 *portId = AudioPort::getNextUniqueId();
801 }
802
Eric Laurentc75307b2015-03-17 15:29:32 -0700803 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800804 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100805 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800806 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100807 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800808 }
François Gaffie036e1e92015-03-19 10:16:24 +0100809 *stream = streamTypefromAttributesInt(&attributes);
810 *output = desc->mIoHandle;
811 ALOGV("getOutputForAttr() returns output %d", *output);
812 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800813 }
814 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
815 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
816 return BAD_VALUE;
817 }
818
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700819 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
820 " session %d selectedDeviceId %d",
821 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700823
824 *stream = streamTypefromAttributesInt(&attributes);
825
826 // Explicit routing?
827 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700828 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800829 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700830 }
831 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700832
Eric Laurente83b55d2014-11-14 10:06:21 -0800833 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700834 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700835
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200837 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700838 }
839
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800840 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
841 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200842 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700843
Andy Hungc88b0642018-04-27 15:42:35 -0700844 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700846 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 return INVALID_OPERATION;
848 }
Paul McLeanaa981192015-03-21 09:55:15 -0700849
Mikhail Naganov708e0382018-05-30 09:53:04 -0700850 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700851 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
852 : AUDIO_PORT_HANDLE_NONE;
853
854 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857}
858
859audio_io_handle_t AudioPolicyManager::getOutputForDevice(
860 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800861 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800863 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200864 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700865{
Andy Hungc88b0642018-04-27 15:42:35 -0700866 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700867 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700868
Eric Laurente552edb2014-03-10 17:42:56 -0700869 // open a direct output if required by specified parameters
870 //force direct flag if offload flag is set: offloading implies a direct output stream
871 // and all common behaviors are driven by checking only the direct flag
872 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200873 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
874 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700875 }
Nadav Bar766fb022018-01-07 12:18:03 +0200876 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
877 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700878 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800879 // only allow deep buffering for music stream type
880 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200881 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700882 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200883 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700884 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
885 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200886 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800887 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700888 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200889 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700890 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800891 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200892 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700893 AUDIO_OUTPUT_FLAG_DIRECT);
894 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200895 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
896 stream == AUDIO_STREAM_MUSIC &&
897 audio_is_linear_pcm(config->format) &&
898 isInCall()) {
899 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700900 }
Eric Laurente552edb2014-03-10 17:42:56 -0700901
Nadav Bar766fb022018-01-07 12:18:03 +0200902
Eric Laurentb732cf52014-09-24 19:08:21 -0700903 sp<IOProfile> profile;
904
905 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700906 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200907 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800908 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
909 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700910 goto non_direct_output;
911 }
912
Andy Hung2ddee192015-12-18 17:34:44 -0800913 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
914 // This prevents creating an offloaded track and tearing it down immediately after start
915 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700916 // FIXME: We should check the audio session here but we do not have it in this context.
917 // This may prevent offloading in rare situations where effects are left active by apps
918 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700919
Nadav Bar766fb022018-01-07 12:18:03 +0200920 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800921 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700922 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800923 config->sample_rate,
924 config->format,
925 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200926 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700927 }
928
Eric Laurent1c333e22014-05-20 10:48:17 -0700929 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700930 // exclusive outputs for MMAP and Offload are enforced by different session ids.
931 for (size_t i = 0; i < mOutputs.size(); i++) {
932 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
933 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
934 // reuse direct output if currently open by the same client
935 // and configured with same parameters
936 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700937 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700938 (config->channel_mask == desc->mChannelMask) &&
939 (session == desc->mDirectClientSession)) {
940 desc->mDirectOpenCount++;
941 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
942 mOutputs.keyAt(i), session);
943 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 }
945 }
946 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800947
948 if (!profile->canOpenNewIo()) {
949 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700950 }
Eric Laurent861a6282015-05-18 15:40:16 -0700951
Eric Laurent3974e3b2017-12-07 17:58:43 -0800952 sp<SwAudioOutputDescriptor> outputDesc =
953 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800954
Mikhail Naganov708e0382018-05-30 09:53:04 -0700955 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800956 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
957 : String8("");
958
Nadav Bar766fb022018-01-07 12:18:03 +0200959 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700960
961 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700962 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800963 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700964 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800965 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
966 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
967 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
968 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
969 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700970 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800971 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700972 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800973 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800974 if (audio_is_linear_pcm(config->format) &&
975 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800976 goto non_direct_output;
977 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700978 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700980 outputDesc->mRefCount[stream] = 0;
981 outputDesc->mStopTime[stream] = 0;
982 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800983 outputDesc->mDirectClientSession = session;
984
Eric Laurente552edb2014-03-10 17:42:56 -0700985 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700986 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000987 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700988 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700989 return output;
990 }
991
Eric Laurentb732cf52014-09-24 19:08:21 -0700992non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700993
994 // A request for HW A/V sync cannot fallback to a mixed output because time
995 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -0800996 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -0700997 return AUDIO_IO_HANDLE_NONE;
998 }
999
Eric Laurente552edb2014-03-10 17:42:56 -07001000 // ignoring channel mask due to downmix capability in mixer
1001
1002 // open a non direct output
1003
1004 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001005 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001006 // get which output is suitable for the specified stream. The actual
1007 // routing change will happen when startOutput() will be called
1008 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1009
Eric Laurent8838a382014-09-08 16:44:28 -07001010 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001011 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1012 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001013 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001014 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001015 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001016 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001017
Eric Laurente552edb2014-03-10 17:42:56 -07001018 return output;
1019}
1020
Eric Laurente0720872014-03-11 09:30:41 -07001021audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001022 audio_output_flags_t flags,
1023 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001024{
1025 // select one output among several that provide a path to a particular device or set of
1026 // devices (the list was previously build by getOutputsForDevice()).
1027 // The priority is as follows:
1028 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001029 // 2: the output with the bit depth the closest to the requested one
1030 // 3: the primary output
1031 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001032
1033 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001034 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001035 }
1036 if (outputs.size() == 1) {
1037 return outputs[0];
1038 }
1039
1040 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001041 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1042 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1043 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001044 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1045 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001046
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001047 for (audio_io_handle_t output : outputs) {
1048 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001049 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001050 // if a valid format is specified, skip output if not compatible
1051 if (format != AUDIO_FORMAT_INVALID) {
1052 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001053 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001054 continue;
1055 }
1056 } else if (!audio_is_linear_pcm(format)) {
1057 continue;
1058 }
Eric Laurente6930022016-02-11 10:20:40 -08001059 if (AudioPort::isBetterFormatMatch(
1060 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001061 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001062 bestFormat = outputDesc->mFormat;
1063 }
Eric Laurent8838a382014-09-08 16:44:28 -07001064 }
1065
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001066 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001067 if (commonFlags >= maxCommonFlags) {
1068 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001069 if (format != AUDIO_FORMAT_INVALID
1070 && AudioPort::isBetterFormatMatch(
1071 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001072 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001073 bestFormatForFlags = outputDesc->mFormat;
1074 }
1075 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001076 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001077 maxCommonFlags = commonFlags;
1078 bestFormatForFlags = outputDesc->mFormat;
1079 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001080 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001081 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001082 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001083 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001084 }
1085 }
1086 }
1087
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001088 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001089 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001090 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001091 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001092 return outputForFormat;
1093 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001094 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001095 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
1097
1098 return outputs[0];
1099}
1100
Eric Laurente0720872014-03-11 09:30:41 -07001101status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001102 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001103 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001104{
Paul McLeanaa981192015-03-21 09:55:15 -07001105 ALOGV("startOutput() output %d, stream %d, session %d",
1106 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001107 ssize_t index = mOutputs.indexOfKey(output);
1108 if (index < 0) {
1109 ALOGW("startOutput() unknown output %d", output);
1110 return BAD_VALUE;
1111 }
1112
Eric Laurentc75307b2015-03-17 15:29:32 -07001113 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1114
Eric Laurent733ce942017-12-07 12:18:25 -08001115 status_t status = outputDesc->start();
1116 if (status != NO_ERROR) {
1117 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001118 }
1119
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001120 // Routing?
1121 mOutputRoutes.incRouteActivity(session);
1122
Eric Laurentc75307b2015-03-17 15:29:32 -07001123 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001124 AudioMix *policyMix = NULL;
1125 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001126 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001127 policyMix = outputDesc->mPolicyMix;
1128 address = policyMix->mDeviceAddress.string();
1129 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1130 newDevice = policyMix->mDeviceType;
1131 } else {
1132 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1133 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001134 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001135 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001136 if (newDevice != outputDesc->device()) {
1137 checkStrategyRoute(getStrategy(stream), output);
1138 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001139 } else {
1140 newDevice = AUDIO_DEVICE_NONE;
1141 }
1142
1143 uint32_t delayMs = 0;
1144
Eric Laurent733ce942017-12-07 12:18:25 -08001145 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001146
1147 if (status != NO_ERROR) {
1148 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001149 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001150 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001151 }
1152 // Automatically enable the remote submix input when output is started on a re routing mix
1153 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001154 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1155 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001156 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1157 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001158 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001159 "remote-submix");
1160 }
1161
1162 if (delayMs != 0) {
1163 usleep(delayMs * 1000);
1164 }
1165
1166 return status;
1167}
1168
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001169status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 audio_stream_type_t stream,
1171 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001172 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 uint32_t *delayMs)
1174{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001175 // cannot start playback of STREAM_TTS if any other output is being used
1176 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001177
1178 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001179 if (stream == AUDIO_STREAM_TTS) {
1180 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001181 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001182 return INVALID_OPERATION;
1183 } else {
1184 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1185 }
1186 } else {
1187 // some playback other than beacon starts
1188 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1189 }
1190
Eric Laurent77305a62016-07-25 16:39:22 -07001191 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001192 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001193 bool force = !outputDesc->isActive() &&
1194 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001195
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001196 // requiresMuteCheck is false when we can bypass mute strategy.
1197 // It covers a common case when there is no materially active audio
1198 // and muting would result in unnecessary delay and dropped audio.
1199 const uint32_t outputLatencyMs = outputDesc->latency();
1200 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1201
Eric Laurente552edb2014-03-10 17:42:56 -07001202 // increment usage count for this stream on the requested output:
1203 // NOTE that the usage count is the same for duplicated output and hardware output which is
1204 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1205 outputDesc->changeRefCount(stream, 1);
1206
Eric Laurent36829f92017-04-07 19:04:42 -07001207 if (stream == AUDIO_STREAM_MUSIC) {
1208 selectOutputForMusicEffects();
1209 }
1210
Eric Laurent493404d2015-04-21 15:07:36 -07001211 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001212 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001213 if (device == AUDIO_DEVICE_NONE) {
1214 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001215 }
Eric Laurent36829f92017-04-07 19:04:42 -07001216
Eric Laurente552edb2014-03-10 17:42:56 -07001217 routing_strategy strategy = getStrategy(stream);
1218 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001219 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1220 (beaconMuteLatency > 0);
1221 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001223 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001224 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001225 // An output has a shared device if
1226 // - managed by the same hw module
1227 // - supports the currently selected device
1228 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1229 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1230
Eric Laurent77305a62016-07-25 16:39:22 -07001231 // force a device change if any other output is:
1232 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001233 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001234 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001235 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001236 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001237 // change the device currently selected by the other output.
1238 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001239 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001240 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001241 force = true;
1242 }
1243 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001244 // a notification so that audio focus effect can propagate, or that a mute/unmute
1245 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001246 const uint32_t latencyMs = desc->latency();
1247 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1248
1249 if (shouldWait && isActive && (waitMs < latencyMs)) {
1250 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001251 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001252
1253 // Require mute check if another output is on a shared device
1254 // and currently active to have proper drain and avoid pops.
1255 // Note restoring AudioTracks onto this output needs to invoke
1256 // a volume ramp if there is no mute.
1257 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001258 }
1259 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001260
1261 const uint32_t muteWaitMs =
1262 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001263
Eric Laurente552edb2014-03-10 17:42:56 -07001264 // apply volume rules for current stream and device if necessary
1265 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001266 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001267 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001268 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001269
1270 // update the outputs if starting an output with a stream that can affect notification
1271 // routing
1272 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001273
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001274 // force reevaluating accessibility routing when ringtone or alarm starts
1275 if (strategy == STRATEGY_SONIFICATION) {
1276 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1277 }
Eric Laurentdc462862016-07-19 12:29:53 -07001278
1279 if (waitMs > muteWaitMs) {
1280 *delayMs = waitMs - muteWaitMs;
1281 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001282
1283 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1284 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1285 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1286 // change occurs after the MixerThread starts and causes a stream volume
1287 // glitch.
1288 //
1289 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001290 }
Eric Laurentdc462862016-07-19 12:29:53 -07001291
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001292 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1293 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1294 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1295 }
1296
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001297 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1298 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1299 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1300 }
1301
Eric Laurente552edb2014-03-10 17:42:56 -07001302 return NO_ERROR;
1303}
1304
1305
Eric Laurente0720872014-03-11 09:30:41 -07001306status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001307 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001308 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001309{
1310 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1311 ssize_t index = mOutputs.indexOfKey(output);
1312 if (index < 0) {
1313 ALOGW("stopOutput() unknown output %d", output);
1314 return BAD_VALUE;
1315 }
1316
Eric Laurentc75307b2015-03-17 15:29:32 -07001317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001318
Eric Laurentc75307b2015-03-17 15:29:32 -07001319 if (outputDesc->mRefCount[stream] == 1) {
1320 // Automatically disable the remote submix input when output is stopped on a
1321 // re routing mix of type MIX_TYPE_RECORDERS
1322 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1323 outputDesc->mPolicyMix != NULL &&
1324 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1325 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1326 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001327 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001328 "remote-submix");
1329 }
1330 }
1331
1332 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001333 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001334 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001335 int activityCount = mOutputRoutes.decRouteActivity(session);
1336 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1337
1338 if (forceDeviceUpdate) {
1339 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1340 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001341 }
1342
Eric Laurent3974e3b2017-12-07 17:58:43 -08001343 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1344
Eric Laurent733ce942017-12-07 12:18:25 -08001345 if (status == NO_ERROR ) {
1346 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001347 }
1348 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001349}
1350
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001351status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001352 audio_stream_type_t stream,
1353 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001354{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001355 // always handle stream stop, check which stream type is stopping
1356 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1357
Eric Laurente552edb2014-03-10 17:42:56 -07001358 if (outputDesc->mRefCount[stream] > 0) {
1359 // decrement usage count of this stream on the output
1360 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001361
Eric Laurente552edb2014-03-10 17:42:56 -07001362 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001363 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001364 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001365 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001366 // delay the device switch by twice the latency because stopOutput() is executed when
1367 // the track stop() command is received and at that time the audio track buffer can
1368 // still contain data that needs to be drained. The latency only covers the audio HAL
1369 // and kernel buffers. Also the latency does not always include additional delay in the
1370 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001371 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001372
1373 // force restoring the device selection on other active outputs if it differs from the
1374 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001375 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001376 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001377 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001378 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001379 desc->isActive() &&
1380 outputDesc->sharesHwModuleWith(desc) &&
1381 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001382 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1383 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001384
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001386 newDevice2,
1387 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001388 delayMs);
1389 // re-apply device specific volume if not done by setOutputDevice()
1390 if (!force) {
1391 applyStreamVolumes(desc, newDevice2, delayMs);
1392 }
Eric Laurente552edb2014-03-10 17:42:56 -07001393 }
1394 }
1395 // update the outputs if stopping one with a stream that can affect notification routing
1396 handleNotificationRoutingForStream(stream);
1397 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001398
1399 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1400 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1401 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1402 }
1403
Eric Laurent36829f92017-04-07 19:04:42 -07001404 if (stream == AUDIO_STREAM_MUSIC) {
1405 selectOutputForMusicEffects();
1406 }
Eric Laurente552edb2014-03-10 17:42:56 -07001407 return NO_ERROR;
1408 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001410 return INVALID_OPERATION;
1411 }
1412}
1413
Eric Laurente83b55d2014-11-14 10:06:21 -08001414void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001415 audio_stream_type_t stream __unused,
1416 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001417{
1418 ALOGV("releaseOutput() %d", output);
1419 ssize_t index = mOutputs.indexOfKey(output);
1420 if (index < 0) {
1421 ALOGW("releaseOutput() releasing unknown output %d", output);
1422 return;
1423 }
1424
Paul McLeanaa981192015-03-21 09:55:15 -07001425 // Routing
1426 mOutputRoutes.removeRoute(session);
1427
Eric Laurentc75307b2015-03-17 15:29:32 -07001428 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001429 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001430 if (desc->mDirectOpenCount <= 0) {
1431 ALOGW("releaseOutput() invalid open count %d for output %d",
1432 desc->mDirectOpenCount, output);
1433 return;
1434 }
1435 if (--desc->mDirectOpenCount == 0) {
1436 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001437 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001438 }
1439 }
1440}
1441
1442
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1444 audio_io_handle_t *input,
1445 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001446 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001447 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001448 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001449 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001450 input_type_t *inputType,
1451 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001452{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001453 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001454 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001455 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001456
Eric Laurentad2e7b92017-09-14 20:06:42 -07001457 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001458 // handle legacy remote submix case where the address was not always specified
1459 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001460 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001461 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001462 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001463 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001464
Eric Laurentfe231122017-11-17 17:48:06 -08001465 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1466 inputSource = AUDIO_SOURCE_MIC;
1467 }
1468
Paul McLean466dc8e2015-04-17 13:15:36 -06001469 // Explicit routing?
1470 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001471 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001472 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001473 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001474 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001475
Eric Laurentad2e7b92017-09-14 20:06:42 -07001476 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1477 // possible
1478 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1479 *input != AUDIO_IO_HANDLE_NONE) {
1480 ssize_t index = mInputs.indexOfKey(*input);
1481 if (index < 0) {
1482 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1483 status = BAD_VALUE;
1484 goto error;
1485 }
1486 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1487 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1488 if (audioSession == 0) {
1489 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1490 status = BAD_VALUE;
1491 goto error;
1492 }
1493 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1494 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001495 // corresponds to a new client and is only permitted from the same UID.
1496 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001497 if (audioSession->openCount() == 1) {
1498 audioSession->setUid(uid);
1499 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001500 if (!audioSession->isSilenced()) {
1501 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1502 uid, session, audioSession->uid());
1503 status = INVALID_OPERATION;
1504 goto error;
1505 }
1506 audioSession->setUid(uid);
1507 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001508 }
1509 audioSession->changeOpenCount(1);
1510 *inputType = API_INPUT_LEGACY;
1511 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1512 *portId = AudioPort::getNextUniqueId();
1513 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001514 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001515 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1516 : AUDIO_PORT_HANDLE_NONE;
1517 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1518
1519 return NO_ERROR;
1520 }
1521
1522 *input = AUDIO_IO_HANDLE_NONE;
1523 *inputType = API_INPUT_INVALID;
1524
Eric Laurentad2e7b92017-09-14 20:06:42 -07001525 halInputSource = inputSource;
1526
1527 // TODO: check for existing client for this port ID
1528 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1529 *portId = AudioPort::getNextUniqueId();
1530 }
1531
1532 audio_devices_t device;
1533
Eric Laurentc447ded2015-01-06 08:47:05 -08001534 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001535 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001536 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1537 if (status != NO_ERROR) {
1538 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001539 }
1540 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001541 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1542 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001543 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001544 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001545 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001546 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001547 status = BAD_VALUE;
1548 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001549 }
Eric Laurentc722f302014-12-10 11:21:49 -08001550 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001551 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001552 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1553 // there is an external policy, but this input is attached to a mix of recorders,
1554 // meaning it receives audio injected into the framework, so the recorder doesn't
1555 // know about it and is therefore considered "legacy"
1556 *inputType = API_INPUT_LEGACY;
1557 } else {
1558 // recording a mix of players defined by an external policy, we're rerouting for
1559 // an external policy
1560 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1561 }
Eric Laurentc722f302014-12-10 11:21:49 -08001562 } else if (audio_is_remote_submix_device(device)) {
1563 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001564 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001565 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1566 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001567 } else {
1568 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001569 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001570
Eric Laurent599c7582015-12-07 18:05:55 -08001571 }
1572
1573 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001574 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001575 policyMix);
1576 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001577 status = INVALID_OPERATION;
1578 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001579 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001580
Mikhail Naganov708e0382018-05-30 09:53:04 -07001581 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001582 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1583 : AUDIO_PORT_HANDLE_NONE;
1584
1585 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1586 *input, *inputType, *selectedDeviceId);
1587
Eric Laurent599c7582015-12-07 18:05:55 -08001588 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001589
1590error:
1591 mInputRoutes.removeRoute(session);
1592 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001593}
1594
1595
1596audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1597 String8 address,
1598 audio_session_t session,
1599 uid_t uid,
1600 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001601 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001602 audio_input_flags_t flags,
1603 AudioMix *policyMix)
1604{
1605 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1606 audio_source_t halInputSource = inputSource;
1607 bool isSoundTrigger = false;
1608
1609 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1610 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1611 if (index >= 0) {
1612 input = mSoundTriggerSessions.valueFor(session);
1613 isSoundTrigger = true;
1614 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1615 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1616 } else {
1617 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001618 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001619 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001620 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001621 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001622 }
1623
Andy Hungf129b032015-04-07 13:45:50 -07001624 // find a compatible input profile (not necessarily identical in parameters)
1625 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001626 // sampling rate and flags may be updated by getInputProfile
1627 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1628 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001629 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001630 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001631 audio_input_flags_t profileFlags = flags;
1632 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001633 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001634 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001635 profileSamplingRate, profileFormat, profileChannelMask,
1636 profileFlags);
1637 if (profile != 0) {
1638 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001639 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1640 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001641 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1642 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1643 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001644 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001645 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1646 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001647 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001648 }
Eric Laurente552edb2014-03-10 17:42:56 -07001649 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001650 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001651 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001652 if (samplingRate == 0) {
1653 samplingRate = profileSamplingRate;
1654 }
Eric Laurente552edb2014-03-10 17:42:56 -07001655
Eric Laurent322b4d22015-04-03 15:57:54 -07001656 if (profile->getModuleHandle() == 0) {
1657 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001658 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001659 }
1660
Eric Laurent599c7582015-12-07 18:05:55 -08001661 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001662 inputSource,
1663 config->format,
1664 samplingRate,
1665 config->channel_mask,
1666 flags,
1667 uid,
1668 isSoundTrigger,
1669 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001670
Eric Laurent74708e72017-04-07 17:13:42 -07001671// FIXME: disable concurrent capture until UI is ready
1672#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001673 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001674 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001675 for (size_t i = 0; i < mInputs.size(); i++) {
1676 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001677 // reuse input if:
1678 // - it shares the same profile
1679 // AND
1680 // - it is not a reroute submix input
1681 // AND
1682 // - it is: not used for sound trigger
1683 // OR
1684 // used for sound trigger and all clients use the same session ID
1685 //
1686 if ((profile == desc->mProfile) &&
1687 (isSoundTrigger == desc->isSoundTrigger()) &&
1688 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001689
1690 sp<AudioSession> as = desc->getAudioSession(session);
1691 if (as != 0) {
1692 // do not allow unmatching properties on same session
1693 if (as->matches(audioSession)) {
1694 as->changeOpenCount(1);
1695 } else {
1696 ALOGW("getInputForDevice() record with different attributes"
1697 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001698 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001699 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001700 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001701 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001702 }
Eric Laurentbb948092017-01-23 18:33:30 -08001703
Eric Laurent555530a2017-02-07 18:17:24 -08001704 // Reuse the already opened input stream on this profile if:
1705 // - the new capture source is background OR
1706 // - the path requested configurations match OR
1707 // - the new source priority is less than the highest source priority on this input
1708 // If the input stream cannot be reused, close it before opening a new stream
1709 // on the same profile for the new client so that the requested path configuration
1710 // can be selected.
1711 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001712 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001713 desc->mChannelMask != config->channel_mask ||
1714 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001715 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001716 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001717 reusedInputDesc = desc;
1718 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001719 } else {
1720 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001721 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1722 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001723 }
Eric Laurent599c7582015-12-07 18:05:55 -08001724 }
1725 }
Eric Laurent599c7582015-12-07 18:05:55 -08001726
Eric Laurent555530a2017-02-07 18:17:24 -08001727 if (reusedInputDesc != 0) {
1728 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1729 for (size_t j = 0; j < sessions.size(); j++) {
1730 audio_session_t currentSession = sessions.keyAt(j);
1731 stopInput(reusedInputDesc->mIoHandle, currentSession);
1732 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1733 }
1734 }
Eric Laurent74708e72017-04-07 17:13:42 -07001735#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001736
Eric Laurent3974e3b2017-12-07 17:58:43 -08001737 if (!profile->canOpenNewIo()) {
1738 return AUDIO_IO_HANDLE_NONE;
1739 }
1740
Eric Laurentfe231122017-11-17 17:48:06 -08001741 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001742
Eric Laurentfe231122017-11-17 17:48:06 -08001743 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1744 lConfig.sample_rate = profileSamplingRate;
1745 lConfig.channel_mask = profileChannelMask;
1746 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001747
Eric Laurent53b810e2017-12-10 17:25:10 -08001748 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001749 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001750 // the inputs vector must be of size >= 1, but we don't want to crash here
1751 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1752 }
1753
Eric Laurentfe231122017-11-17 17:48:06 -08001754 status_t status = inputDesc->open(&lConfig, device, address,
1755 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001756
1757 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001758 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001759 (profileSamplingRate != lConfig.sample_rate) ||
1760 !audio_formats_match(profileFormat, lConfig.format) ||
1761 (profileChannelMask != lConfig.channel_mask)) {
1762 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001763 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001764 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001765 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001766 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001767 }
Eric Laurent599c7582015-12-07 18:05:55 -08001768 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001769 }
1770
Eric Laurentc722f302014-12-10 11:21:49 -08001771 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001772 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001773
Eric Laurent599c7582015-12-07 18:05:55 -08001774 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001775 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001776
Eric Laurent599c7582015-12-07 18:05:55 -08001777 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001778}
1779
Eric Laurentbb948092017-01-23 18:33:30 -08001780//static
1781bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1782{
1783 return (source == AUDIO_SOURCE_HOTWORD) ||
1784 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1785 (source == AUDIO_SOURCE_FM_TUNER);
1786}
1787
Eric Laurentfb66dd92016-01-28 18:32:03 -08001788bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1789 const sp<AudioSession>& audioSession)
1790{
1791 // Do not allow capture if an active voice call is using a software patch and
1792 // the call TX source device is on the same HW module.
1793 // FIXME: would be better to refine to only inputs whose profile connects to the
1794 // call TX device but this information is not in the audio patch
1795 if (mCallTxPatch != 0 &&
1796 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1797 return false;
1798 }
1799
1800 // starting concurrent capture is enabled if:
1801 // 1) capturing for re-routing
1802 // 2) capturing for HOTWORD source
1803 // 3) capturing for FM TUNER source
1804 // 3) All other active captures are either for re-routing or HOTWORD
1805
1806 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001807 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001808 return true;
1809 }
1810
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001811 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001812 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001813 !is_virtual_input_device(activeInput->mDevice)) {
1814 return false;
1815 }
1816 }
1817
1818 return true;
1819}
1820
Chris Thornton2b864642017-06-27 21:26:07 -07001821// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1822bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1823 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1824 bool soundTriggerSupportsConcurrentCapture = false;
1825 unsigned int numModules = 0;
1826 struct sound_trigger_module_descriptor* nModules = NULL;
1827
1828 status_t status = SoundTrigger::listModules(nModules, &numModules);
1829 if (status == NO_ERROR && numModules != 0) {
1830 nModules = (struct sound_trigger_module_descriptor*) calloc(
1831 numModules, sizeof(struct sound_trigger_module_descriptor));
1832 if (nModules == NULL) {
1833 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1834 // ram the next time this function is called.
1835 ALOGE("Failed to allocate buffer for module descriptors");
1836 return false;
1837 }
1838
1839 status = SoundTrigger::listModules(nModules, &numModules);
1840 if (status == NO_ERROR) {
1841 soundTriggerSupportsConcurrentCapture = true;
1842 for (size_t i = 0; i < numModules; ++i) {
1843 soundTriggerSupportsConcurrentCapture &=
1844 nModules[i].properties.concurrent_capture;
1845 }
1846 }
1847 free(nModules);
1848 }
1849 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1850 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1851 }
1852 return mSoundTriggerSupportsConcurrentCapture;
1853}
1854
Eric Laurentfb66dd92016-01-28 18:32:03 -08001855
Eric Laurent4dc68062014-07-28 17:26:49 -07001856status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001857 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001858 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001859 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001860{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001861
1862 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1863 input, session, silenced, *concurrency);
1864
Eric Laurentfb66dd92016-01-28 18:32:03 -08001865 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001866
Eric Laurente552edb2014-03-10 17:42:56 -07001867 ssize_t index = mInputs.indexOfKey(input);
1868 if (index < 0) {
1869 ALOGW("startInput() unknown input %d", input);
1870 return BAD_VALUE;
1871 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001872 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001873
Eric Laurent599c7582015-12-07 18:05:55 -08001874 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1875 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001876 ALOGW("startInput() unknown session %d on input %d", session, input);
1877 return BAD_VALUE;
1878 }
1879
Eric Laurent74708e72017-04-07 17:13:42 -07001880// FIXME: disable concurrent capture until UI is ready
1881#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001882 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1883 ALOGW("startInput(%d) failed: other input already started", input);
1884 return INVALID_OPERATION;
1885 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001886
Eric Laurentfb66dd92016-01-28 18:32:03 -08001887 if (isInCall()) {
1888 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1889 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001890 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001891 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001892 }
Eric Laurent74708e72017-04-07 17:13:42 -07001893#else
1894 if (!is_virtual_input_device(inputDesc->mDevice)) {
1895 if (mCallTxPatch != 0 &&
1896 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1897 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001898 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001899 return INVALID_OPERATION;
1900 }
1901
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001902 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001903
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001904 // If a UID is idle and records silence and another not silenced recording starts
1905 // from another UID (idle or active) we stop the current idle UID recording in
1906 // favor of the new one - "There can be only one" TM
1907 if (!silenced) {
1908 for (const auto& activeDesc : activeInputs) {
1909 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1910 activeDesc->getId() == inputDesc->getId()) {
1911 continue;
1912 }
1913
1914 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1915 true /*activeOnly*/);
1916 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1917 if (activeSession->isSilenced()) {
1918 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1919 audio_session_t activeSessionId = activeSession->session();
1920 stopInput(activeInput, activeSessionId);
1921 releaseInput(activeInput, activeSessionId);
1922 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1923 activeInputs = mInputs.getActiveInputs();
1924 }
1925 }
1926 }
1927
1928 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001929 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1930 activeDesc->getId() == inputDesc->getId()) {
1931 continue;
1932 }
1933
Eric Laurent74708e72017-04-07 17:13:42 -07001934 audio_source_t activeSource = activeDesc->inputSource(true);
1935 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1936 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1937 if (activeDesc->hasPreemptedSession(session)) {
1938 ALOGW("startInput(%d) failed for HOTWORD: "
1939 "other input %d already started for HOTWORD",
1940 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001941 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001942 return INVALID_OPERATION;
1943 }
1944 } else {
1945 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1946 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001947 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001948 return INVALID_OPERATION;
1949 }
1950 } else {
1951 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1952 ALOGW("startInput(%d) failed: other input %d already started",
1953 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001954 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001955 return INVALID_OPERATION;
1956 }
1957 }
1958 }
1959
Chris Thornton2b864642017-06-27 21:26:07 -07001960 // We only need to check if the sound trigger session supports concurrent capture if the
1961 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1962 // that's running.
1963 const bool allowConcurrentWithSoundTrigger =
1964 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1965
Eric Laurent74708e72017-04-07 17:13:42 -07001966 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001967 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001968 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1969 continue;
1970 }
1971
Eric Laurent74708e72017-04-07 17:13:42 -07001972 audio_source_t activeSource = activeDesc->inputSource(true);
1973 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1974 AudioSessionCollection activeSessions =
1975 activeDesc->getAudioSessions(true /*activeOnly*/);
1976 audio_session_t activeSession = activeSessions.keyAt(0);
1977 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1978 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001979 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001980 sessions.add(activeSession);
1981 inputDesc->setPreemptedSessions(sessions);
1982 stopInput(activeHandle, activeSession);
1983 releaseInput(activeHandle, activeSession);
1984 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1985 input, activeDesc->mIoHandle);
1986 }
1987 }
1988 }
1989#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001990
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001991 // Make sure we start with the correct silence state
1992 audioSession->setSilenced(silenced);
1993
Eric Laurent313d1e72016-01-29 09:56:57 -08001994 // increment activity count before calling getNewInputDevice() below as only active sessions
1995 // are considered for device selection
1996 audioSession->changeActiveCount(1);
1997
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001998 // Routing?
1999 mInputRoutes.incRouteActivity(session);
2000
Eric Laurent2157f5b2018-04-25 18:33:02 -07002001 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002002 // indicate active capture to sound trigger service if starting capture from a mic on
2003 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002004 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002005 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurent733ce942017-12-07 12:18:25 -08002007 status_t status = inputDesc->start();
2008 if (status != NO_ERROR) {
2009 mInputRoutes.decRouteActivity(session);
2010 audioSession->changeActiveCount(-1);
2011 return status;
2012 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002013
Eric Laurent733ce942017-12-07 12:18:25 -08002014 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002015 // if input maps to a dynamic policy with an activity listener, notify of state change
2016 if ((inputDesc->mPolicyMix != NULL)
2017 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2018 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2019 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002020 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002021
Eric Laurentf7c50102016-09-30 15:19:43 -07002022 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2023 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002024 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002025 SoundTrigger::setCaptureState(true);
2026 }
2027
2028 // automatically enable the remote submix output when input is started if not
2029 // used by a policy mix of type MIX_TYPE_RECORDERS
2030 // For remote submix (a virtual device), we open only one input per capture request.
2031 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2032 String8 address = String8("");
2033 if (inputDesc->mPolicyMix == NULL) {
2034 address = String8("0");
2035 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2036 address = inputDesc->mPolicyMix->mDeviceAddress;
2037 }
2038 if (address != "") {
2039 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2040 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2041 address, "remote-submix");
2042 }
Eric Laurentc722f302014-12-10 11:21:49 -08002043 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002044 }
Eric Laurente552edb2014-03-10 17:42:56 -07002045 }
2046
Eric Laurent599c7582015-12-07 18:05:55 -08002047 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002048
Eric Laurente552edb2014-03-10 17:42:56 -07002049 return NO_ERROR;
2050}
2051
Eric Laurent4dc68062014-07-28 17:26:49 -07002052status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2053 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002054{
2055 ALOGV("stopInput() input %d", input);
2056 ssize_t index = mInputs.indexOfKey(input);
2057 if (index < 0) {
2058 ALOGW("stopInput() unknown input %d", input);
2059 return BAD_VALUE;
2060 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002061 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002062
Eric Laurent599c7582015-12-07 18:05:55 -08002063 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002064 if (index < 0) {
2065 ALOGW("stopInput() unknown session %d on input %d", session, input);
2066 return BAD_VALUE;
2067 }
2068
Eric Laurent599c7582015-12-07 18:05:55 -08002069 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002070 ALOGW("stopInput() input %d already stopped", input);
2071 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002072 }
2073
Eric Laurent599c7582015-12-07 18:05:55 -08002074 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002075
2076 // Routing?
2077 mInputRoutes.decRouteActivity(session);
2078
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002079 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002080 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002081 if (inputDesc->isActive()) {
2082 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2083 } else {
2084 // if input maps to a dynamic policy with an activity listener, notify of state change
2085 if ((inputDesc->mPolicyMix != NULL)
2086 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2087 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2088 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002089 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002090
2091 // automatically disable the remote submix output when input is stopped if not
2092 // used by a policy mix of type MIX_TYPE_RECORDERS
2093 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2094 String8 address = String8("");
2095 if (inputDesc->mPolicyMix == NULL) {
2096 address = String8("0");
2097 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2098 address = inputDesc->mPolicyMix->mDeviceAddress;
2099 }
2100 if (address != "") {
2101 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2102 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2103 address, "remote-submix");
2104 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002105 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002106
Eric Laurentf7c50102016-09-30 15:19:43 -07002107 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002108 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002109
Eric Laurentf7c50102016-09-30 15:19:43 -07002110 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2111 // primary HW module
2112 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2113 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2114 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002115 SoundTrigger::setCaptureState(false);
2116 }
2117 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002118 }
Eric Laurente552edb2014-03-10 17:42:56 -07002119 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002120 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002121}
2122
Eric Laurent4dc68062014-07-28 17:26:49 -07002123void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2124 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002125{
2126 ALOGV("releaseInput() %d", input);
2127 ssize_t index = mInputs.indexOfKey(input);
2128 if (index < 0) {
2129 ALOGW("releaseInput() releasing unknown input %d", input);
2130 return;
2131 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002132
2133 // Routing
2134 mInputRoutes.removeRoute(session);
2135
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002136 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2137 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002138
Eric Laurent599c7582015-12-07 18:05:55 -08002139 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002140 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002141 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2142 return;
2143 }
Eric Laurent599c7582015-12-07 18:05:55 -08002144
2145 if (audioSession->openCount() == 0) {
2146 ALOGW("releaseInput() invalid open count %d on session %d",
2147 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 return;
2149 }
Eric Laurent599c7582015-12-07 18:05:55 -08002150
2151 if (audioSession->changeOpenCount(-1) == 0) {
2152 inputDesc->removeAudioSession(session);
2153 }
2154
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002155 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002156 ALOGV("releaseInput() exit > 0");
2157 return;
2158 }
2159
Eric Laurent05b90f82014-08-27 15:32:29 -07002160 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002161 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002162 ALOGV("releaseInput() exit");
2163}
2164
Eric Laurentd4692962014-05-05 18:13:44 -07002165void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002166 bool patchRemoved = false;
2167
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002168 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002169 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002170 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002171 if (patch_index >= 0) {
2172 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002173 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 mAudioPatches.removeItemsAt(patch_index);
2175 patchRemoved = true;
2176 }
Eric Laurentfe231122017-11-17 17:48:06 -08002177 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002178 }
jiabin829a00b2018-04-04 16:28:32 -07002179 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002180 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002181 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002182 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002183
2184 if (patchRemoved) {
2185 mpClientInterface->onAudioPatchListUpdate();
2186 }
Eric Laurentd4692962014-05-05 18:13:44 -07002187}
2188
Eric Laurente0720872014-03-11 09:30:41 -07002189void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002190 int indexMin,
2191 int indexMax)
2192{
2193 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002194 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002195
2196 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002197 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2198 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002199 continue;
2200 }
2201 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002202 }
Eric Laurente552edb2014-03-10 17:42:56 -07002203}
2204
Eric Laurente0720872014-03-11 09:30:41 -07002205status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002206 int index,
2207 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002208{
2209
Nadav Bar7c605f62017-12-25 00:01:52 +02002210 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2211 // app that has MODIFY_PHONE_STATE permission.
2212 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2213 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002214 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002215 return BAD_VALUE;
2216 }
2217 if (!audio_is_output_device(device)) {
2218 return BAD_VALUE;
2219 }
2220
2221 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002222 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002223
Eric Laurent1fd372e2016-04-06 14:23:53 -07002224 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002225 stream, device, index);
2226
Eric Laurent28d09f02016-03-08 10:43:05 -08002227 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002228 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2229 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002230 continue;
2231 }
2232 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2233 }
Eric Laurente552edb2014-03-10 17:42:56 -07002234
Eric Laurent1fd372e2016-04-06 14:23:53 -07002235 // update volume on all outputs and streams matching the following:
2236 // - The requested stream (or a stream matching for volume control) is active on the output
2237 // - The device (or devices) selected by the strategy corresponding to this stream includes
2238 // the requested device
2239 // - For non default requested device, currently selected device on the output is either the
2240 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002241 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2242 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002243 status_t status = NO_ERROR;
2244 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002245 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2246 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002247 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002248 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002249 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002250 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002251 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002252 continue;
2253 }
Eric Laurent794fde22016-03-11 09:50:45 -08002254 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002255 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2256 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002257 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2258 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002259 continue;
2260 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002261 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002262 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002263 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002264 applyVolume = (curDevice & curStreamDevice) != 0;
2265 } else {
2266 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002267 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002268 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002269
Eric Laurente76f29c2016-09-14 17:17:53 -07002270 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002271 //FIXME: workaround for truncated touch sounds
2272 // delayed volume change for system stream to be removed when the problem is
2273 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002274 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002275 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2276 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002277 if (volStatus != NO_ERROR) {
2278 status = volStatus;
2279 }
2280 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282 }
2283 return status;
2284}
2285
Eric Laurente0720872014-03-11 09:30:41 -07002286status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002287 int *index,
2288 audio_devices_t device)
2289{
2290 if (index == NULL) {
2291 return BAD_VALUE;
2292 }
2293 if (!audio_is_output_device(device)) {
2294 return BAD_VALUE;
2295 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002296 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002297 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002298 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002299 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2300 }
François Gaffiedfd74092015-03-19 12:10:59 +01002301 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002302
François Gaffied1ab2bd2015-12-02 18:20:06 +01002303 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002304 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2305 return NO_ERROR;
2306}
2307
Eric Laurent36829f92017-04-07 19:04:42 -07002308audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002309{
2310 // select one output among several suitable for global effects.
2311 // The priority is as follows:
2312 // 1: An offloaded output. If the effect ends up not being offloadable,
2313 // AudioFlinger will invalidate the track and the offloaded output
2314 // will be closed causing the effect to be moved to a PCM output.
2315 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002316 // 3: The primary output
2317 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002318
Eric Laurent3b73df72014-03-11 09:06:29 -07002319 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002320 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002321 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002322
Eric Laurent36829f92017-04-07 19:04:42 -07002323 if (outputs.size() == 0) {
2324 return AUDIO_IO_HANDLE_NONE;
2325 }
Eric Laurente552edb2014-03-10 17:42:56 -07002326
Eric Laurent36829f92017-04-07 19:04:42 -07002327 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2328 bool activeOnly = true;
2329
2330 while (output == AUDIO_IO_HANDLE_NONE) {
2331 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2332 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2333 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2334
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002335 for (audio_io_handle_t output : outputs) {
2336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002337 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2338 continue;
2339 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002340 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2341 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002342 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002343 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002344 }
2345 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002346 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002347 }
2348 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002349 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002350 }
2351 }
2352 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2353 output = outputOffloaded;
2354 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2355 output = outputDeepBuffer;
2356 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2357 output = outputPrimary;
2358 } else {
2359 output = outputs[0];
2360 }
2361 activeOnly = false;
2362 }
2363
2364 if (output != mMusicEffectOutput) {
2365 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2366 mMusicEffectOutput = output;
2367 }
2368
2369 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002370 return output;
2371}
2372
Eric Laurent36829f92017-04-07 19:04:42 -07002373audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2374{
2375 return selectOutputForMusicEffects();
2376}
2377
Eric Laurente0720872014-03-11 09:30:41 -07002378status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002379 audio_io_handle_t io,
2380 uint32_t strategy,
2381 int session,
2382 int id)
2383{
2384 ssize_t index = mOutputs.indexOfKey(io);
2385 if (index < 0) {
2386 index = mInputs.indexOfKey(io);
2387 if (index < 0) {
2388 ALOGW("registerEffect() unknown io %d", io);
2389 return INVALID_OPERATION;
2390 }
2391 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002392 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002393}
2394
Eric Laurentc75307b2015-03-17 15:29:32 -07002395bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2396{
Eric Laurent28d09f02016-03-08 10:43:05 -08002397 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002398 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2399 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002400 continue;
2401 }
2402 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2403 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002404 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002405}
2406
2407bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2408{
2409 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2410}
2411
Eric Laurente0720872014-03-11 09:30:41 -07002412bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002413{
2414 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002415 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002416 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002417 return true;
2418 }
2419 }
2420 return false;
2421}
2422
Eric Laurent275e8e92014-11-30 15:14:47 -08002423// Register a list of custom mixes with their attributes and format.
2424// When a mix is registered, corresponding input and output profiles are
2425// added to the remote submix hw module. The profile contains only the
2426// parameters (sampling rate, format...) specified by the mix.
2427// The corresponding input remote submix device is also connected.
2428//
2429// When a remote submix device is connected, the address is checked to select the
2430// appropriate profile and the corresponding input or output stream is opened.
2431//
2432// When capture starts, getInputForAttr() will:
2433// - 1 look for a mix matching the address passed in attribtutes tags if any
2434// - 2 if none found, getDeviceForInputSource() will:
2435// - 2.1 look for a mix matching the attributes source
2436// - 2.2 if none found, default to device selection by policy rules
2437// At this time, the corresponding output remote submix device is also connected
2438// and active playback use cases can be transferred to this mix if needed when reconnecting
2439// after AudioTracks are invalidated
2440//
2441// When playback starts, getOutputForAttr() will:
2442// - 1 look for a mix matching the address passed in attribtutes tags if any
2443// - 2 if none found, look for a mix matching the attributes usage
2444// - 3 if none found, default to device and output selection by policy rules.
2445
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002446status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002447{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002448 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2449 status_t res = NO_ERROR;
2450
2451 sp<HwModule> rSubmixModule;
2452 // examine each mix's route type
2453 for (size_t i = 0; i < mixes.size(); i++) {
2454 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2455 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2456 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002457 break;
2458 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002459 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002460 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002461 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002462 rSubmixModule = mHwModules.getModuleFromName(
2463 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2464 if (rSubmixModule == 0) {
2465 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2466 i);
2467 res = INVALID_OPERATION;
2468 break;
2469 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002470 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002471
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002472 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002473
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002475 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 res = INVALID_OPERATION;
2477 break;
2478 }
2479 audio_config_t outputConfig = mixes[i].mFormat;
2480 audio_config_t inputConfig = mixes[i].mFormat;
2481 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2482 // stereo and let audio flinger do the channel conversion if needed.
2483 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2484 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2485 rSubmixModule->addOutputProfile(address, &outputConfig,
2486 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2487 rSubmixModule->addInputProfile(address, &inputConfig,
2488 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002489
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2491 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2492 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2493 address.string(), "remote-submix");
2494 } else {
2495 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2496 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2497 address.string(), "remote-submix");
2498 }
2499 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002500 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002502 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2503 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002504
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002505 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2507 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2508 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2509 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2510 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2511 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002512 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2513 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002514 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2515 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002516 } else {
2517 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002518 }
2519 break;
2520 }
2521 }
2522
2523 if (res != NO_ERROR) {
2524 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002525 i, device, address.string());
2526 res = INVALID_OPERATION;
2527 break;
2528 } else if (!foundOutput) {
2529 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2530 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002531 res = INVALID_OPERATION;
2532 break;
2533 }
Eric Laurentc722f302014-12-10 11:21:49 -08002534 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002535 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536 if (res != NO_ERROR) {
2537 unregisterPolicyMixes(mixes);
2538 }
2539 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002540}
2541
2542status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2543{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002544 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002545 status_t res = NO_ERROR;
2546 sp<HwModule> rSubmixModule;
2547 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002548 for (const auto& mix : mixes) {
2549 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002550
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002552 rSubmixModule = mHwModules.getModuleFromName(
2553 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2554 if (rSubmixModule == 0) {
2555 res = INVALID_OPERATION;
2556 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002557 }
2558 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002559
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002560 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002561
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002562 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2563 res = INVALID_OPERATION;
2564 continue;
2565 }
2566
2567 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2568 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2569 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2570 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2571 address.string(), "remote-submix");
2572 }
2573 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2575 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2576 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2577 address.string(), "remote-submix");
2578 }
2579 rSubmixModule->removeOutputProfile(address);
2580 rSubmixModule->removeInputProfile(address);
2581
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002582 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2583 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002584 res = INVALID_OPERATION;
2585 continue;
2586 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002587 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002588 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002590}
2591
Eric Laurente552edb2014-03-10 17:42:56 -07002592
Eric Laurente0720872014-03-11 09:30:41 -07002593status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002594{
Eric Laurente552edb2014-03-10 17:42:56 -07002595 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002596 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2597 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002598 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002599 std::string stateLiteral;
2600 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002601 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2602 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2603 "communications", "media", "record", "dock", "system",
2604 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2605 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2606 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2607 result.appendFormat(" Force use for %s: %d\n",
2608 forceUses[i], mEngine->getForceUse(i));
2609 }
2610 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2611 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2612 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002613 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002614
François Gaffie112b0af2015-11-19 16:13:25 +01002615 mAvailableOutputDevices.dump(fd, String8("Available output"));
2616 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002617 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002618 mOutputs.dump(fd);
2619 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002620 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002621 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002622 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002623 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002624
2625 return NO_ERROR;
2626}
2627
2628// This function checks for the parameters which can be offloaded.
2629// This can be enhanced depending on the capability of the DSP and policy
2630// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002631bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002632{
2633 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002634 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002635 offloadInfo.sample_rate, offloadInfo.channel_mask,
2636 offloadInfo.format,
2637 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2638 offloadInfo.has_video);
2639
Andy Hung2ddee192015-12-18 17:34:44 -08002640 if (mMasterMono) {
2641 return false; // no offloading if mono is set.
2642 }
2643
Eric Laurente552edb2014-03-10 17:42:56 -07002644 // Check if offload has been disabled
2645 char propValue[PROPERTY_VALUE_MAX];
2646 if (property_get("audio.offload.disable", propValue, "0")) {
2647 if (atoi(propValue) != 0) {
2648 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2649 return false;
2650 }
2651 }
2652
2653 // Check if stream type is music, then only allow offload as of now.
2654 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2655 {
2656 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2657 return false;
2658 }
2659
2660 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002661 const bool allowOffloadWithVideo =
2662 property_get_bool("audio.offload.video", false /* default_value */);
2663 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002664 ALOGV("isOffloadSupported: has_video == true, returning false");
2665 return false;
2666 }
2667
2668 //If duration is less than minimum value defined in property, return false
2669 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2670 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2671 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2672 return false;
2673 }
2674 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2675 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2676 return false;
2677 }
2678
2679 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2680 // creating an offloaded track and tearing it down immediately after start when audioflinger
2681 // detects there is an active non offloadable effect.
2682 // FIXME: We should check the audio session here but we do not have it in this context.
2683 // This may prevent offloading in rare situations where effects are left active by apps
2684 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002685 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002686 return false;
2687 }
2688
2689 // See if there is a profile to support this.
2690 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002691 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002692 offloadInfo.sample_rate,
2693 offloadInfo.format,
2694 offloadInfo.channel_mask,
2695 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002696 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2697 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002698}
2699
Eric Laurent6a94d692014-05-20 11:18:06 -07002700status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2701 audio_port_type_t type,
2702 unsigned int *num_ports,
2703 struct audio_port *ports,
2704 unsigned int *generation)
2705{
2706 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2707 generation == NULL) {
2708 return BAD_VALUE;
2709 }
2710 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2711 if (ports == NULL) {
2712 *num_ports = 0;
2713 }
2714
2715 size_t portsWritten = 0;
2716 size_t portsMax = *num_ports;
2717 *num_ports = 0;
2718 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002719 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2720 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002721 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002722 for (const auto& dev : mAvailableOutputDevices) {
2723 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002724 continue;
2725 }
2726 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002727 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002728 }
2729 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002730 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 }
2732 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002733 for (const auto& dev : mAvailableInputDevices) {
2734 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002735 continue;
2736 }
2737 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002738 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002739 }
2740 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002742 }
2743 }
2744 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2745 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2746 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2747 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2748 }
2749 *num_ports += mInputs.size();
2750 }
2751 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002752 size_t numOutputs = 0;
2753 for (size_t i = 0; i < mOutputs.size(); i++) {
2754 if (!mOutputs[i]->isDuplicated()) {
2755 numOutputs++;
2756 if (portsWritten < portsMax) {
2757 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2758 }
2759 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002760 }
Eric Laurent84c70242014-06-23 08:46:27 -07002761 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002762 }
2763 }
2764 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002765 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002766 return NO_ERROR;
2767}
2768
Eric Laurent99fcae42018-05-17 16:59:18 -07002769status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002770{
Eric Laurent99fcae42018-05-17 16:59:18 -07002771 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2772 return BAD_VALUE;
2773 }
2774 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2775 if (dev != 0) {
2776 dev->toAudioPort(port);
2777 return NO_ERROR;
2778 }
2779 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2780 if (dev != 0) {
2781 dev->toAudioPort(port);
2782 return NO_ERROR;
2783 }
2784 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2785 if (out != 0) {
2786 out->toAudioPort(port);
2787 return NO_ERROR;
2788 }
2789 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2790 if (in != 0) {
2791 in->toAudioPort(port);
2792 return NO_ERROR;
2793 }
2794 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002795}
2796
Eric Laurent6a94d692014-05-20 11:18:06 -07002797status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2798 audio_patch_handle_t *handle,
2799 uid_t uid)
2800{
2801 ALOGV("createAudioPatch()");
2802
2803 if (handle == NULL || patch == NULL) {
2804 return BAD_VALUE;
2805 }
2806 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2807
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002808 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002809 return BAD_VALUE;
2810 }
2811 // only one source per audio patch supported for now
2812 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 return INVALID_OPERATION;
2814 }
Eric Laurent874c42872014-08-08 15:13:39 -07002815
2816 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 return INVALID_OPERATION;
2818 }
Eric Laurent874c42872014-08-08 15:13:39 -07002819 for (size_t i = 0; i < patch->num_sinks; i++) {
2820 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2821 return INVALID_OPERATION;
2822 }
2823 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002824
2825 sp<AudioPatch> patchDesc;
2826 ssize_t index = mAudioPatches.indexOfKey(*handle);
2827
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2829 patch->sources[0].role,
2830 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002831#if LOG_NDEBUG == 0
2832 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002833 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002834 patch->sinks[i].role,
2835 patch->sinks[i].type);
2836 }
2837#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002838
2839 if (index >= 0) {
2840 patchDesc = mAudioPatches.valueAt(index);
2841 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2842 mUidCached, patchDesc->mUid, uid);
2843 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2844 return INVALID_OPERATION;
2845 }
2846 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002847 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 }
2849
2850 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002851 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 if (outputDesc == NULL) {
2853 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2854 return BAD_VALUE;
2855 }
Eric Laurent84c70242014-06-23 08:46:27 -07002856 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2857 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 if (patchDesc != 0) {
2859 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2860 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2861 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2862 return BAD_VALUE;
2863 }
2864 }
Eric Laurent874c42872014-08-08 15:13:39 -07002865 DeviceVector devices;
2866 for (size_t i = 0; i < patch->num_sinks; i++) {
2867 // Only support mix to devices connection
2868 // TODO add support for mix to mix connection
2869 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2870 ALOGV("createAudioPatch() source mix but sink is not a device");
2871 return INVALID_OPERATION;
2872 }
2873 sp<DeviceDescriptor> devDesc =
2874 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2875 if (devDesc == 0) {
2876 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2877 return BAD_VALUE;
2878 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002879
François Gaffie53615e22015-03-19 09:24:12 +01002880 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002881 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002882 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002883 NULL, // updatedSamplingRate
2884 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002885 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002886 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002887 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002888 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002889 ALOGV("createAudioPatch() profile not supported for device %08x",
2890 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002891 return INVALID_OPERATION;
2892 }
2893 devices.add(devDesc);
2894 }
2895 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 return INVALID_OPERATION;
2897 }
Eric Laurent874c42872014-08-08 15:13:39 -07002898
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 // TODO: reconfigure output format and channels here
2900 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002901 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002902 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 index = mAudioPatches.indexOfKey(*handle);
2904 if (index >= 0) {
2905 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2906 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2907 }
2908 patchDesc = mAudioPatches.valueAt(index);
2909 patchDesc->mUid = uid;
2910 ALOGV("createAudioPatch() success");
2911 } else {
2912 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2913 return INVALID_OPERATION;
2914 }
2915 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2916 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2917 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002918 // only one sink supported when connecting an input device to a mix
2919 if (patch->num_sinks > 1) {
2920 return INVALID_OPERATION;
2921 }
François Gaffie53615e22015-03-19 09:24:12 +01002922 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 if (inputDesc == NULL) {
2924 return BAD_VALUE;
2925 }
2926 if (patchDesc != 0) {
2927 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2928 return BAD_VALUE;
2929 }
2930 }
2931 sp<DeviceDescriptor> devDesc =
2932 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2933 if (devDesc == 0) {
2934 return BAD_VALUE;
2935 }
2936
François Gaffie53615e22015-03-19 09:24:12 +01002937 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002938 devDesc->mAddress,
2939 patch->sinks[0].sample_rate,
2940 NULL, /*updatedSampleRate*/
2941 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002942 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002943 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002944 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002945 // FIXME for the parameter type,
2946 // and the NONE
2947 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002948 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 return INVALID_OPERATION;
2950 }
2951 // TODO: reconfigure output format and channels here
2952 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002953 devDesc->type(), inputDesc->mIoHandle);
2954 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 index = mAudioPatches.indexOfKey(*handle);
2956 if (index >= 0) {
2957 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2958 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2959 }
2960 patchDesc = mAudioPatches.valueAt(index);
2961 patchDesc->mUid = uid;
2962 ALOGV("createAudioPatch() success");
2963 } else {
2964 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2965 return INVALID_OPERATION;
2966 }
2967 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2968 // device to device connection
2969 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002970 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 return BAD_VALUE;
2972 }
2973 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 sp<DeviceDescriptor> srcDeviceDesc =
2975 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002976 if (srcDeviceDesc == 0) {
2977 return BAD_VALUE;
2978 }
Eric Laurent874c42872014-08-08 15:13:39 -07002979
Eric Laurent6a94d692014-05-20 11:18:06 -07002980 //update source and sink with our own data as the data passed in the patch may
2981 // be incomplete.
2982 struct audio_patch newPatch = *patch;
2983 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002984
Eric Laurent874c42872014-08-08 15:13:39 -07002985 for (size_t i = 0; i < patch->num_sinks; i++) {
2986 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2987 ALOGV("createAudioPatch() source device but one sink is not a device");
2988 return INVALID_OPERATION;
2989 }
2990
2991 sp<DeviceDescriptor> sinkDeviceDesc =
2992 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2993 if (sinkDeviceDesc == 0) {
2994 return BAD_VALUE;
2995 }
2996 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2997
Eric Laurent3bcf8592015-04-03 12:13:24 -07002998 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002999 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003000 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003001 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003002 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003003 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003004 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003005 return INVALID_OPERATION;
3006 }
Eric Laurent874c42872014-08-08 15:13:39 -07003007 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003008 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003009 // if the sink device is reachable via an opened output stream, request to go via
3010 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003011 audio_io_handle_t output = selectOutput(outputs,
3012 AUDIO_OUTPUT_FLAG_NONE,
3013 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003014 if (output != AUDIO_IO_HANDLE_NONE) {
3015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3016 if (outputDesc->isDuplicated()) {
3017 return INVALID_OPERATION;
3018 }
3019 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003020 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003021 newPatch.num_sources = 2;
3022 }
Eric Laurent83b88082014-06-20 18:31:16 -07003023 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003024 }
3025 // TODO: check from routing capabilities in config file and other conflicting patches
3026
Mikhail Naganovdc769682018-05-04 15:34:08 -07003027 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3028 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3030 status);
3031 return INVALID_OPERATION;
3032 }
3033 } else {
3034 return BAD_VALUE;
3035 }
3036 } else {
3037 return BAD_VALUE;
3038 }
3039 return NO_ERROR;
3040}
3041
3042status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3043 uid_t uid)
3044{
3045 ALOGV("releaseAudioPatch() patch %d", handle);
3046
3047 ssize_t index = mAudioPatches.indexOfKey(handle);
3048
3049 if (index < 0) {
3050 return BAD_VALUE;
3051 }
3052 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3053 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3054 mUidCached, patchDesc->mUid, uid);
3055 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3056 return INVALID_OPERATION;
3057 }
3058
3059 struct audio_patch *patch = &patchDesc->mPatch;
3060 patchDesc->mUid = mUidCached;
3061 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003063 if (outputDesc == NULL) {
3064 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3065 return BAD_VALUE;
3066 }
3067
Eric Laurentc75307b2015-03-17 15:29:32 -07003068 setOutputDevice(outputDesc,
3069 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003070 true,
3071 0,
3072 NULL);
3073 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3074 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003075 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003076 if (inputDesc == NULL) {
3077 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3078 return BAD_VALUE;
3079 }
3080 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003081 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003082 true,
3083 NULL);
3084 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3086 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3087 status, patchDesc->mAfPatchHandle);
3088 removeAudioPatch(patchDesc->mHandle);
3089 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003090 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 } else {
3092 return BAD_VALUE;
3093 }
3094 } else {
3095 return BAD_VALUE;
3096 }
3097 return NO_ERROR;
3098}
3099
3100status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3101 struct audio_patch *patches,
3102 unsigned int *generation)
3103{
François Gaffie53615e22015-03-19 09:24:12 +01003104 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003105 return BAD_VALUE;
3106 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003108 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003109}
3110
Eric Laurente1715a42014-05-20 11:30:42 -07003111status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003112{
Eric Laurente1715a42014-05-20 11:30:42 -07003113 ALOGV("setAudioPortConfig()");
3114
3115 if (config == NULL) {
3116 return BAD_VALUE;
3117 }
3118 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3119 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003120 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3121 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003122 }
3123
Eric Laurenta121f902014-06-03 13:32:54 -07003124 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003125 if (config->type == AUDIO_PORT_TYPE_MIX) {
3126 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003127 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003128 if (outputDesc == NULL) {
3129 return BAD_VALUE;
3130 }
Eric Laurent84c70242014-06-23 08:46:27 -07003131 ALOG_ASSERT(!outputDesc->isDuplicated(),
3132 "setAudioPortConfig() called on duplicated output %d",
3133 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003134 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003135 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003136 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003137 if (inputDesc == NULL) {
3138 return BAD_VALUE;
3139 }
Eric Laurenta121f902014-06-03 13:32:54 -07003140 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003141 } else {
3142 return BAD_VALUE;
3143 }
3144 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3145 sp<DeviceDescriptor> deviceDesc;
3146 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3147 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3148 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3149 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3150 } else {
3151 return BAD_VALUE;
3152 }
3153 if (deviceDesc == NULL) {
3154 return BAD_VALUE;
3155 }
Eric Laurenta121f902014-06-03 13:32:54 -07003156 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003157 } else {
3158 return BAD_VALUE;
3159 }
3160
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003161 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003162 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3163 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003164 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003165 audioPortConfig->toAudioPortConfig(&newConfig, config);
3166 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003167 }
Eric Laurenta121f902014-06-03 13:32:54 -07003168 if (status != NO_ERROR) {
3169 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003170 }
Eric Laurente1715a42014-05-20 11:30:42 -07003171
3172 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003173}
3174
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003175void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3176{
Eric Laurentd60560a2015-04-10 11:31:20 -07003177 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003178 clearAudioPatches(uid);
3179 clearSessionRoutes(uid);
3180}
3181
Eric Laurent6a94d692014-05-20 11:18:06 -07003182void AudioPolicyManager::clearAudioPatches(uid_t uid)
3183{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003184 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3186 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003187 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003188 }
3189 }
3190}
3191
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003192void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3193 audio_io_handle_t ouptutToSkip)
3194{
3195 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3196 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3197 for (size_t j = 0; j < mOutputs.size(); j++) {
3198 if (mOutputs.keyAt(j) == ouptutToSkip) {
3199 continue;
3200 }
3201 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3202 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3203 continue;
3204 }
3205 // If the default device for this strategy is on another output mix,
3206 // invalidate all tracks in this strategy to force re connection.
3207 // Otherwise select new device on the output mix.
3208 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003209 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003210 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3211 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3212 }
3213 }
3214 } else {
3215 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3216 setOutputDevice(outputDesc, newDevice, false);
3217 }
3218 }
3219}
3220
3221void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3222{
3223 // remove output routes associated with this uid
3224 SortedVector<routing_strategy> affectedStrategies;
3225 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3226 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3227 if (route->mUid == uid) {
3228 mOutputRoutes.removeItemsAt(i);
3229 if (route->mDeviceDescriptor != 0) {
3230 affectedStrategies.add(getStrategy(route->mStreamType));
3231 }
3232 }
3233 }
3234 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003235 for (const auto& strategy : affectedStrategies) {
3236 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003237 }
3238
3239 // remove input routes associated with this uid
3240 SortedVector<audio_source_t> affectedSources;
3241 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3242 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3243 if (route->mUid == uid) {
3244 mInputRoutes.removeItemsAt(i);
3245 if (route->mDeviceDescriptor != 0) {
3246 affectedSources.add(route->mSource);
3247 }
3248 }
3249 }
3250 // reroute inputs if necessary
3251 SortedVector<audio_io_handle_t> inputsToClose;
3252 for (size_t i = 0; i < mInputs.size(); i++) {
3253 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003254 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003255 inputsToClose.add(inputDesc->mIoHandle);
3256 }
3257 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003258 for (const auto& input : inputsToClose) {
3259 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003260 }
3261}
3262
Eric Laurentd60560a2015-04-10 11:31:20 -07003263void AudioPolicyManager::clearAudioSources(uid_t uid)
3264{
3265 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3266 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3267 if (sourceDesc->mUid == uid) {
3268 stopAudioSource(mAudioSources.keyAt(i));
3269 }
3270 }
3271}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003272
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003273status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3274 audio_io_handle_t *ioHandle,
3275 audio_devices_t *device)
3276{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003277 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3278 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003279 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003280
François Gaffiedf372692015-03-19 10:43:27 +01003281 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003282}
3283
Eric Laurentd60560a2015-04-10 11:31:20 -07003284status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3285 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003286 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003287 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003288{
Eric Laurentd60560a2015-04-10 11:31:20 -07003289 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3290 if (source == NULL || attributes == NULL || handle == NULL) {
3291 return BAD_VALUE;
3292 }
3293
Glenn Kasten559d4392016-03-29 13:42:57 -07003294 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003295
3296 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3297 source->type != AUDIO_PORT_TYPE_DEVICE) {
3298 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3299 return INVALID_OPERATION;
3300 }
3301
3302 sp<DeviceDescriptor> srcDeviceDesc =
3303 mAvailableInputDevices.getDevice(source->ext.device.type,
3304 String8(source->ext.device.address));
3305 if (srcDeviceDesc == 0) {
3306 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3307 return BAD_VALUE;
3308 }
3309 sp<AudioSourceDescriptor> sourceDesc =
3310 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3311
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003312 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003313 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3314 sourceDesc->mPatchDesc = patchDesc;
3315
3316 status_t status = connectAudioSource(sourceDesc);
3317 if (status == NO_ERROR) {
3318 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3319 *handle = sourceDesc->getHandle();
3320 }
3321 return status;
3322}
3323
3324status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3325{
3326 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3327
3328 // make sure we only have one patch per source.
3329 disconnectAudioSource(sourceDesc);
3330
3331 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003332 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003333 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3334
3335 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3336 sp<DeviceDescriptor> sinkDeviceDesc =
3337 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3338
3339 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003340
3341 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3342 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003343 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003344 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3345 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3346 // create patch between src device and output device
3347 // create Hwoutput and add to mHwOutputs
3348 } else {
3349 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3350 audio_io_handle_t output =
3351 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3352 if (output == AUDIO_IO_HANDLE_NONE) {
3353 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3354 return INVALID_OPERATION;
3355 }
3356 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3357 if (outputDesc->isDuplicated()) {
3358 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3359 return INVALID_OPERATION;
3360 }
Eric Laurent733ce942017-12-07 12:18:25 -08003361 status_t status = outputDesc->start();
3362 if (status != NO_ERROR) {
3363 return status;
3364 }
3365
Eric Laurentd60560a2015-04-10 11:31:20 -07003366 // create a special patch with no sink and two sources:
3367 // - the second source indicates to PatchPanel through which output mix this patch should
3368 // be connected as well as the stream type for volume control
3369 // - the sink is defined by whatever output device is currently selected for the output
3370 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003371 PatchBuilder patchBuilder;
3372 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3373 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003374 &afPatchHandle,
3375 0);
3376 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3377 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003378 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003379 if (status != NO_ERROR) {
3380 ALOGW("%s patch panel could not connect device patch, error %d",
3381 __FUNCTION__, status);
3382 return INVALID_OPERATION;
3383 }
3384 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003385 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003386
3387 if (status != NO_ERROR) {
3388 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3389 return status;
3390 }
3391 sourceDesc->mSwOutput = outputDesc;
3392 if (delayMs != 0) {
3393 usleep(delayMs * 1000);
3394 }
3395 }
3396
3397 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3398 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3399
3400 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003401}
3402
Glenn Kasten559d4392016-03-29 13:42:57 -07003403status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003404{
Eric Laurentd60560a2015-04-10 11:31:20 -07003405 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3406 ALOGV("%s handle %d", __FUNCTION__, handle);
3407 if (sourceDesc == 0) {
3408 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3409 return BAD_VALUE;
3410 }
3411 status_t status = disconnectAudioSource(sourceDesc);
3412
3413 mAudioSources.removeItem(handle);
3414 return status;
3415}
3416
Andy Hung2ddee192015-12-18 17:34:44 -08003417status_t AudioPolicyManager::setMasterMono(bool mono)
3418{
3419 if (mMasterMono == mono) {
3420 return NO_ERROR;
3421 }
3422 mMasterMono = mono;
3423 // if enabling mono we close all offloaded devices, which will invalidate the
3424 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3425 // for recreating the new AudioTrack as non-offloaded PCM.
3426 //
3427 // If disabling mono, we leave all tracks as is: we don't know which clients
3428 // and tracks are able to be recreated as offloaded. The next "song" should
3429 // play back offloaded.
3430 if (mMasterMono) {
3431 Vector<audio_io_handle_t> offloaded;
3432 for (size_t i = 0; i < mOutputs.size(); ++i) {
3433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3434 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3435 offloaded.push(desc->mIoHandle);
3436 }
3437 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003438 for (const auto& handle : offloaded) {
3439 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003440 }
3441 }
3442 // update master mono for all remaining outputs
3443 for (size_t i = 0; i < mOutputs.size(); ++i) {
3444 updateMono(mOutputs.keyAt(i));
3445 }
3446 return NO_ERROR;
3447}
3448
3449status_t AudioPolicyManager::getMasterMono(bool *mono)
3450{
3451 *mono = mMasterMono;
3452 return NO_ERROR;
3453}
3454
Eric Laurentac9cef52017-06-09 15:46:26 -07003455float AudioPolicyManager::getStreamVolumeDB(
3456 audio_stream_type_t stream, int index, audio_devices_t device)
3457{
3458 return computeVolume(stream, index, device);
3459}
3460
jiabin81772902018-04-02 17:52:27 -07003461status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3462 FormatVector& formats) {
3463 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3464 return BAD_VALUE;
3465 }
3466 String8 reply;
3467 reply = mpClientInterface->getParameters(
3468 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3469 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3470 AudioParameter repliedParameters(reply);
3471 if (repliedParameters.get(
3472 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3473 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3474 return BAD_VALUE;
3475 }
3476 for (auto format : formatsFromString(reply.string())) {
3477 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3478 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3479 if (format == AAC_FORMATS[i]) {
3480 format = AUDIO_FORMAT_AAC_LC;
3481 break;
3482 }
3483 }
3484 bool exist = false;
3485 for (size_t i = 0; i < formats.size(); i++) {
3486 if (format == formats[i]) {
3487 exist = true;
3488 break;
3489 }
3490 }
3491 bool isSurroundFormat = false;
3492 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3493 if (SURROUND_FORMATS[i] == format) {
3494 isSurroundFormat = true;
3495 break;
3496 }
3497 }
3498 if (!exist && isSurroundFormat) {
3499 formats.add(format);
3500 }
3501 }
3502 return NO_ERROR;
3503}
3504
3505status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3506 audio_format_t *surroundFormats,
3507 bool *surroundFormatsEnabled,
3508 bool reported)
3509{
3510 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3511 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3512 return BAD_VALUE;
3513 }
3514 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3515 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3516
3517 // Only return value if there is HDMI output.
3518 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3519 return INVALID_OPERATION;
3520 }
3521
3522 size_t formatsWritten = 0;
3523 size_t formatsMax = *numSurroundFormats;
3524 *numSurroundFormats = 0;
3525 FormatVector formats;
3526 if (reported) {
3527 // Only get surround formats which are reported by device.
3528 // First list already open outputs that can be routed to this device
3529 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3530 SortedVector<audio_io_handle_t> outputs;
3531 bool reportedFormatFound = false;
3532 status_t status;
3533 sp<SwAudioOutputDescriptor> desc;
3534 for (size_t i = 0; i < mOutputs.size(); i++) {
3535 desc = mOutputs.valueAt(i);
3536 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3537 outputs.add(mOutputs.keyAt(i));
3538 }
3539 }
3540 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003541 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003542 AUDIO_DEVICE_OUT_HDMI);
3543 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3544 String8 address = hdmiOutputDevices[i]->mAddress;
3545 for (const auto& hwModule : mHwModules) {
3546 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3547 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3548 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3549 profile->supportDeviceAddress(address)) {
3550 size_t j;
3551 for (j = 0; j < outputs.size(); j++) {
3552 desc = mOutputs.valueFor(outputs.itemAt(j));
3553 if (!desc->isDuplicated() && desc->mProfile == profile) {
3554 break;
3555 }
3556 }
3557 if (j != outputs.size()) {
3558 status = getSupportedFormats(outputs.itemAt(j), formats);
3559 reportedFormatFound |= (status == NO_ERROR);
3560 continue;
3561 }
3562
3563 if (!profile->canOpenNewIo()) {
3564 ALOGW("Max Output number %u already opened for this profile %s",
3565 profile->maxOpenCount, profile->getTagName().c_str());
3566 continue;
3567 }
3568
3569 ALOGV("opening output for device %08x with params %s profile %p name %s",
3570 device, address.string(), profile.get(), profile->getName().string());
3571 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3572 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3573 status_t status = desc->open(nullptr, device, address,
3574 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3575 &output);
3576
3577 if (status == NO_ERROR) {
3578 status = getSupportedFormats(output, formats);
3579 reportedFormatFound |= (status == NO_ERROR);
3580 desc->close();
3581 output = AUDIO_IO_HANDLE_NONE;
3582 }
3583 }
3584 }
3585 }
3586 }
3587
3588 if (!reportedFormatFound) {
3589 return UNKNOWN_ERROR;
3590 }
3591 } else {
3592 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3593 formats.add(SURROUND_FORMATS[i]);
3594 }
3595 }
3596 for (size_t i = 0; i < formats.size(); i++) {
3597 if (formatsWritten < formatsMax) {
3598 surroundFormats[formatsWritten] = formats[i];
3599 bool formatEnabled = false;
3600 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3601 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3602 formatEnabled =
3603 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3604 break;
3605 }
3606 } else {
3607 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3608 }
3609 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3610 }
3611 (*numSurroundFormats)++;
3612 }
3613 return NO_ERROR;
3614}
3615
3616status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3617{
3618 // Check if audio format is a surround formats.
3619 bool isSurroundFormat = false;
3620 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3621 if (audioFormat == SURROUND_FORMATS[i]) {
3622 isSurroundFormat = true;
3623 break;
3624 }
3625 }
3626 if (!isSurroundFormat) {
3627 return BAD_VALUE;
3628 }
3629
3630 // Should only be called when MANUAL.
3631 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3632 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3633 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3634 return INVALID_OPERATION;
3635 }
3636
3637 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3638 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3639 return NO_ERROR;
3640 }
3641
3642 // The operation is valid only when there is HDMI output available.
3643 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3644 return INVALID_OPERATION;
3645 }
3646
3647 if (enabled) {
3648 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3649 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3650 mSurroundFormats.insert(AAC_FORMATS[i]);
3651 }
3652 } else {
3653 mSurroundFormats.insert(audioFormat);
3654 }
3655 } else {
3656 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3657 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3658 mSurroundFormats.erase(AAC_FORMATS[i]);
3659 }
3660 } else {
3661 mSurroundFormats.erase(audioFormat);
3662 }
3663 }
3664
3665 sp<SwAudioOutputDescriptor> outputDesc;
3666 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003667 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003668 AUDIO_DEVICE_OUT_HDMI);
3669 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3670 // Simulate reconnection to update enabled surround sound formats.
3671 String8 address = hdmiOutputDevices[i]->mAddress;
3672 String8 name = hdmiOutputDevices[i]->getName();
3673 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3674 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3675 address.c_str(),
3676 name.c_str());
3677 if (status != NO_ERROR) {
3678 continue;
3679 }
3680 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3681 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3682 address.c_str(),
3683 name.c_str());
3684 profileUpdated |= (status == NO_ERROR);
3685 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003686 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003687 AUDIO_DEVICE_IN_HDMI);
3688 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3689 // Simulate reconnection to update enabled surround sound formats.
3690 String8 address = hdmiInputDevices[i]->mAddress;
3691 String8 name = hdmiInputDevices[i]->getName();
3692 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3693 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3694 address.c_str(),
3695 name.c_str());
3696 if (status != NO_ERROR) {
3697 continue;
3698 }
3699 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3700 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3701 address.c_str(),
3702 name.c_str());
3703 profileUpdated |= (status == NO_ERROR);
3704 }
3705
3706 // Undo the surround formats change due to no audio profiles updated.
3707 if (!profileUpdated) {
3708 if (enabled) {
3709 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3710 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3711 mSurroundFormats.erase(AAC_FORMATS[i]);
3712 }
3713 } else {
3714 mSurroundFormats.erase(audioFormat);
3715 }
3716 } else {
3717 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3718 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3719 mSurroundFormats.insert(AAC_FORMATS[i]);
3720 }
3721 } else {
3722 mSurroundFormats.insert(audioFormat);
3723 }
3724 }
3725 }
3726
3727 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3728}
3729
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003730void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3731{
3732 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3733
3734 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3735 for (size_t i = 0; i < activeInputs.size(); i++) {
3736 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3737 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3738 for (size_t j = 0; j < activeSessions.size(); j++) {
3739 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3740 if (activeSession->uid() == uid) {
3741 activeSession->setSilenced(silenced);
3742 }
3743 }
3744 }
3745}
3746
Eric Laurentd60560a2015-04-10 11:31:20 -07003747status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3748{
3749 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3750
3751 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3752 if (patchDesc == 0) {
3753 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3754 sourceDesc->mPatchDesc->mHandle);
3755 return BAD_VALUE;
3756 }
3757 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3758
Eric Laurent28d09f02016-03-08 10:43:05 -08003759 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003760 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3761 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003762 status_t status = stopSource(swOutputDesc, stream, false);
3763 if (status == NO_ERROR) {
3764 swOutputDesc->stop();
3765 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003766 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3767 } else {
3768 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3769 if (hwOutputDesc != 0) {
3770 // release patch between src device and output device
3771 // close Hwoutput and remove from mHwOutputs
3772 } else {
3773 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3774 }
3775 }
3776 return NO_ERROR;
3777}
3778
3779sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3780 audio_io_handle_t output, routing_strategy strategy)
3781{
3782 sp<AudioSourceDescriptor> source;
3783 for (size_t i = 0; i < mAudioSources.size(); i++) {
3784 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3785 routing_strategy sourceStrategy =
3786 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3787 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3788 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3789 source = sourceDesc;
3790 break;
3791 }
3792 }
3793 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003794}
3795
Eric Laurente552edb2014-03-10 17:42:56 -07003796// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003797// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003798// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003799uint32_t AudioPolicyManager::nextAudioPortGeneration()
3800{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003801 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003802}
3803
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003804#ifdef USE_XML_AUDIO_POLICY_CONF
3805// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3806static const char *kConfigLocationList[] =
3807 {"/odm/etc", "/vendor/etc", "/system/etc"};
3808static const int kConfigLocationListSize =
3809 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3810
3811static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3812 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003813 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003814 status_t ret;
3815
Petri Gyntherf497f292018-04-17 18:46:10 -07003816 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3817 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3818 // A2DP offload supported but disabled: try to use special XML file
3819 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3820 }
3821 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3822
3823 for (const char* fileName : fileNames) {
3824 for (int i = 0; i < kConfigLocationListSize; i++) {
3825 PolicySerializer serializer;
3826 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3827 "%s/%s", kConfigLocationList[i], fileName);
3828 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3829 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003830 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003831 return ret;
3832 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003833 }
3834 }
3835 return ret;
3836}
3837#endif
3838
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003839AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3840 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003841 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003842 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003843 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003844 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003845 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003846#ifdef USE_XML_AUDIO_POLICY_CONF
3847 mVolumeCurves(new VolumeCurvesCollection()),
3848 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003849 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003850#else
3851 mVolumeCurves(new StreamDescriptorCollection()),
3852 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3853 mDefaultOutputDevice),
3854#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003855 mAudioPortGeneration(1),
3856 mBeaconMuteRefCount(0),
3857 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003858 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003859 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003860 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003861 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3862 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003863{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003864}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003865
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003866AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3867 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3868{
3869 loadConfig();
3870 initialize();
3871}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003872
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003873void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003874#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003875 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003876#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003877 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3878 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003879#endif
3880 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003881 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003882 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003883}
3884
3885status_t AudioPolicyManager::initialize() {
3886 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003887
3888 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003889 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3890 if (!engineInstance) {
3891 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003893 }
3894 // Retrieve the Policy Manager Interface
3895 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3896 if (mEngine == NULL) {
3897 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003898 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003899 }
3900 mEngine->setObserver(this);
3901 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003902 if (status != NO_ERROR) {
3903 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3904 return status;
3905 }
François Gaffie2110e042015-03-24 08:41:51 +01003906
Eric Laurent3a4311c2014-03-17 12:00:47 -07003907 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003908 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003909 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3910 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003911 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003912 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003913 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3914 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003915 continue;
3916 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003917 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003918 // open all output streams needed to access attached devices
3919 // except for direct output streams that are only opened when they are actually
3920 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003921 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003922 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003923 if (!outProfile->canOpenNewIo()) {
3924 ALOGE("Invalid Output profile max open count %u for profile %s",
3925 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3926 continue;
3927 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003928 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003929 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 continue;
3931 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003932 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003933 mTtsOutputAvailable = true;
3934 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003936 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003937 continue;
3938 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003939 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003940 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3941 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003942 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003943 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003944 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003945 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003946 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003947 if ((profileType & outputDeviceTypes) == 0) {
3948 continue;
3949 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003950 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3951 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003952 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003953 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3954 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003955 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3956 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003957 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003958 status_t status = outputDesc->open(nullptr, profileType, address,
3959 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003960
3961 if (status != NO_ERROR) {
3962 ALOGW("Cannot open output stream for device %08x on hw module %s",
3963 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003964 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003965 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003966 for (const auto& dev : supportedDevices) {
3967 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003968 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003969 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003970 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003971 }
3972 }
3973 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003974 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003975 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003976 }
3977 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003978 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003979 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003980 true,
3981 0,
3982 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003983 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003984 }
Eric Laurente552edb2014-03-10 17:42:56 -07003985 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003986 // open input streams needed to access attached devices to validate
3987 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003988 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003989 if (!inProfile->canOpenNewIo()) {
3990 ALOGE("Invalid Input profile max open count %u for profile %s",
3991 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3992 continue;
3993 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003994 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003995 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003996 continue;
3997 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003998 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003999 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004000 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4001
Eric Laurentd78f1532014-09-16 16:38:20 -07004002 if ((profileType & inputDeviceTypes) == 0) {
4003 continue;
4004 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004005 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004006 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004007
Mikhail Naganov708e0382018-05-30 09:53:04 -07004008 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004009 // the inputs vector must be of size >= 1, but we don't want to crash here
4010 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4011 : String8("");
4012 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4013 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4014
Eric Laurentd78f1532014-09-16 16:38:20 -07004015 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004016 status_t status = inputDesc->open(nullptr,
4017 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004018 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004019 AUDIO_SOURCE_MIC,
4020 AUDIO_INPUT_FLAG_NONE,
4021 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004022
4023 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004024 for (const auto& dev : inProfile->getSupportedDevices()) {
4025 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004026 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004027 if (index >= 0) {
4028 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4029 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004030 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004031 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004032 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004033 }
4034 }
Eric Laurentfe231122017-11-17 17:48:06 -08004035 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004036 } else {
4037 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004038 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004039 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004040 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004041 }
4042 }
4043 // make sure all attached devices have been allocated a unique ID
4044 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004045 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004046 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004047 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4048 continue;
4049 }
François Gaffie2110e042015-03-24 08:41:51 +01004050 // The device is now validated and can be appended to the available devices of the engine
4051 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4052 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004053 i++;
4054 }
4055 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004056 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004057 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4059 continue;
4060 }
François Gaffie2110e042015-03-24 08:41:51 +01004061 // The device is now validated and can be appended to the available devices of the engine
4062 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4063 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 i++;
4065 }
4066 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004067 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004068 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004069 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 }
jiabin9ff780e2018-03-19 18:19:52 -07004071 // If microphones address is empty, set it according to device type
4072 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4073 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4074 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4075 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4076 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4077 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4078 }
4079 }
4080 }
Eric Laurente552edb2014-03-10 17:42:56 -07004081
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004082 if (mPrimaryOutput == 0) {
4083 ALOGE("Failed to open primary output");
4084 status = NO_INIT;
4085 }
Eric Laurente552edb2014-03-10 17:42:56 -07004086
4087 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004088 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004089}
4090
Eric Laurente0720872014-03-11 09:30:41 -07004091AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004092{
Eric Laurente552edb2014-03-10 17:42:56 -07004093 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004094 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004095 }
4096 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004097 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004098 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004099 mAvailableOutputDevices.clear();
4100 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004101 mOutputs.clear();
4102 mInputs.clear();
4103 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004104 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004105 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004106}
4107
Eric Laurente0720872014-03-11 09:30:41 -07004108status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004109{
Eric Laurent87ffa392015-05-22 10:32:38 -07004110 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004111}
4112
Eric Laurente552edb2014-03-10 17:42:56 -07004113// ---
4114
Eric Laurent98e38192018-02-15 18:31:53 -08004115void AudioPolicyManager::addOutput(audio_io_handle_t output,
4116 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004117{
Eric Laurent1c333e22014-05-20 10:48:17 -07004118 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004119 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004120 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004121 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004122 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004123}
4124
François Gaffie53615e22015-03-19 09:24:12 +01004125void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4126{
4127 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004128 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004129}
4130
Eric Laurent98e38192018-02-15 18:31:53 -08004131void AudioPolicyManager::addInput(audio_io_handle_t input,
4132 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004133{
Eric Laurent1c333e22014-05-20 10:48:17 -07004134 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004135 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004136}
Eric Laurente552edb2014-03-10 17:42:56 -07004137
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004138void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004139 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004140 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004141 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004142 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004143 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004144 if (devDesc != 0) {
4145 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4146 desc->mIoHandle, address.string());
4147 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004148 }
4149}
4150
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004151status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004152 audio_policy_dev_state_t state,
4153 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004154 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004155{
François Gaffie53615e22015-03-19 09:24:12 +01004156 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004157 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004158
4159 if (audio_device_is_digital(device)) {
4160 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004161 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004162 }
Eric Laurente552edb2014-03-10 17:42:56 -07004163
Eric Laurent3b73df72014-03-11 09:06:29 -07004164 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004165 // first list already open outputs that can be routed to this device
4166 for (size_t i = 0; i < mOutputs.size(); i++) {
4167 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004168 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004169 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004170 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4171 outputs.add(mOutputs.keyAt(i));
4172 } else {
4173 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004174 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004175 }
Eric Laurente552edb2014-03-10 17:42:56 -07004176 }
4177 }
4178 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004179 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004180 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004181 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4182 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004183 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004184 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004185 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004186 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004187 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4188 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004189 }
Eric Laurente552edb2014-03-10 17:42:56 -07004190 }
4191 }
4192 }
4193
Eric Laurent7b279bb2015-12-14 10:18:23 -08004194 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004195
Eric Laurente552edb2014-03-10 17:42:56 -07004196 if (profiles.isEmpty() && outputs.isEmpty()) {
4197 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4198 return BAD_VALUE;
4199 }
4200
4201 // open outputs for matching profiles if needed. Direct outputs are also opened to
4202 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4203 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004204 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004205
4206 // nothing to do if one output is already opened for this profile
4207 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004208 for (j = 0; j < outputs.size(); j++) {
4209 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004210 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004211 // matching profile: save the sample rates, format and channel masks supported
4212 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004213 if (audio_device_is_digital(device)) {
4214 devDesc->importAudioPort(profile);
4215 }
Eric Laurente552edb2014-03-10 17:42:56 -07004216 break;
4217 }
4218 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004219 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004220 continue;
4221 }
4222
Eric Laurent3974e3b2017-12-07 17:58:43 -08004223 if (!profile->canOpenNewIo()) {
4224 ALOGW("Max Output number %u already opened for this profile %s",
4225 profile->maxOpenCount, profile->getTagName().c_str());
4226 continue;
4227 }
4228
Eric Laurent83efe1c2017-07-09 16:51:08 -07004229 ALOGV("opening output for device %08x with params %s profile %p name %s",
4230 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004231 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004232 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004233 status_t status = desc->open(nullptr, device, address,
4234 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004235
Eric Laurentfe231122017-11-17 17:48:06 -08004236 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004237 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004238 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004239 char *param = audio_device_address_to_parameter(device, address);
4240 mpClientInterface->setParameters(output, String8(param));
4241 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004242 }
Phil Burk00eeb322016-03-31 12:41:00 -07004243 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004244 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004245 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004246 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004247 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004248 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004249 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004250 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004251 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4252 profile->pickAudioProfile(
4253 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 config.offload_info.sample_rate = config.sample_rate;
4255 config.offload_info.channel_mask = config.channel_mask;
4256 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004257
4258 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4259 AUDIO_OUTPUT_FLAG_NONE, &output);
4260 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004261 output = AUDIO_IO_HANDLE_NONE;
4262 }
Eric Laurentd4692962014-05-05 18:13:44 -07004263 }
4264
Eric Laurentcf2c0212014-07-25 16:20:43 -07004265 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004266 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004267 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004268 sp<AudioPolicyMix> policyMix;
4269 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004270 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4271 address.string());
4272 }
François Gaffie036e1e92015-03-19 10:16:24 +01004273 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004274 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004275
Eric Laurent87ffa392015-05-22 10:32:38 -07004276 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4277 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004278 // no duplicated output for direct outputs and
4279 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004280 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004281
Eric Laurentd4692962014-05-05 18:13:44 -07004282 //TODO: configure audio effect output stage here
4283
4284 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004285 sp<SwAudioOutputDescriptor> dupOutputDesc =
4286 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4287 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4288 &duplicatedOutput);
4289 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004290 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004291 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004292 } else {
4293 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004294 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004295 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004296 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004297 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004298 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004299 }
Eric Laurente552edb2014-03-10 17:42:56 -07004300 }
4301 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004302 } else {
4303 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004304 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004305 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004306 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004307 profiles.removeAt(profile_index);
4308 profile_index--;
4309 } else {
4310 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004311 // Load digital format info only for digital devices
4312 if (audio_device_is_digital(device)) {
4313 devDesc->importAudioPort(profile);
4314 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004315
François Gaffie53615e22015-03-19 09:24:12 +01004316 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004317 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4318 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004319 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004320 NULL/*patch handle*/, address.string());
4321 }
Eric Laurente552edb2014-03-10 17:42:56 -07004322 ALOGV("checkOutputsForDevice(): adding output %d", output);
4323 }
4324 }
4325
4326 if (profiles.isEmpty()) {
4327 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4328 return BAD_VALUE;
4329 }
Eric Laurentd4692962014-05-05 18:13:44 -07004330 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004331 // check if one opened output is not needed any more after disconnecting one device
4332 for (size_t i = 0; i < mOutputs.size(); i++) {
4333 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004334 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004335 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004336 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004337 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004338 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004339 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004340 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4341 mOutputs.keyAt(i));
4342 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004343 }
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
4345 }
Eric Laurentd4692962014-05-05 18:13:44 -07004346 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004347 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004348 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4349 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004350 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004351 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004352 "clearing direct output profile %zu on module %s",
4353 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004354 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004355 }
4356 }
4357 }
4358 }
4359 return NO_ERROR;
4360}
4361
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004362status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004363 audio_policy_dev_state_t state,
4364 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004365 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004366{
Paul McLean9080a4c2015-06-18 08:24:02 -07004367 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004368 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004369
4370 if (audio_device_is_digital(device)) {
4371 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004372 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004373 }
4374
Eric Laurentd4692962014-05-05 18:13:44 -07004375 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4376 // first list already open inputs that can be routed to this device
4377 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4378 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004379 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004380 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4381 inputs.add(mInputs.keyAt(input_index));
4382 }
4383 }
4384
4385 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004386 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004387 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004388 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004389 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004390 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004391 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004392
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004393 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004394 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004395 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004396 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004397 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4398 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004399 }
Eric Laurentd4692962014-05-05 18:13:44 -07004400 }
4401 }
4402 }
4403
4404 if (profiles.isEmpty() && inputs.isEmpty()) {
4405 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4406 return BAD_VALUE;
4407 }
4408
4409 // open inputs for matching profiles if needed. Direct inputs are also opened to
4410 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4411 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4412
Eric Laurent1c333e22014-05-20 10:48:17 -07004413 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004414
Eric Laurentd4692962014-05-05 18:13:44 -07004415 // nothing to do if one input is already opened for this profile
4416 size_t input_index;
4417 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4418 desc = mInputs.valueAt(input_index);
4419 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004420 if (audio_device_is_digital(device)) {
4421 devDesc->importAudioPort(profile);
4422 }
Eric Laurentd4692962014-05-05 18:13:44 -07004423 break;
4424 }
4425 }
4426 if (input_index != mInputs.size()) {
4427 continue;
4428 }
4429
Eric Laurent3974e3b2017-12-07 17:58:43 -08004430 if (!profile->canOpenNewIo()) {
4431 ALOGW("Max Input number %u already opened for this profile %s",
4432 profile->maxOpenCount, profile->getTagName().c_str());
4433 continue;
4434 }
4435
Eric Laurentfe231122017-11-17 17:48:06 -08004436 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004437 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004438 status_t status = desc->open(nullptr,
4439 device,
4440 address,
4441 AUDIO_SOURCE_MIC,
4442 AUDIO_INPUT_FLAG_NONE,
4443 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004444
Eric Laurentcf2c0212014-07-25 16:20:43 -07004445 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004446 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004447 char *param = audio_device_address_to_parameter(device, address);
4448 mpClientInterface->setParameters(input, String8(param));
4449 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004450 }
Phil Burk00eeb322016-03-31 12:41:00 -07004451 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004452 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004453 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004454 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004455 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004456 }
4457
4458 if (input != 0) {
4459 addInput(input, desc);
4460 }
4461 } // endif input != 0
4462
Eric Laurentcf2c0212014-07-25 16:20:43 -07004463 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004464 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004465 profiles.removeAt(profile_index);
4466 profile_index--;
4467 } else {
4468 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004469 if (audio_device_is_digital(device)) {
4470 devDesc->importAudioPort(profile);
4471 }
Eric Laurentd4692962014-05-05 18:13:44 -07004472 ALOGV("checkInputsForDevice(): adding input %d", input);
4473 }
4474 } // end scan profiles
4475
4476 if (profiles.isEmpty()) {
4477 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4478 return BAD_VALUE;
4479 }
4480 } else {
4481 // Disconnect
4482 // check if one opened input is not needed any more after disconnecting one device
4483 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4484 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004485 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004486 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4487 mInputs.keyAt(input_index));
4488 inputs.add(mInputs.keyAt(input_index));
4489 }
4490 }
4491 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004492 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004493 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004494 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004495 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004496 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004497 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004498 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4499 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004500 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004501 }
4502 }
4503 }
4504 } // end disconnect
4505
4506 return NO_ERROR;
4507}
4508
4509
Eric Laurente0720872014-03-11 09:30:41 -07004510void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004511{
4512 ALOGV("closeOutput(%d)", output);
4513
Eric Laurentc75307b2015-03-17 15:29:32 -07004514 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 if (outputDesc == NULL) {
4516 ALOGW("closeOutput() unknown output %d", output);
4517 return;
4518 }
François Gaffie036e1e92015-03-19 10:16:24 +01004519 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004520
Eric Laurente552edb2014-03-10 17:42:56 -07004521 // look for duplicated outputs connected to the output being removed.
4522 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004523 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004524 if (dupOutputDesc->isDuplicated() &&
4525 (dupOutputDesc->mOutput1 == outputDesc ||
4526 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004527 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004528 if (dupOutputDesc->mOutput1 == outputDesc) {
4529 outputDesc2 = dupOutputDesc->mOutput2;
4530 } else {
4531 outputDesc2 = dupOutputDesc->mOutput1;
4532 }
4533 // As all active tracks on duplicated output will be deleted,
4534 // and as they were also referenced on the other output, the reference
4535 // count for their stream type must be adjusted accordingly on
4536 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004537 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004538 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004539 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004540 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004541 }
Eric Laurent733ce942017-12-07 12:18:25 -08004542 // stop() will be a no op if the output is still active but is needed in case all
4543 // active streams refcounts where cleared above
4544 if (wasActive) {
4545 outputDesc2->stop();
4546 }
Eric Laurente552edb2014-03-10 17:42:56 -07004547 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4548 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4549
4550 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004551 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004552 }
4553 }
4554
Eric Laurent05b90f82014-08-27 15:32:29 -07004555 nextAudioPortGeneration();
4556
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004557 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004558 if (index >= 0) {
4559 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004560 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004561 mAudioPatches.removeItemsAt(index);
4562 mpClientInterface->onAudioPatchListUpdate();
4563 }
4564
Eric Laurentfe231122017-11-17 17:48:06 -08004565 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004566
François Gaffie53615e22015-03-19 09:24:12 +01004567 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004568 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004569}
4570
4571void AudioPolicyManager::closeInput(audio_io_handle_t input)
4572{
4573 ALOGV("closeInput(%d)", input);
4574
4575 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4576 if (inputDesc == NULL) {
4577 ALOGW("closeInput() unknown input %d", input);
4578 return;
4579 }
4580
Eric Laurent6a94d692014-05-20 11:18:06 -07004581 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004582
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004583 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004584 if (index >= 0) {
4585 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004586 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004587 mAudioPatches.removeItemsAt(index);
4588 mpClientInterface->onAudioPatchListUpdate();
4589 }
4590
Eric Laurentfe231122017-11-17 17:48:06 -08004591 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004592 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004593}
4594
Eric Laurentc75307b2015-03-17 15:29:32 -07004595SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4596 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004597 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004598{
4599 SortedVector<audio_io_handle_t> outputs;
4600
4601 ALOGVV("getOutputsForDevice() device %04x", device);
4602 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004603 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004604 i, openOutputs.valueAt(i)->isDuplicated(),
4605 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004606 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4607 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4608 outputs.add(openOutputs.keyAt(i));
4609 }
4610 }
4611 return outputs;
4612}
4613
Eric Laurente0720872014-03-11 09:30:41 -07004614bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004615 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004616{
4617 if (outputs1.size() != outputs2.size()) {
4618 return false;
4619 }
4620 for (size_t i = 0; i < outputs1.size(); i++) {
4621 if (outputs1[i] != outputs2[i]) {
4622 return false;
4623 }
4624 }
4625 return true;
4626}
4627
Mikhail Naganov37977152018-07-11 15:54:44 -07004628void AudioPolicyManager::checkForDeviceAndOutputChanges()
4629{
4630 checkForDeviceAndOutputChanges([](){ return false; });
4631}
4632
4633void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4634{
4635 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4636 // output is suspended before any tracks are moved to it
4637 checkA2dpSuspend();
4638 checkOutputForAllStrategies();
4639 if (onOutputsChecked()) checkA2dpSuspend();
4640 updateDevicesAndOutputs();
4641}
4642
Eric Laurente0720872014-03-11 09:30:41 -07004643void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004644{
4645 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4646 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4647 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4648 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4649
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004650 // also take into account external policy-related changes: add all outputs which are
4651 // associated with policies in the "before" and "after" output vectors
4652 ALOGVV("checkOutputForStrategy(): policy related outputs");
4653 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004654 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004655 if (desc != 0 && desc->mPolicyMix != NULL) {
4656 srcOutputs.add(desc->mIoHandle);
4657 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4658 }
4659 }
4660 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004661 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004662 if (desc != 0 && desc->mPolicyMix != NULL) {
4663 dstOutputs.add(desc->mIoHandle);
4664 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4665 }
4666 }
4667
Eric Laurente552edb2014-03-10 17:42:56 -07004668 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004669 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4670 // audio from invalidated tracks will be rendered when unmuting
4671 uint32_t maxLatency = 0;
4672 for (audio_io_handle_t srcOut : srcOutputs) {
4673 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4674 if (desc != 0 && maxLatency < desc->latency()) {
4675 maxLatency = desc->latency();
4676 }
4677 }
Eric Laurente552edb2014-03-10 17:42:56 -07004678 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4679 strategy, srcOutputs[0], dstOutputs[0]);
4680 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004681 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004682 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4683 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004684 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004685 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004686 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004687 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004688 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004689 if (source != 0){
4690 connectAudioSource(source);
4691 }
Eric Laurente552edb2014-03-10 17:42:56 -07004692 }
4693
4694 // Move effects associated to this strategy from previous output to new output
4695 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004696 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004697 }
4698 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004699 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004700 if (getStrategy((audio_stream_type_t)i) == strategy) {
4701 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004702 }
4703 }
4704 }
4705}
4706
Eric Laurente0720872014-03-11 09:30:41 -07004707void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004708{
François Gaffie2110e042015-03-24 08:41:51 +01004709 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004710 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004711 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004712 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004713 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004714 checkOutputForStrategy(STRATEGY_SONIFICATION);
4715 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004716 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 checkOutputForStrategy(STRATEGY_MEDIA);
4718 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004719 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
François Gaffie53615e22015-03-19 09:24:12 +01004724 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004725 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004726 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004727 return;
4728 }
4729
Eric Laurent3a4311c2014-03-17 12:00:47 -07004730 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004731 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4732 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4733 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004734
4735 // if suspended, restore A2DP output if:
4736 // ((SCO device is NOT connected) ||
4737 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4738 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004739 //
Eric Laurentf732e072016-08-03 19:30:28 -07004740 // if not suspended, suspend A2DP output if:
4741 // (SCO device is connected) &&
4742 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4743 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004744 //
4745 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004746 if (!isScoConnected ||
4747 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4748 AUDIO_POLICY_FORCE_BT_SCO) &&
4749 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4750 AUDIO_POLICY_FORCE_BT_SCO) &&
4751 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004752 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004753
4754 mpClientInterface->restoreOutput(a2dpOutput);
4755 mA2dpSuspended = false;
4756 }
4757 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004758 if (isScoConnected &&
4759 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4760 AUDIO_POLICY_FORCE_BT_SCO) ||
4761 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4762 AUDIO_POLICY_FORCE_BT_SCO) ||
4763 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004764 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004765
4766 mpClientInterface->suspendOutput(a2dpOutput);
4767 mA2dpSuspended = true;
4768 }
4769 }
4770}
4771
Eric Laurentc75307b2015-03-17 15:29:32 -07004772audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4773 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004774{
4775 audio_devices_t device = AUDIO_DEVICE_NONE;
4776
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004777 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 if (index >= 0) {
4779 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4780 if (patchDesc->mUid != mUidCached) {
4781 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004782 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 return outputDesc->device();
4784 }
4785 }
4786
Eric Laurentf3a5a602018-05-22 18:42:55 -07004787 // Check if an explicit routing request exists for an active stream on this output and
4788 // use it in priority before any other rule
4789 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4790 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4791 audio_devices_t forcedDevice =
4792 mOutputRoutes.getActiveDeviceForStream(
4793 (audio_stream_type_t)stream, mAvailableOutputDevices);
4794
4795 if (forcedDevice != AUDIO_DEVICE_NONE) {
4796 return forcedDevice;
4797 }
4798 }
4799 }
4800
Eric Laurente552edb2014-03-10 17:42:56 -07004801 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004802 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004803 // use device for strategy enforced audible
4804 // 2: we are in call or the strategy phone is active on the output:
4805 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004806 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004807 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004808 // 4: the strategy for enforced audible is active but not enforced on the output:
4809 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004810 // 5: the strategy accessibility is active on the output:
4811 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004812 // 6: the strategy "respectful" sonification is active on the output:
4813 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004814 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004815 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004816 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004817 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004818 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004819 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004820
4821 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4822 // with a refined rule considering mutually exclusive devices (using same backend)
4823 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004824 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004825 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004826 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4827 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004828 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004829 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004830 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004831 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004832 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4833 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004834 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4835 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004836 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004837 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004838 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004839 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004840 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004842 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004843 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004844 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004845 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004846 }
4847
Eric Laurent1c333e22014-05-20 10:48:17 -07004848 ALOGV("getNewOutputDevice() selected device %x", device);
4849 return device;
4850}
4851
Eric Laurentfb66dd92016-01-28 18:32:03 -08004852audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004853{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004854 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004855
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004856 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 if (index >= 0) {
4858 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4859 if (patchDesc->mUid != mUidCached) {
4860 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004861 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 return inputDesc->mDevice;
4863 }
4864 }
4865
Eric Laurentdc95a252018-04-12 12:46:56 -07004866 // If we are not in call and no client is active on this input, this methods returns
4867 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004868 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004869 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4870 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4871 }
4872 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004873 device = getDeviceAndMixForInputSource(source);
4874 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004875
Eric Laurente552edb2014-03-10 17:42:56 -07004876 return device;
4877}
4878
Eric Laurent794fde22016-03-11 09:50:45 -08004879bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4880 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004881 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004882}
4883
Eric Laurente0720872014-03-11 09:30:41 -07004884uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004885 return (uint32_t)getStrategy(stream);
4886}
4887
Eric Laurente0720872014-03-11 09:30:41 -07004888audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004889 // By checking the range of stream before calling getStrategy, we avoid
4890 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4891 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004892 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004893 return AUDIO_DEVICE_NONE;
4894 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004895 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004896 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4897 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004898 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 }
Eric Laurent794fde22016-03-11 09:50:45 -08004900 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004901 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004902 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004903 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4904 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004905 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004906 curDevices |= outputDesc->device();
4907 }
4908 }
4909 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004910 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004911
4912 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4913 and doesn't really need to.*/
4914 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4915 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4916 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4917 }
Eric Laurente552edb2014-03-10 17:42:56 -07004918 return devices;
4919}
4920
François Gaffie2110e042015-03-24 08:41:51 +01004921routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4922{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004923 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004924 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004925}
4926
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004927uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4928 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004929 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4930 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4931 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004932 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4933 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4934 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004935 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004936 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004937}
4938
Eric Laurente0720872014-03-11 09:30:41 -07004939void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004940 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004941 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004942 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4943 updateDevicesAndOutputs();
4944 break;
4945 default:
4946 break;
4947 }
4948}
4949
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004950uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004951
4952 // skip beacon mute management if a dedicated TTS output is available
4953 if (mTtsOutputAvailable) {
4954 return 0;
4955 }
4956
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004957 switch(event) {
4958 case STARTING_OUTPUT:
4959 mBeaconMuteRefCount++;
4960 break;
4961 case STOPPING_OUTPUT:
4962 if (mBeaconMuteRefCount > 0) {
4963 mBeaconMuteRefCount--;
4964 }
4965 break;
4966 case STARTING_BEACON:
4967 mBeaconPlayingRefCount++;
4968 break;
4969 case STOPPING_BEACON:
4970 if (mBeaconPlayingRefCount > 0) {
4971 mBeaconPlayingRefCount--;
4972 }
4973 break;
4974 }
4975
4976 if (mBeaconMuteRefCount > 0) {
4977 // any playback causes beacon to be muted
4978 return setBeaconMute(true);
4979 } else {
4980 // no other playback: unmute when beacon starts playing, mute when it stops
4981 return setBeaconMute(mBeaconPlayingRefCount == 0);
4982 }
4983}
4984
4985uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4986 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4987 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4988 // keep track of muted state to avoid repeating mute/unmute operations
4989 if (mBeaconMuted != mute) {
4990 // mute/unmute AUDIO_STREAM_TTS on all outputs
4991 ALOGV("\t muting %d", mute);
4992 uint32_t maxLatency = 0;
4993 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004994 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004995 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004996 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004997 0 /*delay*/, AUDIO_DEVICE_NONE);
4998 const uint32_t latency = desc->latency() * 2;
4999 if (latency > maxLatency) {
5000 maxLatency = latency;
5001 }
5002 }
5003 mBeaconMuted = mute;
5004 return maxLatency;
5005 }
5006 return 0;
5007}
5008
Eric Laurente0720872014-03-11 09:30:41 -07005009audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005010 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005011{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005012 // Check if an explicit routing request exists for a stream type corresponding to the
5013 // specified strategy and use it in priority over default routing rules.
5014 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5015 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5016 audio_devices_t forcedDevice =
5017 mOutputRoutes.getActiveDeviceForStream(
5018 (audio_stream_type_t)stream, mAvailableOutputDevices);
5019 if (forcedDevice != AUDIO_DEVICE_NONE) {
5020 return forcedDevice;
5021 }
Paul McLeanaa981192015-03-21 09:55:15 -07005022 }
5023 }
5024
Eric Laurente552edb2014-03-10 17:42:56 -07005025 if (fromCache) {
5026 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5027 strategy, mDeviceForStrategy[strategy]);
5028 return mDeviceForStrategy[strategy];
5029 }
François Gaffie2110e042015-03-24 08:41:51 +01005030 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005031}
5032
Eric Laurente0720872014-03-11 09:30:41 -07005033void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005034{
5035 for (int i = 0; i < NUM_STRATEGIES; i++) {
5036 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5037 }
5038 mPreviousOutputs = mOutputs;
5039}
5040
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005041uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005042 audio_devices_t prevDevice,
5043 uint32_t delayMs)
5044{
5045 // mute/unmute strategies using an incompatible device combination
5046 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5047 // if unmuting, unmute only after the specified delay
5048 if (outputDesc->isDuplicated()) {
5049 return 0;
5050 }
5051
5052 uint32_t muteWaitMs = 0;
5053 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005054 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005055
5056 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5057 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005058 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005059 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5060 bool doMute = false;
5061
5062 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5063 doMute = true;
5064 outputDesc->mStrategyMutedByDevice[i] = true;
5065 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5066 doMute = true;
5067 outputDesc->mStrategyMutedByDevice[i] = false;
5068 }
Eric Laurent99401132014-05-07 19:48:15 -07005069 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005070 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005071 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005072 // skip output if it does not share any device with current output
5073 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5074 == AUDIO_DEVICE_NONE) {
5075 continue;
5076 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005077 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005078 mute ? "muting" : "unmuting", i, curDevice);
5079 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005080 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005081 if (mute) {
5082 // FIXME: should not need to double latency if volume could be applied
5083 // immediately by the audioflinger mixer. We must account for the delay
5084 // between now and the next time the audioflinger thread for this output
5085 // will process a buffer (which corresponds to one buffer size,
5086 // usually 1/2 or 1/4 of the latency).
5087 if (muteWaitMs < desc->latency() * 2) {
5088 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005089 }
5090 }
5091 }
5092 }
5093 }
5094 }
5095
Eric Laurent99401132014-05-07 19:48:15 -07005096 // temporary mute output if device selection changes to avoid volume bursts due to
5097 // different per device volumes
5098 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005099 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5100 // temporary mute duration is conservatively set to 4 times the reported latency
5101 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5102 if (muteWaitMs < tempMuteWaitMs) {
5103 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005104 }
Eric Laurentdc462862016-07-19 12:29:53 -07005105
Eric Laurent99401132014-05-07 19:48:15 -07005106 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005107 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005108 // make sure that we do not start the temporary mute period too early in case of
5109 // delayed device change
5110 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005111 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005112 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005113 }
5114 }
5115 }
5116
Eric Laurente552edb2014-03-10 17:42:56 -07005117 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5118 if (muteWaitMs > delayMs) {
5119 muteWaitMs -= delayMs;
5120 usleep(muteWaitMs * 1000);
5121 return muteWaitMs;
5122 }
5123 return 0;
5124}
5125
Eric Laurentc75307b2015-03-17 15:29:32 -07005126uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005127 audio_devices_t device,
5128 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005129 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005130 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005131 const char *address,
5132 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005133{
Eric Laurentc75307b2015-03-17 15:29:32 -07005134 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005135 AudioParameter param;
5136 uint32_t muteWaitMs;
5137
5138 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005139 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5140 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5141 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5142 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005143 return muteWaitMs;
5144 }
5145 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5146 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005147 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005148 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005149 return 0;
5150 }
5151
5152 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005153 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005154
5155 audio_devices_t prevDevice = outputDesc->mDevice;
5156
Paul McLeanaa981192015-03-21 09:55:15 -07005157 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005158
5159 if (device != AUDIO_DEVICE_NONE) {
5160 outputDesc->mDevice = device;
5161 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005162
5163 // if the outputs are not materially active, there is no need to mute.
5164 if (requiresMuteCheck) {
5165 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5166 } else {
5167 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5168 muteWaitMs = 0;
5169 }
Eric Laurente552edb2014-03-10 17:42:56 -07005170
5171 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005172 // the requested device is AUDIO_DEVICE_NONE
5173 // OR the requested device is the same as current device
5174 // AND force is not specified
5175 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005176 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005177 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5178 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005179 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005180 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005181 return muteWaitMs;
5182 }
5183
5184 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005185
Eric Laurente552edb2014-03-10 17:42:56 -07005186 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005187 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005188 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005189 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005190 DeviceVector deviceList;
5191 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005192 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005193 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005194 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5195 device, String8(address));
5196 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005197 }
5198
Eric Laurent1c333e22014-05-20 10:48:17 -07005199 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005200 PatchBuilder patchBuilder;
5201 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005202 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005203 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005205 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005206 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005207
5208 // inform all input as well
5209 for (size_t i = 0; i < mInputs.size(); i++) {
5210 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005211 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005212 AudioParameter inputCmd = AudioParameter();
5213 ALOGV("%s: inform input %d of device:%d", __func__,
5214 inputDescriptor->mIoHandle, device);
5215 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5216 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5217 inputCmd.toString(),
5218 delayMs);
5219 }
5220 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005221 }
Eric Laurente552edb2014-03-10 17:42:56 -07005222
5223 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005224 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005225
5226 return muteWaitMs;
5227}
5228
Eric Laurentc75307b2015-03-17 15:29:32 -07005229status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 int delayMs,
5231 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005232{
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 ssize_t index;
5234 if (patchHandle) {
5235 index = mAudioPatches.indexOfKey(*patchHandle);
5236 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005237 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005238 }
5239 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005240 return INVALID_OPERATION;
5241 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5243 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005244 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005245 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 removeAudioPatch(patchDesc->mHandle);
5247 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005248 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005249 return status;
5250}
5251
5252status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5253 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 bool force,
5255 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005256{
5257 status_t status = NO_ERROR;
5258
Eric Laurent1f2f2232014-06-02 12:01:23 -07005259 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5261 inputDesc->mDevice = device;
5262
Mikhail Naganov708e0382018-05-30 09:53:04 -07005263 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005265 PatchBuilder patchBuilder;
5266 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005267 // AUDIO_SOURCE_HOTWORD is for internal use only:
5268 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005269 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5270 auto result = usecase;
5271 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5272 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5273 }
5274 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005276 addSource(deviceList.itemAt(0));
5277 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005278 }
5279 }
5280 return status;
5281}
5282
Eric Laurent6a94d692014-05-20 11:18:06 -07005283status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5284 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005285{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005286 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 ssize_t index;
5288 if (patchHandle) {
5289 index = mAudioPatches.indexOfKey(*patchHandle);
5290 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005291 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 }
5293 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 return INVALID_OPERATION;
5295 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5297 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005298 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005299 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 removeAudioPatch(patchDesc->mHandle);
5301 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005302 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005303 return status;
5304}
5305
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005306sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005307 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005308 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005309 audio_format_t& format,
5310 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005311 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005312{
5313 // Choose an input profile based on the requested capture parameters: select the first available
5314 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005315 //
5316 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5317 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005318
Glenn Kasten730b9262018-03-29 15:01:26 -07005319 sp<IOProfile> firstInexact;
5320 uint32_t updatedSamplingRate = 0;
5321 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5322 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005323 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005324 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005325 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005326 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005327 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005328 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005329 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005330 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005331 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005332 &channelMask /*updatedChannelMask*/,
5333 // FIXME ugly cast
5334 (audio_output_flags_t) flags,
5335 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005336 return profile;
5337 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005338 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5339 samplingRate,
5340 &updatedSamplingRate,
5341 format,
5342 &updatedFormat,
5343 channelMask,
5344 &updatedChannelMask,
5345 // FIXME ugly cast
5346 (audio_output_flags_t) flags,
5347 false /*exactMatchRequiredForInputFlags*/)) {
5348 firstInexact = profile;
5349 }
5350
Eric Laurente552edb2014-03-10 17:42:56 -07005351 }
5352 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005353 if (firstInexact != nullptr) {
5354 samplingRate = updatedSamplingRate;
5355 format = updatedFormat;
5356 channelMask = updatedChannelMask;
5357 return firstInexact;
5358 }
Eric Laurente552edb2014-03-10 17:42:56 -07005359 return NULL;
5360}
5361
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005362
5363audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005364 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005365{
François Gaffie036e1e92015-03-19 10:16:24 +01005366 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5367 audio_devices_t selectedDeviceFromMix =
5368 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005369
François Gaffie036e1e92015-03-19 10:16:24 +01005370 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5371 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005372 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005373 return getDeviceForInputSource(inputSource);
5374}
5375
5376audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5377{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005378 // Routing
5379 // Scan the whole RouteMap to see if we have an explicit route:
5380 // if the input source in the RouteMap is the same as the argument above,
5381 // and activity count is non-zero and the device in the route descriptor is available
5382 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005383 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5384 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005385 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005386 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005387 return route->mDeviceDescriptor->type();
5388 }
5389 }
5390
5391 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005392}
5393
Eric Laurente0720872014-03-11 09:30:41 -07005394float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005395 int index,
5396 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005397{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005398 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005399
5400 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5401 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5402 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5403 // the ringtone volume
5404 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5405 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5406 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5407 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5408 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5409 }
5410
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005411 // in-call: always cap volume by voice volume + some low headroom
5412 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005413 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005414 switch (stream) {
5415 case AUDIO_STREAM_SYSTEM:
5416 case AUDIO_STREAM_RING:
5417 case AUDIO_STREAM_MUSIC:
5418 case AUDIO_STREAM_ALARM:
5419 case AUDIO_STREAM_NOTIFICATION:
5420 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5421 case AUDIO_STREAM_DTMF:
5422 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005423 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005424 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005425 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005426 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005427 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005428 if (volumeDB > maxVoiceVolDb) {
5429 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5430 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5431 volumeDB = maxVoiceVolDb;
5432 }
5433 } break;
5434 default:
5435 break;
5436 }
5437 }
5438
Eric Laurente552edb2014-03-10 17:42:56 -07005439 // if a headset is connected, apply the following rules to ring tones and notifications
5440 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005441 // - always attenuate notifications volume by 6dB
5442 // - attenuate ring tones volume by 6dB unless music is not playing and
5443 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005444 // - if music is playing, always limit the volume to current music volume,
5445 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005446 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005447 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5448 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5449 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005450 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005451 AUDIO_DEVICE_OUT_USB_HEADSET |
5452 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005453 ((stream_strategy == STRATEGY_SONIFICATION)
5454 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005455 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005456 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005457 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005458 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005459 // when the phone is ringing we must consider that music could have been paused just before
5460 // by the music application and behave as if music was active if the last music track was
5461 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005462 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005463 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005464 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005465 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005466 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005467 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5468 musicDevice),
5469 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005470 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5471 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005472 if (volumeDB > minVolDB) {
5473 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005474 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005475 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005476 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5477 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5478 // on A2DP, also ensure notification volume is not too low compared to media when
5479 // intended to be played
5480 if ((volumeDB > -96.0f) &&
5481 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5482 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5483 stream, device,
5484 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5485 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5486 }
5487 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005488 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5489 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005490 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005491 }
5492 }
5493
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005494 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005495}
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005498 int index,
5499 const sp<AudioOutputDescriptor>& outputDesc,
5500 audio_devices_t device,
5501 int delayMs,
5502 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005503{
Eric Laurente552edb2014-03-10 17:42:56 -07005504 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005505 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005506 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005507 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005508 return NO_ERROR;
5509 }
François Gaffie2110e042015-03-24 08:41:51 +01005510 audio_policy_forced_cfg_t forceUseForComm =
5511 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005512 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005513 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5514 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005515 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005516 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005517 return INVALID_OPERATION;
5518 }
5519
Eric Laurentc75307b2015-03-17 15:29:32 -07005520 if (device == AUDIO_DEVICE_NONE) {
5521 device = outputDesc->device();
5522 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005523
Eric Laurentffbc80f2015-03-18 18:30:19 -07005524 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005525 if (outputDesc->isFixedVolume(device) ||
5526 // Force VoIP volume to max for bluetooth SCO
5527 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5528 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005529 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005530 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005531
Eric Laurentffbc80f2015-03-18 18:30:19 -07005532 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005533
Eric Laurent3b73df72014-03-11 09:06:29 -07005534 if (stream == AUDIO_STREAM_VOICE_CALL ||
5535 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 float voiceVolume;
5537 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005538 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005539 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005540 } else {
5541 voiceVolume = 1.0;
5542 }
5543
Eric Laurent18fba842016-03-31 14:41:26 -07005544 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005545 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5546 mLastVoiceVolume = voiceVolume;
5547 }
5548 }
5549
5550 return NO_ERROR;
5551}
5552
Eric Laurentc75307b2015-03-17 15:29:32 -07005553void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5554 audio_devices_t device,
5555 int delayMs,
5556 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005557{
Eric Laurentc75307b2015-03-17 15:29:32 -07005558 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005559
Eric Laurent794fde22016-03-11 09:50:45 -08005560 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005561 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005562 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005564 device,
5565 delayMs,
5566 force);
5567 }
5568}
5569
Eric Laurente0720872014-03-11 09:30:41 -07005570void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005571 bool on,
5572 const sp<AudioOutputDescriptor>& outputDesc,
5573 int delayMs,
5574 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005575{
Eric Laurent72249d52015-06-08 11:12:15 -07005576 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5577 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005578 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005579 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005580 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005581 }
5582 }
5583}
5584
Eric Laurente0720872014-03-11 09:30:41 -07005585void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005586 bool on,
5587 const sp<AudioOutputDescriptor>& outputDesc,
5588 int delayMs,
5589 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005590{
Eric Laurente552edb2014-03-10 17:42:56 -07005591 if (device == AUDIO_DEVICE_NONE) {
5592 device = outputDesc->device();
5593 }
5594
Eric Laurentc75307b2015-03-17 15:29:32 -07005595 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5596 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005597
5598 if (on) {
5599 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005600 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005601 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005602 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005603 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005604 }
5605 }
5606 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5607 outputDesc->mMuteCount[stream]++;
5608 } else {
5609 if (outputDesc->mMuteCount[stream] == 0) {
5610 ALOGV("setStreamMute() unmuting non muted stream!");
5611 return;
5612 }
5613 if (--outputDesc->mMuteCount[stream] == 0) {
5614 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005615 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005617 device,
5618 delayMs);
5619 }
5620 }
5621}
5622
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005623audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5624{
5625 // flags to stream type mapping
5626 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5627 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5628 }
5629 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5630 return AUDIO_STREAM_BLUETOOTH_SCO;
5631 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005632 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5633 return AUDIO_STREAM_TTS;
5634 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005635
5636 // usage to stream type mapping
5637 switch (attr->usage) {
5638 case AUDIO_USAGE_MEDIA:
5639 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005640 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005641 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5642 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005643 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5644 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005645 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5646 return AUDIO_STREAM_SYSTEM;
5647 case AUDIO_USAGE_VOICE_COMMUNICATION:
5648 return AUDIO_STREAM_VOICE_CALL;
5649
5650 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5651 return AUDIO_STREAM_DTMF;
5652
5653 case AUDIO_USAGE_ALARM:
5654 return AUDIO_STREAM_ALARM;
5655 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5656 return AUDIO_STREAM_RING;
5657
5658 case AUDIO_USAGE_NOTIFICATION:
5659 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5660 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5661 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5662 case AUDIO_USAGE_NOTIFICATION_EVENT:
5663 return AUDIO_STREAM_NOTIFICATION;
5664
5665 case AUDIO_USAGE_UNKNOWN:
5666 default:
5667 return AUDIO_STREAM_MUSIC;
5668 }
5669}
Eric Laurente83b55d2014-11-14 10:06:21 -08005670
François Gaffie53615e22015-03-19 09:24:12 +01005671bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5672{
Eric Laurente83b55d2014-11-14 10:06:21 -08005673 // has flags that map to a strategy?
5674 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5675 return true;
5676 }
5677
5678 // has known usage?
5679 switch (paa->usage) {
5680 case AUDIO_USAGE_UNKNOWN:
5681 case AUDIO_USAGE_MEDIA:
5682 case AUDIO_USAGE_VOICE_COMMUNICATION:
5683 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5684 case AUDIO_USAGE_ALARM:
5685 case AUDIO_USAGE_NOTIFICATION:
5686 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5687 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5688 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5689 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5690 case AUDIO_USAGE_NOTIFICATION_EVENT:
5691 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5692 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5693 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5694 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005695 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005696 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005697 break;
5698 default:
5699 return false;
5700 }
5701 return true;
5702}
5703
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005704bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005705 routing_strategy strategy, uint32_t inPastMs,
5706 nsecs_t sysTime) const
5707{
5708 if ((sysTime == 0) && (inPastMs != 0)) {
5709 sysTime = systemTime();
5710 }
Eric Laurent794fde22016-03-11 09:50:45 -08005711 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005712 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5713 (NUM_STRATEGIES == strategy)) &&
5714 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5715 return true;
5716 }
5717 }
5718 return false;
5719}
5720
Eric Laurent484e9272018-06-07 17:29:23 -07005721bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5722 routing_strategy strategy, uint32_t inPastMs,
5723 nsecs_t sysTime) const
5724{
5725 for (size_t i = 0; i < mOutputs.size(); i++) {
5726 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5727 if (outputDesc->sharesHwModuleWith(desc)
5728 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5729 return true;
5730 }
5731 }
5732 return false;
5733}
5734
François Gaffie2110e042015-03-24 08:41:51 +01005735audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5736{
5737 return mEngine->getForceUse(usage);
5738}
5739
5740bool AudioPolicyManager::isInCall()
5741{
5742 return isStateInCall(mEngine->getPhoneState());
5743}
5744
5745bool AudioPolicyManager::isStateInCall(int state)
5746{
5747 return is_state_in_call(state);
5748}
5749
Eric Laurentd60560a2015-04-10 11:31:20 -07005750void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5751{
5752 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5753 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5754 if (sourceDesc->mDevice->equals(deviceDesc)) {
5755 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5756 stopAudioSource(sourceDesc->getHandle());
5757 }
5758 }
5759
5760 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5761 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5762 bool release = false;
5763 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5764 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5765 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5766 source->ext.device.type == deviceDesc->type()) {
5767 release = true;
5768 }
5769 }
5770 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5771 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5772 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5773 sink->ext.device.type == deviceDesc->type()) {
5774 release = true;
5775 }
5776 }
5777 if (release) {
5778 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5779 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5780 }
5781 }
5782}
5783
Phil Burk09bc4612016-02-24 15:58:15 -08005784// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005785void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5786 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005787 // TODO Set this based on Config properties.
5788 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005789
5790 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5791 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005792 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005793
jiabin81772902018-04-02 17:52:27 -07005794 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5795 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5796 formats.clear();
5797 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5798 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005799 }
jiabin81772902018-04-02 17:52:27 -07005800 // Always enable IEC61937 when in MANUAL mode.
5801 formats.add(AUDIO_FORMAT_IEC61937);
5802 } else { // NEVER, AUTO or ALWAYS
5803 // Analyze original support for various formats.
5804 bool supportsAC3 = false;
5805 bool supportsOtherSurround = false;
5806 bool supportsIEC61937 = false;
5807 mSurroundFormats.clear();
5808 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5809 audio_format_t format = formats[formatIndex];
5810 switch (format) {
5811 case AUDIO_FORMAT_AC3:
5812 supportsAC3 = true;
5813 break;
5814 case AUDIO_FORMAT_E_AC3:
5815 case AUDIO_FORMAT_DTS:
5816 case AUDIO_FORMAT_DTS_HD:
5817 // If ALWAYS, remove all other surround formats here
5818 // since we will add them later.
5819 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5820 formats.removeAt(formatIndex);
5821 formatIndex--;
5822 }
5823 supportsOtherSurround = true;
5824 break;
5825 case AUDIO_FORMAT_IEC61937:
5826 supportsIEC61937 = true;
5827 break;
5828 default:
5829 break;
5830 }
5831 }
Phil Burk09bc4612016-02-24 15:58:15 -08005832
jiabin81772902018-04-02 17:52:27 -07005833 // Modify formats based on surround preferences.
5834 // If NEVER, remove support for surround formats.
5835 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5836 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5837 // Remove surround sound related formats.
5838 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5839 audio_format_t format = formats[formatIndex];
5840 switch(format) {
5841 case AUDIO_FORMAT_AC3:
5842 case AUDIO_FORMAT_E_AC3:
5843 case AUDIO_FORMAT_DTS:
5844 case AUDIO_FORMAT_DTS_HD:
5845 case AUDIO_FORMAT_IEC61937:
5846 formats.removeAt(formatIndex);
5847 break;
5848 default:
5849 formatIndex++; // keep it
5850 break;
5851 }
5852 }
5853 supportsAC3 = false;
5854 supportsOtherSurround = false;
5855 supportsIEC61937 = false;
5856 }
5857 } else { // AUTO or ALWAYS
5858 // Most TVs support AC3 even if they do not report it in the EDID.
5859 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5860 && !supportsAC3) {
5861 formats.add(AUDIO_FORMAT_AC3);
5862 supportsAC3 = true;
5863 }
5864
5865 // If ALWAYS, add support for raw surround formats if all are missing.
5866 // This assumes that if any of these formats are reported by the HAL
5867 // then the report is valid and should not be modified.
5868 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5869 formats.add(AUDIO_FORMAT_E_AC3);
5870 formats.add(AUDIO_FORMAT_DTS);
5871 formats.add(AUDIO_FORMAT_DTS_HD);
5872 supportsOtherSurround = true;
5873 }
5874
5875 // Add support for IEC61937 if any raw surround supported.
5876 // The HAL could do this but add it here, just in case.
5877 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5878 formats.add(AUDIO_FORMAT_IEC61937);
5879 supportsIEC61937 = true;
5880 }
5881
5882 // Add reported surround sound formats to enabled surround formats.
5883 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005884 audio_format_t format = formats[formatIndex];
5885 switch(format) {
5886 case AUDIO_FORMAT_AC3:
5887 case AUDIO_FORMAT_E_AC3:
5888 case AUDIO_FORMAT_DTS:
5889 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005890 case AUDIO_FORMAT_AAC_LC:
5891 case AUDIO_FORMAT_DOLBY_TRUEHD:
5892 case AUDIO_FORMAT_E_AC3_JOC:
5893 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005894 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005895 break;
5896 }
Phil Burk09bc4612016-02-24 15:58:15 -08005897 }
Phil Burk07ac1142016-03-25 13:39:29 -07005898 }
Phil Burk09bc4612016-02-24 15:58:15 -08005899 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005900}
5901
5902// Modify the list of channel masks supported.
5903void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5904 ChannelsVector &channelMasks = *channelMasksPtr;
5905 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5906 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5907
5908 // If NEVER, then remove support for channelMasks > stereo.
5909 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5910 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5911 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5912 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5913 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5914 channelMasks.removeAt(maskIndex);
5915 } else {
5916 maskIndex++;
5917 }
5918 }
jiabin81772902018-04-02 17:52:27 -07005919 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5920 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5921 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005922 bool supports5dot1 = false;
5923 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005924 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005925 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5926 supports5dot1 = true;
5927 break;
5928 }
5929 }
5930 // If not then add 5.1 support.
5931 if (!supports5dot1) {
5932 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5933 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5934 }
Phil Burk09bc4612016-02-24 15:58:15 -08005935 }
5936}
5937
Phil Burk00eeb322016-03-31 12:41:00 -07005938void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5939 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005940 AudioProfileVector &profiles)
5941{
5942 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005943
François Gaffie112b0af2015-11-19 16:13:25 +01005944 // Format MUST be checked first to update the list of AudioProfile
5945 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005946 reply = mpClientInterface->getParameters(
5947 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005948 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005949 AudioParameter repliedParameters(reply);
5950 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005951 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005952 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5953 return;
5954 }
Phil Burk09bc4612016-02-24 15:58:15 -08005955 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005956 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005957 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005958 }
Phil Burk09bc4612016-02-24 15:58:15 -08005959 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005960 }
François Gaffie112b0af2015-11-19 16:13:25 +01005961
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005962 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005963 ChannelsVector channelMasks;
5964 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005965 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005966 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005967
5968 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005969 reply = mpClientInterface->getParameters(
5970 ioHandle,
5971 requestedParameters.toString() + ";" +
5972 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005973 ALOGV("%s: supported sampling rates %s", __FUNCTION__, 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::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005977 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005978 }
5979 }
5980 if (profiles.hasDynamicChannelsFor(format)) {
5981 reply = mpClientInterface->getParameters(ioHandle,
5982 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005983 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005984 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005985 AudioParameter repliedParameters(reply);
5986 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005987 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005988 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005989 if (device == AUDIO_DEVICE_OUT_HDMI) {
5990 filterSurroundChannelMasks(&channelMasks);
5991 }
François Gaffie112b0af2015-11-19 16:13:25 +01005992 }
5993 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005994 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005995 }
5996}
Eric Laurentd60560a2015-04-10 11:31:20 -07005997
Mikhail Naganovdc769682018-05-04 15:34:08 -07005998status_t AudioPolicyManager::installPatch(const char *caller,
5999 audio_patch_handle_t *patchHandle,
6000 AudioIODescriptorInterface *ioDescriptor,
6001 const struct audio_patch *patch,
6002 int delayMs)
6003{
6004 ssize_t index = mAudioPatches.indexOfKey(
6005 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6006 *patchHandle : ioDescriptor->getPatchHandle());
6007 sp<AudioPatch> patchDesc;
6008 status_t status = installPatch(
6009 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6010 if (status == NO_ERROR) {
6011 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6012 }
6013 return status;
6014}
6015
6016status_t AudioPolicyManager::installPatch(const char *caller,
6017 ssize_t index,
6018 audio_patch_handle_t *patchHandle,
6019 const struct audio_patch *patch,
6020 int delayMs,
6021 uid_t uid,
6022 sp<AudioPatch> *patchDescPtr)
6023{
6024 sp<AudioPatch> patchDesc;
6025 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6026 if (index >= 0) {
6027 patchDesc = mAudioPatches.valueAt(index);
6028 afPatchHandle = patchDesc->mAfPatchHandle;
6029 }
6030
6031 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6032 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6033 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6034 if (status == NO_ERROR) {
6035 if (index < 0) {
6036 patchDesc = new AudioPatch(patch, uid);
6037 addAudioPatch(patchDesc->mHandle, patchDesc);
6038 } else {
6039 patchDesc->mPatch = *patch;
6040 }
6041 patchDesc->mAfPatchHandle = afPatchHandle;
6042 if (patchHandle) {
6043 *patchHandle = patchDesc->mHandle;
6044 }
6045 nextAudioPortGeneration();
6046 mpClientInterface->onAudioPatchListUpdate();
6047 }
6048 if (patchDescPtr) *patchDescPtr = patchDesc;
6049 return status;
6050}
6051
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006052} // namespace android