blob: 5cdd63aa04e0f761cccca289dffd1411facded2d [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
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700798 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
799 " session %d selectedDeviceId %d",
800 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700801 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700802
Scott Randolph7b1fd232018-06-18 15:33:03 -0700803 // TODO: check for existing client for this port ID
804 if (*portId == AUDIO_PORT_HANDLE_NONE) {
805 *portId = AudioPort::getNextUniqueId();
806 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700807
Scott Randolph7b1fd232018-06-18 15:33:03 -0700808 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700809 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700810 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800811 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700812 } else {
813 // If no explict route, is there a matching dynamic policy that applies?
814 sp<SwAudioOutputDescriptor> desc;
815 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
816 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
817 if (!audio_has_proportional_frames(config->format)) {
818 return BAD_VALUE;
819 }
820 *stream = streamTypefromAttributesInt(&attributes);
821 *output = desc->mIoHandle;
822 ALOGV("getOutputForAttr() returns output %d", *output);
823 return NO_ERROR;
824 }
825
826 // Virtual sources must always be dynamicaly or explicitly routed
827 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
828 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
829 return BAD_VALUE;
830 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700831 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700832
833 // Virtual sources must always be dynamicaly or explicitly routed
834 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
835 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
836 return BAD_VALUE;
837 }
838
839 *stream = streamTypefromAttributesInt(&attributes);
840
841 // TODO: Should this happen only if an explicit route is active?
842 // the previous code structure meant that this would always happen which
843 // would appear to result in adding a null deviceDesc when not using an
844 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700845 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200851 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852 }
853
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800854 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
855 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200856 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857
Andy Hungc88b0642018-04-27 15:42:35 -0700858 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800859 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700860 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800861 return INVALID_OPERATION;
862 }
Paul McLeanaa981192015-03-21 09:55:15 -0700863
Mikhail Naganov708e0382018-05-30 09:53:04 -0700864 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700865 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
866 : AUDIO_PORT_HANDLE_NONE;
867
868 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
869
Eric Laurente83b55d2014-11-14 10:06:21 -0800870 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871}
872
873audio_io_handle_t AudioPolicyManager::getOutputForDevice(
874 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800875 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800877 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200878 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879{
Andy Hungc88b0642018-04-27 15:42:35 -0700880 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700881 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882
Eric Laurente552edb2014-03-10 17:42:56 -0700883 // open a direct output if required by specified parameters
884 //force direct flag if offload flag is set: offloading implies a direct output stream
885 // and all common behaviors are driven by checking only the direct flag
886 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200887 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
888 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
Nadav Bar766fb022018-01-07 12:18:03 +0200890 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
891 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700892 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 // only allow deep buffering for music stream type
894 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200895 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700896 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200897 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700898 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
899 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200900 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700902 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200903 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700904 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800905 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200906 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700907 AUDIO_OUTPUT_FLAG_DIRECT);
908 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200909 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
910 stream == AUDIO_STREAM_MUSIC &&
911 audio_is_linear_pcm(config->format) &&
912 isInCall()) {
913 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700914 }
Eric Laurente552edb2014-03-10 17:42:56 -0700915
Nadav Bar766fb022018-01-07 12:18:03 +0200916
Eric Laurentb732cf52014-09-24 19:08:21 -0700917 sp<IOProfile> profile;
918
919 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700920 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200921 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800922 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
923 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700924 goto non_direct_output;
925 }
926
Andy Hung2ddee192015-12-18 17:34:44 -0800927 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
928 // This prevents creating an offloaded track and tearing it down immediately after start
929 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700930 // FIXME: We should check the audio session here but we do not have it in this context.
931 // This may prevent offloading in rare situations where effects are left active by apps
932 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700933
Nadav Bar766fb022018-01-07 12:18:03 +0200934 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800935 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700936 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800937 config->sample_rate,
938 config->format,
939 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200940 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942
Eric Laurent1c333e22014-05-20 10:48:17 -0700943 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700944 // exclusive outputs for MMAP and Offload are enforced by different session ids.
945 for (size_t i = 0; i < mOutputs.size(); i++) {
946 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
947 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
948 // reuse direct output if currently open by the same client
949 // and configured with same parameters
950 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700951 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700952 (config->channel_mask == desc->mChannelMask) &&
953 (session == desc->mDirectClientSession)) {
954 desc->mDirectOpenCount++;
955 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
956 mOutputs.keyAt(i), session);
957 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700958 }
959 }
960 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800961
962 if (!profile->canOpenNewIo()) {
963 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700964 }
Eric Laurent861a6282015-05-18 15:40:16 -0700965
Eric Laurent3974e3b2017-12-07 17:58:43 -0800966 sp<SwAudioOutputDescriptor> outputDesc =
967 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800968
Mikhail Naganov708e0382018-05-30 09:53:04 -0700969 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800970 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
971 : String8("");
972
Nadav Bar766fb022018-01-07 12:18:03 +0200973 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700974
975 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700976 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800977 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700978 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800979 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
980 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
981 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
982 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
983 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800985 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700986 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800987 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800988 if (audio_is_linear_pcm(config->format) &&
989 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800990 goto non_direct_output;
991 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700992 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700993 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700994 outputDesc->mRefCount[stream] = 0;
995 outputDesc->mStopTime[stream] = 0;
996 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800997 outputDesc->mDirectClientSession = session;
998
Eric Laurente552edb2014-03-10 17:42:56 -0700999 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001000 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001001 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001002 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001003 return output;
1004 }
1005
Eric Laurentb732cf52014-09-24 19:08:21 -07001006non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001007
1008 // A request for HW A/V sync cannot fallback to a mixed output because time
1009 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001010 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001011 return AUDIO_IO_HANDLE_NONE;
1012 }
1013
Eric Laurente552edb2014-03-10 17:42:56 -07001014 // ignoring channel mask due to downmix capability in mixer
1015
1016 // open a non direct output
1017
1018 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001019 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001020 // get which output is suitable for the specified stream. The actual
1021 // routing change will happen when startOutput() will be called
1022 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1023
Eric Laurent8838a382014-09-08 16:44:28 -07001024 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001025 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1026 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001028 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001029 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001030 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001031
Eric Laurente552edb2014-03-10 17:42:56 -07001032 return output;
1033}
1034
Eric Laurente0720872014-03-11 09:30:41 -07001035audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001036 audio_output_flags_t flags,
1037 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001038{
1039 // select one output among several that provide a path to a particular device or set of
1040 // devices (the list was previously build by getOutputsForDevice()).
1041 // The priority is as follows:
1042 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001043 // 2: the output with the bit depth the closest to the requested one
1044 // 3: the primary output
1045 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001046
1047 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001048 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
1050 if (outputs.size() == 1) {
1051 return outputs[0];
1052 }
1053
1054 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001055 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1056 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1057 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001058 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1059 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001060
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001061 for (audio_io_handle_t output : outputs) {
1062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001063 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001064 // if a valid format is specified, skip output if not compatible
1065 if (format != AUDIO_FORMAT_INVALID) {
1066 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001067 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001068 continue;
1069 }
1070 } else if (!audio_is_linear_pcm(format)) {
1071 continue;
1072 }
Eric Laurente6930022016-02-11 10:20:40 -08001073 if (AudioPort::isBetterFormatMatch(
1074 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001075 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001076 bestFormat = outputDesc->mFormat;
1077 }
Eric Laurent8838a382014-09-08 16:44:28 -07001078 }
1079
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001080 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001081 if (commonFlags >= maxCommonFlags) {
1082 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001083 if (format != AUDIO_FORMAT_INVALID
1084 && AudioPort::isBetterFormatMatch(
1085 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001086 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001087 bestFormatForFlags = outputDesc->mFormat;
1088 }
1089 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001090 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001091 maxCommonFlags = commonFlags;
1092 bestFormatForFlags = outputDesc->mFormat;
1093 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001094 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001096 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001097 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001098 }
1099 }
1100 }
1101
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001102 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001103 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001104 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001105 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001106 return outputForFormat;
1107 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001108 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001109 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001110 }
1111
1112 return outputs[0];
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001116 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001117 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001118{
Paul McLeanaa981192015-03-21 09:55:15 -07001119 ALOGV("startOutput() output %d, stream %d, session %d",
1120 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001121 ssize_t index = mOutputs.indexOfKey(output);
1122 if (index < 0) {
1123 ALOGW("startOutput() unknown output %d", output);
1124 return BAD_VALUE;
1125 }
1126
Eric Laurentc75307b2015-03-17 15:29:32 -07001127 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1128
Eric Laurent733ce942017-12-07 12:18:25 -08001129 status_t status = outputDesc->start();
1130 if (status != NO_ERROR) {
1131 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001132 }
1133
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001134 // Routing?
1135 mOutputRoutes.incRouteActivity(session);
1136
Eric Laurentc75307b2015-03-17 15:29:32 -07001137 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001138 AudioMix *policyMix = NULL;
1139 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001140 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001141 policyMix = outputDesc->mPolicyMix;
1142 address = policyMix->mDeviceAddress.string();
1143 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1144 newDevice = policyMix->mDeviceType;
1145 } else {
1146 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1147 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001148 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001149 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001150 if (newDevice != outputDesc->device()) {
1151 checkStrategyRoute(getStrategy(stream), output);
1152 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 } else {
1154 newDevice = AUDIO_DEVICE_NONE;
1155 }
1156
1157 uint32_t delayMs = 0;
1158
Eric Laurent733ce942017-12-07 12:18:25 -08001159 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001160
1161 if (status != NO_ERROR) {
1162 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001163 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001164 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 }
1166 // Automatically enable the remote submix input when output is started on a re routing mix
1167 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001168 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1169 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1171 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001172 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 "remote-submix");
1174 }
1175
1176 if (delayMs != 0) {
1177 usleep(delayMs * 1000);
1178 }
1179
1180 return status;
1181}
1182
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001183status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 audio_stream_type_t stream,
1185 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001186 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001187 uint32_t *delayMs)
1188{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001189 // cannot start playback of STREAM_TTS if any other output is being used
1190 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001191
1192 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001193 if (stream == AUDIO_STREAM_TTS) {
1194 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001195 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001196 return INVALID_OPERATION;
1197 } else {
1198 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1199 }
1200 } else {
1201 // some playback other than beacon starts
1202 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1203 }
1204
Eric Laurent77305a62016-07-25 16:39:22 -07001205 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001206 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001207 bool force = !outputDesc->isActive() &&
1208 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001209
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001210 // requiresMuteCheck is false when we can bypass mute strategy.
1211 // It covers a common case when there is no materially active audio
1212 // and muting would result in unnecessary delay and dropped audio.
1213 const uint32_t outputLatencyMs = outputDesc->latency();
1214 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1215
Eric Laurente552edb2014-03-10 17:42:56 -07001216 // increment usage count for this stream on the requested output:
1217 // NOTE that the usage count is the same for duplicated output and hardware output which is
1218 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1219 outputDesc->changeRefCount(stream, 1);
1220
Eric Laurent36829f92017-04-07 19:04:42 -07001221 if (stream == AUDIO_STREAM_MUSIC) {
1222 selectOutputForMusicEffects();
1223 }
1224
Eric Laurent493404d2015-04-21 15:07:36 -07001225 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001226 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001227 if (device == AUDIO_DEVICE_NONE) {
1228 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001229 }
Eric Laurent36829f92017-04-07 19:04:42 -07001230
Eric Laurente552edb2014-03-10 17:42:56 -07001231 routing_strategy strategy = getStrategy(stream);
1232 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001233 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1234 (beaconMuteLatency > 0);
1235 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001236 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001237 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001238 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001239 // An output has a shared device if
1240 // - managed by the same hw module
1241 // - supports the currently selected device
1242 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1243 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1244
Eric Laurent77305a62016-07-25 16:39:22 -07001245 // force a device change if any other output is:
1246 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001247 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001248 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001249 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001250 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001251 // change the device currently selected by the other output.
1252 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001253 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001254 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001255 force = true;
1256 }
1257 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001258 // a notification so that audio focus effect can propagate, or that a mute/unmute
1259 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001260 const uint32_t latencyMs = desc->latency();
1261 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1262
1263 if (shouldWait && isActive && (waitMs < latencyMs)) {
1264 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001265 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001266
1267 // Require mute check if another output is on a shared device
1268 // and currently active to have proper drain and avoid pops.
1269 // Note restoring AudioTracks onto this output needs to invoke
1270 // a volume ramp if there is no mute.
1271 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001272 }
1273 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001274
1275 const uint32_t muteWaitMs =
1276 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001277
Eric Laurente552edb2014-03-10 17:42:56 -07001278 // apply volume rules for current stream and device if necessary
1279 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001280 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001281 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001282 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001283
1284 // update the outputs if starting an output with a stream that can affect notification
1285 // routing
1286 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001287
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001288 // force reevaluating accessibility routing when ringtone or alarm starts
1289 if (strategy == STRATEGY_SONIFICATION) {
1290 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1291 }
Eric Laurentdc462862016-07-19 12:29:53 -07001292
1293 if (waitMs > muteWaitMs) {
1294 *delayMs = waitMs - muteWaitMs;
1295 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001296
1297 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1298 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1299 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1300 // change occurs after the MixerThread starts and causes a stream volume
1301 // glitch.
1302 //
1303 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
Eric Laurentdc462862016-07-19 12:29:53 -07001305
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001306 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1307 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1308 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1309 }
1310
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001311 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1312 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1313 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1314 }
1315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 return NO_ERROR;
1317}
1318
1319
Eric Laurente0720872014-03-11 09:30:41 -07001320status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001321 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001322 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001323{
1324 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1325 ssize_t index = mOutputs.indexOfKey(output);
1326 if (index < 0) {
1327 ALOGW("stopOutput() unknown output %d", output);
1328 return BAD_VALUE;
1329 }
1330
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001332
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 if (outputDesc->mRefCount[stream] == 1) {
1334 // Automatically disable the remote submix input when output is stopped on a
1335 // re routing mix of type MIX_TYPE_RECORDERS
1336 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1337 outputDesc->mPolicyMix != NULL &&
1338 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1339 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1340 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001341 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001342 "remote-submix");
1343 }
1344 }
1345
1346 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001347 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001348 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 int activityCount = mOutputRoutes.decRouteActivity(session);
1350 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1351
1352 if (forceDeviceUpdate) {
1353 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1354 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001355 }
1356
Eric Laurent3974e3b2017-12-07 17:58:43 -08001357 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1358
Eric Laurent733ce942017-12-07 12:18:25 -08001359 if (status == NO_ERROR ) {
1360 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001361 }
1362 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001363}
1364
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001365status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001366 audio_stream_type_t stream,
1367 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001368{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001369 // always handle stream stop, check which stream type is stopping
1370 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1371
Eric Laurente552edb2014-03-10 17:42:56 -07001372 if (outputDesc->mRefCount[stream] > 0) {
1373 // decrement usage count of this stream on the output
1374 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001375
Eric Laurente552edb2014-03-10 17:42:56 -07001376 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001377 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001378 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001380 // delay the device switch by twice the latency because stopOutput() is executed when
1381 // the track stop() command is received and at that time the audio track buffer can
1382 // still contain data that needs to be drained. The latency only covers the audio HAL
1383 // and kernel buffers. Also the latency does not always include additional delay in the
1384 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001386
1387 // force restoring the device selection on other active outputs if it differs from the
1388 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001389 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001390 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001391 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001392 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001393 desc->isActive() &&
1394 outputDesc->sharesHwModuleWith(desc) &&
1395 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001396 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1397 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001398
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001400 newDevice2,
1401 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001402 delayMs);
1403 // re-apply device specific volume if not done by setOutputDevice()
1404 if (!force) {
1405 applyStreamVolumes(desc, newDevice2, delayMs);
1406 }
Eric Laurente552edb2014-03-10 17:42:56 -07001407 }
1408 }
1409 // update the outputs if stopping one with a stream that can affect notification routing
1410 handleNotificationRoutingForStream(stream);
1411 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001412
1413 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1414 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1415 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1416 }
1417
Eric Laurent36829f92017-04-07 19:04:42 -07001418 if (stream == AUDIO_STREAM_MUSIC) {
1419 selectOutputForMusicEffects();
1420 }
Eric Laurente552edb2014-03-10 17:42:56 -07001421 return NO_ERROR;
1422 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001424 return INVALID_OPERATION;
1425 }
1426}
1427
Eric Laurente83b55d2014-11-14 10:06:21 -08001428void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001429 audio_stream_type_t stream __unused,
1430 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001431{
1432 ALOGV("releaseOutput() %d", output);
1433 ssize_t index = mOutputs.indexOfKey(output);
1434 if (index < 0) {
1435 ALOGW("releaseOutput() releasing unknown output %d", output);
1436 return;
1437 }
1438
Paul McLeanaa981192015-03-21 09:55:15 -07001439 // Routing
1440 mOutputRoutes.removeRoute(session);
1441
Eric Laurentc75307b2015-03-17 15:29:32 -07001442 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001443 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001444 if (desc->mDirectOpenCount <= 0) {
1445 ALOGW("releaseOutput() invalid open count %d for output %d",
1446 desc->mDirectOpenCount, output);
1447 return;
1448 }
1449 if (--desc->mDirectOpenCount == 0) {
1450 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001452 }
1453 }
1454}
1455
1456
Eric Laurentcaf7f482014-11-25 17:50:47 -08001457status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1458 audio_io_handle_t *input,
1459 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001460 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001461 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001462 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001463 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001464 input_type_t *inputType,
1465 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001466{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001467 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001468 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001469 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001470
Eric Laurentad2e7b92017-09-14 20:06:42 -07001471 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001472 // handle legacy remote submix case where the address was not always specified
1473 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001474 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001475 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001476 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001477 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001478
Eric Laurentfe231122017-11-17 17:48:06 -08001479 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1480 inputSource = AUDIO_SOURCE_MIC;
1481 }
1482
Paul McLean466dc8e2015-04-17 13:15:36 -06001483 // Explicit routing?
1484 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001485 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001486 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001487 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001488 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001489
Eric Laurentad2e7b92017-09-14 20:06:42 -07001490 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1491 // possible
1492 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1493 *input != AUDIO_IO_HANDLE_NONE) {
1494 ssize_t index = mInputs.indexOfKey(*input);
1495 if (index < 0) {
1496 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1497 status = BAD_VALUE;
1498 goto error;
1499 }
1500 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1501 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1502 if (audioSession == 0) {
1503 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1504 status = BAD_VALUE;
1505 goto error;
1506 }
1507 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1508 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001509 // corresponds to a new client and is only permitted from the same UID.
1510 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001511 if (audioSession->openCount() == 1) {
1512 audioSession->setUid(uid);
1513 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001514 if (!audioSession->isSilenced()) {
1515 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1516 uid, session, audioSession->uid());
1517 status = INVALID_OPERATION;
1518 goto error;
1519 }
1520 audioSession->setUid(uid);
1521 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001522 }
1523 audioSession->changeOpenCount(1);
1524 *inputType = API_INPUT_LEGACY;
1525 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1526 *portId = AudioPort::getNextUniqueId();
1527 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001528 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001529 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1530 : AUDIO_PORT_HANDLE_NONE;
1531 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1532
1533 return NO_ERROR;
1534 }
1535
1536 *input = AUDIO_IO_HANDLE_NONE;
1537 *inputType = API_INPUT_INVALID;
1538
Eric Laurentad2e7b92017-09-14 20:06:42 -07001539 halInputSource = inputSource;
1540
1541 // TODO: check for existing client for this port ID
1542 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1543 *portId = AudioPort::getNextUniqueId();
1544 }
1545
1546 audio_devices_t device;
1547
Eric Laurentc447ded2015-01-06 08:47:05 -08001548 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001549 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001550 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1551 if (status != NO_ERROR) {
1552 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001553 }
1554 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001555 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1556 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001557 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001558 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001559 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001560 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001561 status = BAD_VALUE;
1562 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001563 }
Eric Laurentc722f302014-12-10 11:21:49 -08001564 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001565 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001566 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1567 // there is an external policy, but this input is attached to a mix of recorders,
1568 // meaning it receives audio injected into the framework, so the recorder doesn't
1569 // know about it and is therefore considered "legacy"
1570 *inputType = API_INPUT_LEGACY;
1571 } else {
1572 // recording a mix of players defined by an external policy, we're rerouting for
1573 // an external policy
1574 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1575 }
Eric Laurentc722f302014-12-10 11:21:49 -08001576 } else if (audio_is_remote_submix_device(device)) {
1577 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001578 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001579 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1580 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001581 } else {
1582 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001583 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001584
Eric Laurent599c7582015-12-07 18:05:55 -08001585 }
1586
1587 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001588 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001589 policyMix);
1590 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001591 status = INVALID_OPERATION;
1592 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001593 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001594
Mikhail Naganov708e0382018-05-30 09:53:04 -07001595 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001596 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1597 : AUDIO_PORT_HANDLE_NONE;
1598
1599 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1600 *input, *inputType, *selectedDeviceId);
1601
Eric Laurent599c7582015-12-07 18:05:55 -08001602 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001603
1604error:
1605 mInputRoutes.removeRoute(session);
1606 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001607}
1608
1609
1610audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1611 String8 address,
1612 audio_session_t session,
1613 uid_t uid,
1614 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001615 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001616 audio_input_flags_t flags,
1617 AudioMix *policyMix)
1618{
1619 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1620 audio_source_t halInputSource = inputSource;
1621 bool isSoundTrigger = false;
1622
1623 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1624 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1625 if (index >= 0) {
1626 input = mSoundTriggerSessions.valueFor(session);
1627 isSoundTrigger = true;
1628 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1629 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1630 } else {
1631 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001632 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001633 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001634 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001635 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001636 }
1637
Andy Hungf129b032015-04-07 13:45:50 -07001638 // find a compatible input profile (not necessarily identical in parameters)
1639 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001640 // sampling rate and flags may be updated by getInputProfile
1641 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1642 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001643 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001644 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001645 audio_input_flags_t profileFlags = flags;
1646 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001647 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001648 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001649 profileSamplingRate, profileFormat, profileChannelMask,
1650 profileFlags);
1651 if (profile != 0) {
1652 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001653 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1654 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001655 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1656 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1657 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001658 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001659 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1660 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001661 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001662 }
Eric Laurente552edb2014-03-10 17:42:56 -07001663 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001664 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001665 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001666 if (samplingRate == 0) {
1667 samplingRate = profileSamplingRate;
1668 }
Eric Laurente552edb2014-03-10 17:42:56 -07001669
Eric Laurent322b4d22015-04-03 15:57:54 -07001670 if (profile->getModuleHandle() == 0) {
1671 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001672 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001673 }
1674
Eric Laurent599c7582015-12-07 18:05:55 -08001675 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001676 inputSource,
1677 config->format,
1678 samplingRate,
1679 config->channel_mask,
1680 flags,
1681 uid,
1682 isSoundTrigger,
1683 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001684
Eric Laurent74708e72017-04-07 17:13:42 -07001685// FIXME: disable concurrent capture until UI is ready
1686#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001687 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001688 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001689 for (size_t i = 0; i < mInputs.size(); i++) {
1690 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001691 // reuse input if:
1692 // - it shares the same profile
1693 // AND
1694 // - it is not a reroute submix input
1695 // AND
1696 // - it is: not used for sound trigger
1697 // OR
1698 // used for sound trigger and all clients use the same session ID
1699 //
1700 if ((profile == desc->mProfile) &&
1701 (isSoundTrigger == desc->isSoundTrigger()) &&
1702 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001703
1704 sp<AudioSession> as = desc->getAudioSession(session);
1705 if (as != 0) {
1706 // do not allow unmatching properties on same session
1707 if (as->matches(audioSession)) {
1708 as->changeOpenCount(1);
1709 } else {
1710 ALOGW("getInputForDevice() record with different attributes"
1711 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001712 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001713 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001714 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001715 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001716 }
Eric Laurentbb948092017-01-23 18:33:30 -08001717
Eric Laurent555530a2017-02-07 18:17:24 -08001718 // Reuse the already opened input stream on this profile if:
1719 // - the new capture source is background OR
1720 // - the path requested configurations match OR
1721 // - the new source priority is less than the highest source priority on this input
1722 // If the input stream cannot be reused, close it before opening a new stream
1723 // on the same profile for the new client so that the requested path configuration
1724 // can be selected.
1725 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001726 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001727 desc->mChannelMask != config->channel_mask ||
1728 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001729 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001730 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001731 reusedInputDesc = desc;
1732 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001733 } else {
1734 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001735 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1736 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001737 }
Eric Laurent599c7582015-12-07 18:05:55 -08001738 }
1739 }
Eric Laurent599c7582015-12-07 18:05:55 -08001740
Eric Laurent555530a2017-02-07 18:17:24 -08001741 if (reusedInputDesc != 0) {
1742 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1743 for (size_t j = 0; j < sessions.size(); j++) {
1744 audio_session_t currentSession = sessions.keyAt(j);
1745 stopInput(reusedInputDesc->mIoHandle, currentSession);
1746 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1747 }
1748 }
Eric Laurent74708e72017-04-07 17:13:42 -07001749#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001750
Eric Laurent3974e3b2017-12-07 17:58:43 -08001751 if (!profile->canOpenNewIo()) {
1752 return AUDIO_IO_HANDLE_NONE;
1753 }
1754
Eric Laurentfe231122017-11-17 17:48:06 -08001755 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001756
Eric Laurentfe231122017-11-17 17:48:06 -08001757 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1758 lConfig.sample_rate = profileSamplingRate;
1759 lConfig.channel_mask = profileChannelMask;
1760 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001761
Eric Laurent53b810e2017-12-10 17:25:10 -08001762 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001763 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001764 // the inputs vector must be of size >= 1, but we don't want to crash here
1765 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1766 }
1767
Eric Laurentfe231122017-11-17 17:48:06 -08001768 status_t status = inputDesc->open(&lConfig, device, address,
1769 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001770
1771 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001772 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001773 (profileSamplingRate != lConfig.sample_rate) ||
1774 !audio_formats_match(profileFormat, lConfig.format) ||
1775 (profileChannelMask != lConfig.channel_mask)) {
1776 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001777 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001778 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001779 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001780 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001781 }
Eric Laurent599c7582015-12-07 18:05:55 -08001782 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001783 }
1784
Eric Laurentc722f302014-12-10 11:21:49 -08001785 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001786 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001787
Eric Laurent599c7582015-12-07 18:05:55 -08001788 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001789 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001790
Eric Laurent599c7582015-12-07 18:05:55 -08001791 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001792}
1793
Eric Laurentbb948092017-01-23 18:33:30 -08001794//static
1795bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1796{
1797 return (source == AUDIO_SOURCE_HOTWORD) ||
1798 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1799 (source == AUDIO_SOURCE_FM_TUNER);
1800}
1801
Eric Laurentfb66dd92016-01-28 18:32:03 -08001802bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1803 const sp<AudioSession>& audioSession)
1804{
1805 // Do not allow capture if an active voice call is using a software patch and
1806 // the call TX source device is on the same HW module.
1807 // FIXME: would be better to refine to only inputs whose profile connects to the
1808 // call TX device but this information is not in the audio patch
1809 if (mCallTxPatch != 0 &&
1810 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1811 return false;
1812 }
1813
1814 // starting concurrent capture is enabled if:
1815 // 1) capturing for re-routing
1816 // 2) capturing for HOTWORD source
1817 // 3) capturing for FM TUNER source
1818 // 3) All other active captures are either for re-routing or HOTWORD
1819
1820 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001821 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001822 return true;
1823 }
1824
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001825 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001826 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001827 !is_virtual_input_device(activeInput->mDevice)) {
1828 return false;
1829 }
1830 }
1831
1832 return true;
1833}
1834
Chris Thornton2b864642017-06-27 21:26:07 -07001835// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1836bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1837 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1838 bool soundTriggerSupportsConcurrentCapture = false;
1839 unsigned int numModules = 0;
1840 struct sound_trigger_module_descriptor* nModules = NULL;
1841
1842 status_t status = SoundTrigger::listModules(nModules, &numModules);
1843 if (status == NO_ERROR && numModules != 0) {
1844 nModules = (struct sound_trigger_module_descriptor*) calloc(
1845 numModules, sizeof(struct sound_trigger_module_descriptor));
1846 if (nModules == NULL) {
1847 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1848 // ram the next time this function is called.
1849 ALOGE("Failed to allocate buffer for module descriptors");
1850 return false;
1851 }
1852
1853 status = SoundTrigger::listModules(nModules, &numModules);
1854 if (status == NO_ERROR) {
1855 soundTriggerSupportsConcurrentCapture = true;
1856 for (size_t i = 0; i < numModules; ++i) {
1857 soundTriggerSupportsConcurrentCapture &=
1858 nModules[i].properties.concurrent_capture;
1859 }
1860 }
1861 free(nModules);
1862 }
1863 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1864 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1865 }
1866 return mSoundTriggerSupportsConcurrentCapture;
1867}
1868
Eric Laurentfb66dd92016-01-28 18:32:03 -08001869
Eric Laurent4dc68062014-07-28 17:26:49 -07001870status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001871 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001872 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001873 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001874{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001875
1876 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1877 input, session, silenced, *concurrency);
1878
Eric Laurentfb66dd92016-01-28 18:32:03 -08001879 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001880
Eric Laurente552edb2014-03-10 17:42:56 -07001881 ssize_t index = mInputs.indexOfKey(input);
1882 if (index < 0) {
1883 ALOGW("startInput() unknown input %d", input);
1884 return BAD_VALUE;
1885 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001886 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001887
Eric Laurent599c7582015-12-07 18:05:55 -08001888 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1889 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001890 ALOGW("startInput() unknown session %d on input %d", session, input);
1891 return BAD_VALUE;
1892 }
1893
Eric Laurent74708e72017-04-07 17:13:42 -07001894// FIXME: disable concurrent capture until UI is ready
1895#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001896 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1897 ALOGW("startInput(%d) failed: other input already started", input);
1898 return INVALID_OPERATION;
1899 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001900
Eric Laurentfb66dd92016-01-28 18:32:03 -08001901 if (isInCall()) {
1902 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1903 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001904 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001905 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001906 }
Eric Laurent74708e72017-04-07 17:13:42 -07001907#else
1908 if (!is_virtual_input_device(inputDesc->mDevice)) {
1909 if (mCallTxPatch != 0 &&
1910 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1911 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001912 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001913 return INVALID_OPERATION;
1914 }
1915
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001916 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001917
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001918 // If a UID is idle and records silence and another not silenced recording starts
1919 // from another UID (idle or active) we stop the current idle UID recording in
1920 // favor of the new one - "There can be only one" TM
1921 if (!silenced) {
1922 for (const auto& activeDesc : activeInputs) {
1923 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1924 activeDesc->getId() == inputDesc->getId()) {
1925 continue;
1926 }
1927
1928 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1929 true /*activeOnly*/);
1930 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1931 if (activeSession->isSilenced()) {
1932 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1933 audio_session_t activeSessionId = activeSession->session();
1934 stopInput(activeInput, activeSessionId);
1935 releaseInput(activeInput, activeSessionId);
1936 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1937 activeInputs = mInputs.getActiveInputs();
1938 }
1939 }
1940 }
1941
1942 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001943 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1944 activeDesc->getId() == inputDesc->getId()) {
1945 continue;
1946 }
1947
Eric Laurent74708e72017-04-07 17:13:42 -07001948 audio_source_t activeSource = activeDesc->inputSource(true);
1949 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1950 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1951 if (activeDesc->hasPreemptedSession(session)) {
1952 ALOGW("startInput(%d) failed for HOTWORD: "
1953 "other input %d already started for HOTWORD",
1954 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001955 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001956 return INVALID_OPERATION;
1957 }
1958 } else {
1959 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1960 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001961 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001962 return INVALID_OPERATION;
1963 }
1964 } else {
1965 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1966 ALOGW("startInput(%d) failed: other input %d already started",
1967 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001968 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001969 return INVALID_OPERATION;
1970 }
1971 }
1972 }
1973
Chris Thornton2b864642017-06-27 21:26:07 -07001974 // We only need to check if the sound trigger session supports concurrent capture if the
1975 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1976 // that's running.
1977 const bool allowConcurrentWithSoundTrigger =
1978 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1979
Eric Laurent74708e72017-04-07 17:13:42 -07001980 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001981 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001982 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1983 continue;
1984 }
1985
Eric Laurent74708e72017-04-07 17:13:42 -07001986 audio_source_t activeSource = activeDesc->inputSource(true);
1987 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1988 AudioSessionCollection activeSessions =
1989 activeDesc->getAudioSessions(true /*activeOnly*/);
1990 audio_session_t activeSession = activeSessions.keyAt(0);
1991 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1992 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001993 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001994 sessions.add(activeSession);
1995 inputDesc->setPreemptedSessions(sessions);
1996 stopInput(activeHandle, activeSession);
1997 releaseInput(activeHandle, activeSession);
1998 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1999 input, activeDesc->mIoHandle);
2000 }
2001 }
2002 }
2003#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002004
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002005 // Make sure we start with the correct silence state
2006 audioSession->setSilenced(silenced);
2007
Eric Laurent313d1e72016-01-29 09:56:57 -08002008 // increment activity count before calling getNewInputDevice() below as only active sessions
2009 // are considered for device selection
2010 audioSession->changeActiveCount(1);
2011
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002012 // Routing?
2013 mInputRoutes.incRouteActivity(session);
2014
Eric Laurent2157f5b2018-04-25 18:33:02 -07002015 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002016 // indicate active capture to sound trigger service if starting capture from a mic on
2017 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002018 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002019 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002020
Eric Laurent733ce942017-12-07 12:18:25 -08002021 status_t status = inputDesc->start();
2022 if (status != NO_ERROR) {
2023 mInputRoutes.decRouteActivity(session);
2024 audioSession->changeActiveCount(-1);
2025 return status;
2026 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002027
Eric Laurent733ce942017-12-07 12:18:25 -08002028 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002029 // if input maps to a dynamic policy with an activity listener, notify of state change
2030 if ((inputDesc->mPolicyMix != NULL)
2031 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2032 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2033 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002034 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002035
Eric Laurentf7c50102016-09-30 15:19:43 -07002036 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2037 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002038 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002039 SoundTrigger::setCaptureState(true);
2040 }
2041
2042 // automatically enable the remote submix output when input is started if not
2043 // used by a policy mix of type MIX_TYPE_RECORDERS
2044 // For remote submix (a virtual device), we open only one input per capture request.
2045 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2046 String8 address = String8("");
2047 if (inputDesc->mPolicyMix == NULL) {
2048 address = String8("0");
2049 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2050 address = inputDesc->mPolicyMix->mDeviceAddress;
2051 }
2052 if (address != "") {
2053 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2054 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2055 address, "remote-submix");
2056 }
Eric Laurentc722f302014-12-10 11:21:49 -08002057 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002058 }
Eric Laurente552edb2014-03-10 17:42:56 -07002059 }
2060
Eric Laurent599c7582015-12-07 18:05:55 -08002061 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002062
Eric Laurente552edb2014-03-10 17:42:56 -07002063 return NO_ERROR;
2064}
2065
Eric Laurent4dc68062014-07-28 17:26:49 -07002066status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2067 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002068{
2069 ALOGV("stopInput() input %d", input);
2070 ssize_t index = mInputs.indexOfKey(input);
2071 if (index < 0) {
2072 ALOGW("stopInput() unknown input %d", input);
2073 return BAD_VALUE;
2074 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002075 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002076
Eric Laurent599c7582015-12-07 18:05:55 -08002077 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002078 if (index < 0) {
2079 ALOGW("stopInput() unknown session %d on input %d", session, input);
2080 return BAD_VALUE;
2081 }
2082
Eric Laurent599c7582015-12-07 18:05:55 -08002083 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002084 ALOGW("stopInput() input %d already stopped", input);
2085 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002086 }
2087
Eric Laurent599c7582015-12-07 18:05:55 -08002088 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002089
2090 // Routing?
2091 mInputRoutes.decRouteActivity(session);
2092
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002093 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002094 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002095 if (inputDesc->isActive()) {
2096 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2097 } else {
2098 // if input maps to a dynamic policy with an activity listener, notify of state change
2099 if ((inputDesc->mPolicyMix != NULL)
2100 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2101 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2102 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002103 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002104
2105 // automatically disable the remote submix output when input is stopped if not
2106 // used by a policy mix of type MIX_TYPE_RECORDERS
2107 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2108 String8 address = String8("");
2109 if (inputDesc->mPolicyMix == NULL) {
2110 address = String8("0");
2111 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2112 address = inputDesc->mPolicyMix->mDeviceAddress;
2113 }
2114 if (address != "") {
2115 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2116 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2117 address, "remote-submix");
2118 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002119 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002120
Eric Laurentf7c50102016-09-30 15:19:43 -07002121 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002122 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002123
Eric Laurentf7c50102016-09-30 15:19:43 -07002124 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2125 // primary HW module
2126 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2127 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2128 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002129 SoundTrigger::setCaptureState(false);
2130 }
2131 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002132 }
Eric Laurente552edb2014-03-10 17:42:56 -07002133 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002134 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002135}
2136
Eric Laurent4dc68062014-07-28 17:26:49 -07002137void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2138 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002139{
2140 ALOGV("releaseInput() %d", input);
2141 ssize_t index = mInputs.indexOfKey(input);
2142 if (index < 0) {
2143 ALOGW("releaseInput() releasing unknown input %d", input);
2144 return;
2145 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002146
2147 // Routing
2148 mInputRoutes.removeRoute(session);
2149
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002150 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2151 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002152
Eric Laurent599c7582015-12-07 18:05:55 -08002153 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002154 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002155 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2156 return;
2157 }
Eric Laurent599c7582015-12-07 18:05:55 -08002158
2159 if (audioSession->openCount() == 0) {
2160 ALOGW("releaseInput() invalid open count %d on session %d",
2161 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002162 return;
2163 }
Eric Laurent599c7582015-12-07 18:05:55 -08002164
2165 if (audioSession->changeOpenCount(-1) == 0) {
2166 inputDesc->removeAudioSession(session);
2167 }
2168
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002169 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002170 ALOGV("releaseInput() exit > 0");
2171 return;
2172 }
2173
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002175 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002176 ALOGV("releaseInput() exit");
2177}
2178
Eric Laurentd4692962014-05-05 18:13:44 -07002179void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002180 bool patchRemoved = false;
2181
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002182 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002183 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002184 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002185 if (patch_index >= 0) {
2186 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002187 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002188 mAudioPatches.removeItemsAt(patch_index);
2189 patchRemoved = true;
2190 }
Eric Laurentfe231122017-11-17 17:48:06 -08002191 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002192 }
jiabin829a00b2018-04-04 16:28:32 -07002193 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002194 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002195 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002196 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002197
2198 if (patchRemoved) {
2199 mpClientInterface->onAudioPatchListUpdate();
2200 }
Eric Laurentd4692962014-05-05 18:13:44 -07002201}
2202
Eric Laurente0720872014-03-11 09:30:41 -07002203void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002204 int indexMin,
2205 int indexMax)
2206{
2207 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002208 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002209
2210 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002211 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2212 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002213 continue;
2214 }
2215 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002216 }
Eric Laurente552edb2014-03-10 17:42:56 -07002217}
2218
Eric Laurente0720872014-03-11 09:30:41 -07002219status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002220 int index,
2221 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002222{
2223
Nadav Bar7c605f62017-12-25 00:01:52 +02002224 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2225 // app that has MODIFY_PHONE_STATE permission.
2226 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2227 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002228 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002229 return BAD_VALUE;
2230 }
2231 if (!audio_is_output_device(device)) {
2232 return BAD_VALUE;
2233 }
2234
2235 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002236 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002237
Eric Laurent1fd372e2016-04-06 14:23:53 -07002238 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002239 stream, device, index);
2240
Eric Laurent28d09f02016-03-08 10:43:05 -08002241 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002242 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2243 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002244 continue;
2245 }
2246 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2247 }
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Eric Laurent1fd372e2016-04-06 14:23:53 -07002249 // update volume on all outputs and streams matching the following:
2250 // - The requested stream (or a stream matching for volume control) is active on the output
2251 // - The device (or devices) selected by the strategy corresponding to this stream includes
2252 // the requested device
2253 // - For non default requested device, currently selected device on the output is either the
2254 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002255 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2256 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002257 status_t status = NO_ERROR;
2258 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002259 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2260 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002261 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002262 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002263 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002264 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002265 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002266 continue;
2267 }
Eric Laurent794fde22016-03-11 09:50:45 -08002268 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002269 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2270 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002271 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2272 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002273 continue;
2274 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002275 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002276 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002277 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002278 applyVolume = (curDevice & curStreamDevice) != 0;
2279 } else {
2280 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002281 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002282 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002283 // rescale index before applying to curStream as ranges may be different for
2284 // stream and curStream
2285 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002286 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002287 //FIXME: workaround for truncated touch sounds
2288 // delayed volume change for system stream to be removed when the problem is
2289 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002290 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002291 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002292 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002293 if (volStatus != NO_ERROR) {
2294 status = volStatus;
2295 }
2296 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002297 }
Eric Laurente552edb2014-03-10 17:42:56 -07002298 }
2299 return status;
2300}
2301
Eric Laurente0720872014-03-11 09:30:41 -07002302status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002303 int *index,
2304 audio_devices_t device)
2305{
2306 if (index == NULL) {
2307 return BAD_VALUE;
2308 }
2309 if (!audio_is_output_device(device)) {
2310 return BAD_VALUE;
2311 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002312 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002313 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002314 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002315 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2316 }
François Gaffiedfd74092015-03-19 12:10:59 +01002317 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002318
François Gaffied1ab2bd2015-12-02 18:20:06 +01002319 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002320 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2321 return NO_ERROR;
2322}
2323
Eric Laurent36829f92017-04-07 19:04:42 -07002324audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002325{
2326 // select one output among several suitable for global effects.
2327 // The priority is as follows:
2328 // 1: An offloaded output. If the effect ends up not being offloadable,
2329 // AudioFlinger will invalidate the track and the offloaded output
2330 // will be closed causing the effect to be moved to a PCM output.
2331 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002332 // 3: The primary output
2333 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002334
Eric Laurent3b73df72014-03-11 09:06:29 -07002335 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002336 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurent36829f92017-04-07 19:04:42 -07002339 if (outputs.size() == 0) {
2340 return AUDIO_IO_HANDLE_NONE;
2341 }
Eric Laurente552edb2014-03-10 17:42:56 -07002342
Eric Laurent36829f92017-04-07 19:04:42 -07002343 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2344 bool activeOnly = true;
2345
2346 while (output == AUDIO_IO_HANDLE_NONE) {
2347 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2348 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2349 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2350
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002351 for (audio_io_handle_t output : outputs) {
2352 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002353 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2354 continue;
2355 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002356 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2357 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002358 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002359 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002360 }
2361 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002362 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002363 }
2364 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002365 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002366 }
2367 }
2368 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2369 output = outputOffloaded;
2370 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2371 output = outputDeepBuffer;
2372 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2373 output = outputPrimary;
2374 } else {
2375 output = outputs[0];
2376 }
2377 activeOnly = false;
2378 }
2379
2380 if (output != mMusicEffectOutput) {
2381 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2382 mMusicEffectOutput = output;
2383 }
2384
2385 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002386 return output;
2387}
2388
Eric Laurent36829f92017-04-07 19:04:42 -07002389audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2390{
2391 return selectOutputForMusicEffects();
2392}
2393
Eric Laurente0720872014-03-11 09:30:41 -07002394status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002395 audio_io_handle_t io,
2396 uint32_t strategy,
2397 int session,
2398 int id)
2399{
2400 ssize_t index = mOutputs.indexOfKey(io);
2401 if (index < 0) {
2402 index = mInputs.indexOfKey(io);
2403 if (index < 0) {
2404 ALOGW("registerEffect() unknown io %d", io);
2405 return INVALID_OPERATION;
2406 }
2407 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002408 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002409}
2410
Eric Laurentc75307b2015-03-17 15:29:32 -07002411bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2412{
Eric Laurent28d09f02016-03-08 10:43:05 -08002413 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002414 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2415 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002416 continue;
2417 }
2418 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2419 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002420 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002421}
2422
2423bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2424{
2425 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2426}
2427
Eric Laurente0720872014-03-11 09:30:41 -07002428bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002429{
2430 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002431 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002432 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002433 return true;
2434 }
2435 }
2436 return false;
2437}
2438
Eric Laurent275e8e92014-11-30 15:14:47 -08002439// Register a list of custom mixes with their attributes and format.
2440// When a mix is registered, corresponding input and output profiles are
2441// added to the remote submix hw module. The profile contains only the
2442// parameters (sampling rate, format...) specified by the mix.
2443// The corresponding input remote submix device is also connected.
2444//
2445// When a remote submix device is connected, the address is checked to select the
2446// appropriate profile and the corresponding input or output stream is opened.
2447//
2448// When capture starts, getInputForAttr() will:
2449// - 1 look for a mix matching the address passed in attribtutes tags if any
2450// - 2 if none found, getDeviceForInputSource() will:
2451// - 2.1 look for a mix matching the attributes source
2452// - 2.2 if none found, default to device selection by policy rules
2453// At this time, the corresponding output remote submix device is also connected
2454// and active playback use cases can be transferred to this mix if needed when reconnecting
2455// after AudioTracks are invalidated
2456//
2457// When playback starts, getOutputForAttr() will:
2458// - 1 look for a mix matching the address passed in attribtutes tags if any
2459// - 2 if none found, look for a mix matching the attributes usage
2460// - 3 if none found, default to device and output selection by policy rules.
2461
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002462status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002463{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002464 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2465 status_t res = NO_ERROR;
2466
2467 sp<HwModule> rSubmixModule;
2468 // examine each mix's route type
2469 for (size_t i = 0; i < mixes.size(); i++) {
2470 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2471 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2472 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002473 break;
2474 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002477 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002478 rSubmixModule = mHwModules.getModuleFromName(
2479 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2480 if (rSubmixModule == 0) {
2481 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2482 i);
2483 res = INVALID_OPERATION;
2484 break;
2485 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002486 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002487
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002488 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002489
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002490 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002491 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 res = INVALID_OPERATION;
2493 break;
2494 }
2495 audio_config_t outputConfig = mixes[i].mFormat;
2496 audio_config_t inputConfig = mixes[i].mFormat;
2497 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2498 // stereo and let audio flinger do the channel conversion if needed.
2499 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2500 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2501 rSubmixModule->addOutputProfile(address, &outputConfig,
2502 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2503 rSubmixModule->addInputProfile(address, &inputConfig,
2504 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002505
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2507 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2508 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2509 address.string(), "remote-submix");
2510 } else {
2511 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2512 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2513 address.string(), "remote-submix");
2514 }
2515 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002516 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002517 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002518 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2519 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002520
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002521 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2524 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2525 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2526 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2527 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002528 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2529 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002530 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2531 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002532 } else {
2533 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 }
2535 break;
2536 }
2537 }
2538
2539 if (res != NO_ERROR) {
2540 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002541 i, device, address.string());
2542 res = INVALID_OPERATION;
2543 break;
2544 } else if (!foundOutput) {
2545 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2546 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002547 res = INVALID_OPERATION;
2548 break;
2549 }
Eric Laurentc722f302014-12-10 11:21:49 -08002550 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002551 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002552 if (res != NO_ERROR) {
2553 unregisterPolicyMixes(mixes);
2554 }
2555 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002556}
2557
2558status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2559{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002560 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 status_t res = NO_ERROR;
2562 sp<HwModule> rSubmixModule;
2563 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002564 for (const auto& mix : mixes) {
2565 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002566
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002567 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002568 rSubmixModule = mHwModules.getModuleFromName(
2569 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2570 if (rSubmixModule == 0) {
2571 res = INVALID_OPERATION;
2572 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 }
2574 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002575
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002576 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002577
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002578 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2579 res = INVALID_OPERATION;
2580 continue;
2581 }
2582
2583 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2584 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2585 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2586 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2587 address.string(), "remote-submix");
2588 }
2589 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2590 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2591 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2592 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2593 address.string(), "remote-submix");
2594 }
2595 rSubmixModule->removeOutputProfile(address);
2596 rSubmixModule->removeInputProfile(address);
2597
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002598 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2599 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002600 res = INVALID_OPERATION;
2601 continue;
2602 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002603 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002604 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002605 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002606}
2607
Eric Laurente552edb2014-03-10 17:42:56 -07002608
Eric Laurente0720872014-03-11 09:30:41 -07002609status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002610{
Eric Laurente552edb2014-03-10 17:42:56 -07002611 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002612 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2613 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002614 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002615 std::string stateLiteral;
2616 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002617 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2618 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2619 "communications", "media", "record", "dock", "system",
2620 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2621 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2622 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2623 result.appendFormat(" Force use for %s: %d\n",
2624 forceUses[i], mEngine->getForceUse(i));
2625 }
2626 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2627 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2628 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002629 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002630
François Gaffie112b0af2015-11-19 16:13:25 +01002631 mAvailableOutputDevices.dump(fd, String8("Available output"));
2632 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002633 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002634 mOutputs.dump(fd);
2635 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002636 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002637 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002638 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002639 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002640
2641 return NO_ERROR;
2642}
2643
2644// This function checks for the parameters which can be offloaded.
2645// This can be enhanced depending on the capability of the DSP and policy
2646// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002647bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002648{
2649 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002650 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002651 offloadInfo.sample_rate, offloadInfo.channel_mask,
2652 offloadInfo.format,
2653 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2654 offloadInfo.has_video);
2655
Andy Hung2ddee192015-12-18 17:34:44 -08002656 if (mMasterMono) {
2657 return false; // no offloading if mono is set.
2658 }
2659
Eric Laurente552edb2014-03-10 17:42:56 -07002660 // Check if offload has been disabled
2661 char propValue[PROPERTY_VALUE_MAX];
2662 if (property_get("audio.offload.disable", propValue, "0")) {
2663 if (atoi(propValue) != 0) {
2664 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2665 return false;
2666 }
2667 }
2668
2669 // Check if stream type is music, then only allow offload as of now.
2670 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2671 {
2672 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2673 return false;
2674 }
2675
2676 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002677 const bool allowOffloadWithVideo =
2678 property_get_bool("audio.offload.video", false /* default_value */);
2679 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002680 ALOGV("isOffloadSupported: has_video == true, returning false");
2681 return false;
2682 }
2683
2684 //If duration is less than minimum value defined in property, return false
2685 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2686 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2687 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2688 return false;
2689 }
2690 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2691 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2692 return false;
2693 }
2694
2695 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2696 // creating an offloaded track and tearing it down immediately after start when audioflinger
2697 // detects there is an active non offloadable effect.
2698 // FIXME: We should check the audio session here but we do not have it in this context.
2699 // This may prevent offloading in rare situations where effects are left active by apps
2700 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002701 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002702 return false;
2703 }
2704
2705 // See if there is a profile to support this.
2706 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002707 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002708 offloadInfo.sample_rate,
2709 offloadInfo.format,
2710 offloadInfo.channel_mask,
2711 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002712 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2713 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002714}
2715
Eric Laurent6a94d692014-05-20 11:18:06 -07002716status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2717 audio_port_type_t type,
2718 unsigned int *num_ports,
2719 struct audio_port *ports,
2720 unsigned int *generation)
2721{
2722 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2723 generation == NULL) {
2724 return BAD_VALUE;
2725 }
2726 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2727 if (ports == NULL) {
2728 *num_ports = 0;
2729 }
2730
2731 size_t portsWritten = 0;
2732 size_t portsMax = *num_ports;
2733 *num_ports = 0;
2734 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002735 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2736 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002737 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002738 for (const auto& dev : mAvailableOutputDevices) {
2739 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002740 continue;
2741 }
2742 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002743 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002744 }
2745 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002746 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 }
2748 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002749 for (const auto& dev : mAvailableInputDevices) {
2750 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002751 continue;
2752 }
2753 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002754 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002755 }
2756 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 }
2759 }
2760 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2761 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2762 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2763 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2764 }
2765 *num_ports += mInputs.size();
2766 }
2767 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002768 size_t numOutputs = 0;
2769 for (size_t i = 0; i < mOutputs.size(); i++) {
2770 if (!mOutputs[i]->isDuplicated()) {
2771 numOutputs++;
2772 if (portsWritten < portsMax) {
2773 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2774 }
2775 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002776 }
Eric Laurent84c70242014-06-23 08:46:27 -07002777 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002778 }
2779 }
2780 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002781 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002782 return NO_ERROR;
2783}
2784
Eric Laurent99fcae42018-05-17 16:59:18 -07002785status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002786{
Eric Laurent99fcae42018-05-17 16:59:18 -07002787 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2788 return BAD_VALUE;
2789 }
2790 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2791 if (dev != 0) {
2792 dev->toAudioPort(port);
2793 return NO_ERROR;
2794 }
2795 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2796 if (dev != 0) {
2797 dev->toAudioPort(port);
2798 return NO_ERROR;
2799 }
2800 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2801 if (out != 0) {
2802 out->toAudioPort(port);
2803 return NO_ERROR;
2804 }
2805 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2806 if (in != 0) {
2807 in->toAudioPort(port);
2808 return NO_ERROR;
2809 }
2810 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002811}
2812
Eric Laurent6a94d692014-05-20 11:18:06 -07002813status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2814 audio_patch_handle_t *handle,
2815 uid_t uid)
2816{
2817 ALOGV("createAudioPatch()");
2818
2819 if (handle == NULL || patch == NULL) {
2820 return BAD_VALUE;
2821 }
2822 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2823
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002824 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002825 return BAD_VALUE;
2826 }
2827 // only one source per audio patch supported for now
2828 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 return INVALID_OPERATION;
2830 }
Eric Laurent874c42872014-08-08 15:13:39 -07002831
2832 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 return INVALID_OPERATION;
2834 }
Eric Laurent874c42872014-08-08 15:13:39 -07002835 for (size_t i = 0; i < patch->num_sinks; i++) {
2836 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2837 return INVALID_OPERATION;
2838 }
2839 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002840
2841 sp<AudioPatch> patchDesc;
2842 ssize_t index = mAudioPatches.indexOfKey(*handle);
2843
Eric Laurent6a94d692014-05-20 11:18:06 -07002844 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2845 patch->sources[0].role,
2846 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002847#if LOG_NDEBUG == 0
2848 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002849 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002850 patch->sinks[i].role,
2851 patch->sinks[i].type);
2852 }
2853#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002854
2855 if (index >= 0) {
2856 patchDesc = mAudioPatches.valueAt(index);
2857 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2858 mUidCached, patchDesc->mUid, uid);
2859 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2860 return INVALID_OPERATION;
2861 }
2862 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002863 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002864 }
2865
2866 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002867 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002868 if (outputDesc == NULL) {
2869 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2870 return BAD_VALUE;
2871 }
Eric Laurent84c70242014-06-23 08:46:27 -07002872 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2873 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002874 if (patchDesc != 0) {
2875 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2876 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2877 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2878 return BAD_VALUE;
2879 }
2880 }
Eric Laurent874c42872014-08-08 15:13:39 -07002881 DeviceVector devices;
2882 for (size_t i = 0; i < patch->num_sinks; i++) {
2883 // Only support mix to devices connection
2884 // TODO add support for mix to mix connection
2885 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2886 ALOGV("createAudioPatch() source mix but sink is not a device");
2887 return INVALID_OPERATION;
2888 }
2889 sp<DeviceDescriptor> devDesc =
2890 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2891 if (devDesc == 0) {
2892 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2893 return BAD_VALUE;
2894 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002895
François Gaffie53615e22015-03-19 09:24:12 +01002896 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002897 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002898 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002899 NULL, // updatedSamplingRate
2900 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002901 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002902 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002903 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002904 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002905 ALOGV("createAudioPatch() profile not supported for device %08x",
2906 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002907 return INVALID_OPERATION;
2908 }
2909 devices.add(devDesc);
2910 }
2911 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002912 return INVALID_OPERATION;
2913 }
Eric Laurent874c42872014-08-08 15:13:39 -07002914
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 // TODO: reconfigure output format and channels here
2916 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002917 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002918 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002919 index = mAudioPatches.indexOfKey(*handle);
2920 if (index >= 0) {
2921 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2922 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2923 }
2924 patchDesc = mAudioPatches.valueAt(index);
2925 patchDesc->mUid = uid;
2926 ALOGV("createAudioPatch() success");
2927 } else {
2928 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2929 return INVALID_OPERATION;
2930 }
2931 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2932 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2933 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002934 // only one sink supported when connecting an input device to a mix
2935 if (patch->num_sinks > 1) {
2936 return INVALID_OPERATION;
2937 }
François Gaffie53615e22015-03-19 09:24:12 +01002938 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002939 if (inputDesc == NULL) {
2940 return BAD_VALUE;
2941 }
2942 if (patchDesc != 0) {
2943 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2944 return BAD_VALUE;
2945 }
2946 }
2947 sp<DeviceDescriptor> devDesc =
2948 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2949 if (devDesc == 0) {
2950 return BAD_VALUE;
2951 }
2952
François Gaffie53615e22015-03-19 09:24:12 +01002953 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002954 devDesc->mAddress,
2955 patch->sinks[0].sample_rate,
2956 NULL, /*updatedSampleRate*/
2957 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002958 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002959 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002960 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002961 // FIXME for the parameter type,
2962 // and the NONE
2963 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002964 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002965 return INVALID_OPERATION;
2966 }
2967 // TODO: reconfigure output format and channels here
2968 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002969 devDesc->type(), inputDesc->mIoHandle);
2970 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 index = mAudioPatches.indexOfKey(*handle);
2972 if (index >= 0) {
2973 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2974 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2975 }
2976 patchDesc = mAudioPatches.valueAt(index);
2977 patchDesc->mUid = uid;
2978 ALOGV("createAudioPatch() success");
2979 } else {
2980 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2981 return INVALID_OPERATION;
2982 }
2983 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2984 // device to device connection
2985 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002986 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002987 return BAD_VALUE;
2988 }
2989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002990 sp<DeviceDescriptor> srcDeviceDesc =
2991 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002992 if (srcDeviceDesc == 0) {
2993 return BAD_VALUE;
2994 }
Eric Laurent874c42872014-08-08 15:13:39 -07002995
Eric Laurent6a94d692014-05-20 11:18:06 -07002996 //update source and sink with our own data as the data passed in the patch may
2997 // be incomplete.
2998 struct audio_patch newPatch = *patch;
2999 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003000
Eric Laurent874c42872014-08-08 15:13:39 -07003001 for (size_t i = 0; i < patch->num_sinks; i++) {
3002 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3003 ALOGV("createAudioPatch() source device but one sink is not a device");
3004 return INVALID_OPERATION;
3005 }
3006
3007 sp<DeviceDescriptor> sinkDeviceDesc =
3008 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3009 if (sinkDeviceDesc == 0) {
3010 return BAD_VALUE;
3011 }
3012 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3013
Eric Laurent3bcf8592015-04-03 12:13:24 -07003014 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003015 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003016 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003017 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003018 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003019 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003020 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003021 return INVALID_OPERATION;
3022 }
Eric Laurent874c42872014-08-08 15:13:39 -07003023 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003024 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003025 // if the sink device is reachable via an opened output stream, request to go via
3026 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003027 audio_io_handle_t output = selectOutput(outputs,
3028 AUDIO_OUTPUT_FLAG_NONE,
3029 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003030 if (output != AUDIO_IO_HANDLE_NONE) {
3031 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3032 if (outputDesc->isDuplicated()) {
3033 return INVALID_OPERATION;
3034 }
3035 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003036 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003037 newPatch.num_sources = 2;
3038 }
Eric Laurent83b88082014-06-20 18:31:16 -07003039 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 }
3041 // TODO: check from routing capabilities in config file and other conflicting patches
3042
Mikhail Naganovdc769682018-05-04 15:34:08 -07003043 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3044 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3046 status);
3047 return INVALID_OPERATION;
3048 }
3049 } else {
3050 return BAD_VALUE;
3051 }
3052 } else {
3053 return BAD_VALUE;
3054 }
3055 return NO_ERROR;
3056}
3057
3058status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3059 uid_t uid)
3060{
3061 ALOGV("releaseAudioPatch() patch %d", handle);
3062
3063 ssize_t index = mAudioPatches.indexOfKey(handle);
3064
3065 if (index < 0) {
3066 return BAD_VALUE;
3067 }
3068 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3069 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3070 mUidCached, patchDesc->mUid, uid);
3071 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3072 return INVALID_OPERATION;
3073 }
3074
3075 struct audio_patch *patch = &patchDesc->mPatch;
3076 patchDesc->mUid = mUidCached;
3077 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003078 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003079 if (outputDesc == NULL) {
3080 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3081 return BAD_VALUE;
3082 }
3083
Eric Laurentc75307b2015-03-17 15:29:32 -07003084 setOutputDevice(outputDesc,
3085 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 true,
3087 0,
3088 NULL);
3089 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3090 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003091 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003092 if (inputDesc == NULL) {
3093 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3094 return BAD_VALUE;
3095 }
3096 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003097 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003098 true,
3099 NULL);
3100 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003101 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3102 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3103 status, patchDesc->mAfPatchHandle);
3104 removeAudioPatch(patchDesc->mHandle);
3105 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003106 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 } else {
3108 return BAD_VALUE;
3109 }
3110 } else {
3111 return BAD_VALUE;
3112 }
3113 return NO_ERROR;
3114}
3115
3116status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3117 struct audio_patch *patches,
3118 unsigned int *generation)
3119{
François Gaffie53615e22015-03-19 09:24:12 +01003120 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003121 return BAD_VALUE;
3122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003123 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003124 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003125}
3126
Eric Laurente1715a42014-05-20 11:30:42 -07003127status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003128{
Eric Laurente1715a42014-05-20 11:30:42 -07003129 ALOGV("setAudioPortConfig()");
3130
3131 if (config == NULL) {
3132 return BAD_VALUE;
3133 }
3134 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3135 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003136 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3137 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003138 }
3139
Eric Laurenta121f902014-06-03 13:32:54 -07003140 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003141 if (config->type == AUDIO_PORT_TYPE_MIX) {
3142 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003143 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003144 if (outputDesc == NULL) {
3145 return BAD_VALUE;
3146 }
Eric Laurent84c70242014-06-23 08:46:27 -07003147 ALOG_ASSERT(!outputDesc->isDuplicated(),
3148 "setAudioPortConfig() called on duplicated output %d",
3149 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003150 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003151 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003152 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003153 if (inputDesc == NULL) {
3154 return BAD_VALUE;
3155 }
Eric Laurenta121f902014-06-03 13:32:54 -07003156 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003157 } else {
3158 return BAD_VALUE;
3159 }
3160 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3161 sp<DeviceDescriptor> deviceDesc;
3162 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3163 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3164 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3165 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3166 } else {
3167 return BAD_VALUE;
3168 }
3169 if (deviceDesc == NULL) {
3170 return BAD_VALUE;
3171 }
Eric Laurenta121f902014-06-03 13:32:54 -07003172 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003173 } else {
3174 return BAD_VALUE;
3175 }
3176
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003177 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003178 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3179 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003180 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003181 audioPortConfig->toAudioPortConfig(&newConfig, config);
3182 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003183 }
Eric Laurenta121f902014-06-03 13:32:54 -07003184 if (status != NO_ERROR) {
3185 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003186 }
Eric Laurente1715a42014-05-20 11:30:42 -07003187
3188 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003189}
3190
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003191void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3192{
Eric Laurentd60560a2015-04-10 11:31:20 -07003193 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003194 clearAudioPatches(uid);
3195 clearSessionRoutes(uid);
3196}
3197
Eric Laurent6a94d692014-05-20 11:18:06 -07003198void AudioPolicyManager::clearAudioPatches(uid_t uid)
3199{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003200 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3202 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003203 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003204 }
3205 }
3206}
3207
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003208void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3209 audio_io_handle_t ouptutToSkip)
3210{
3211 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3212 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3213 for (size_t j = 0; j < mOutputs.size(); j++) {
3214 if (mOutputs.keyAt(j) == ouptutToSkip) {
3215 continue;
3216 }
3217 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3218 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3219 continue;
3220 }
3221 // If the default device for this strategy is on another output mix,
3222 // invalidate all tracks in this strategy to force re connection.
3223 // Otherwise select new device on the output mix.
3224 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003225 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003226 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3227 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3228 }
3229 }
3230 } else {
3231 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3232 setOutputDevice(outputDesc, newDevice, false);
3233 }
3234 }
3235}
3236
3237void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3238{
3239 // remove output routes associated with this uid
3240 SortedVector<routing_strategy> affectedStrategies;
3241 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3242 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3243 if (route->mUid == uid) {
3244 mOutputRoutes.removeItemsAt(i);
3245 if (route->mDeviceDescriptor != 0) {
3246 affectedStrategies.add(getStrategy(route->mStreamType));
3247 }
3248 }
3249 }
3250 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003251 for (const auto& strategy : affectedStrategies) {
3252 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003253 }
3254
3255 // remove input routes associated with this uid
3256 SortedVector<audio_source_t> affectedSources;
3257 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3258 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3259 if (route->mUid == uid) {
3260 mInputRoutes.removeItemsAt(i);
3261 if (route->mDeviceDescriptor != 0) {
3262 affectedSources.add(route->mSource);
3263 }
3264 }
3265 }
3266 // reroute inputs if necessary
3267 SortedVector<audio_io_handle_t> inputsToClose;
3268 for (size_t i = 0; i < mInputs.size(); i++) {
3269 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003270 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003271 inputsToClose.add(inputDesc->mIoHandle);
3272 }
3273 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003274 for (const auto& input : inputsToClose) {
3275 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003276 }
3277}
3278
Eric Laurentd60560a2015-04-10 11:31:20 -07003279void AudioPolicyManager::clearAudioSources(uid_t uid)
3280{
3281 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3282 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3283 if (sourceDesc->mUid == uid) {
3284 stopAudioSource(mAudioSources.keyAt(i));
3285 }
3286 }
3287}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003288
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003289status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3290 audio_io_handle_t *ioHandle,
3291 audio_devices_t *device)
3292{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003293 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3294 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003295 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003296
François Gaffiedf372692015-03-19 10:43:27 +01003297 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003298}
3299
Eric Laurentd60560a2015-04-10 11:31:20 -07003300status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3301 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003302 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003303 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003304{
Eric Laurentd60560a2015-04-10 11:31:20 -07003305 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3306 if (source == NULL || attributes == NULL || handle == NULL) {
3307 return BAD_VALUE;
3308 }
3309
Glenn Kasten559d4392016-03-29 13:42:57 -07003310 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003311
3312 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3313 source->type != AUDIO_PORT_TYPE_DEVICE) {
3314 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3315 return INVALID_OPERATION;
3316 }
3317
3318 sp<DeviceDescriptor> srcDeviceDesc =
3319 mAvailableInputDevices.getDevice(source->ext.device.type,
3320 String8(source->ext.device.address));
3321 if (srcDeviceDesc == 0) {
3322 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3323 return BAD_VALUE;
3324 }
3325 sp<AudioSourceDescriptor> sourceDesc =
3326 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3327
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003328 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003329 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3330 sourceDesc->mPatchDesc = patchDesc;
3331
3332 status_t status = connectAudioSource(sourceDesc);
3333 if (status == NO_ERROR) {
3334 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3335 *handle = sourceDesc->getHandle();
3336 }
3337 return status;
3338}
3339
3340status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3341{
3342 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3343
3344 // make sure we only have one patch per source.
3345 disconnectAudioSource(sourceDesc);
3346
3347 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003348 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003349 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3350
3351 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3352 sp<DeviceDescriptor> sinkDeviceDesc =
3353 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3354
3355 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003356
3357 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3358 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003359 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003360 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3361 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3362 // create patch between src device and output device
3363 // create Hwoutput and add to mHwOutputs
3364 } else {
3365 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3366 audio_io_handle_t output =
3367 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3368 if (output == AUDIO_IO_HANDLE_NONE) {
3369 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3370 return INVALID_OPERATION;
3371 }
3372 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3373 if (outputDesc->isDuplicated()) {
3374 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3375 return INVALID_OPERATION;
3376 }
Eric Laurent733ce942017-12-07 12:18:25 -08003377 status_t status = outputDesc->start();
3378 if (status != NO_ERROR) {
3379 return status;
3380 }
3381
Eric Laurentd60560a2015-04-10 11:31:20 -07003382 // create a special patch with no sink and two sources:
3383 // - the second source indicates to PatchPanel through which output mix this patch should
3384 // be connected as well as the stream type for volume control
3385 // - the sink is defined by whatever output device is currently selected for the output
3386 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003387 PatchBuilder patchBuilder;
3388 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3389 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003390 &afPatchHandle,
3391 0);
3392 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3393 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003394 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003395 if (status != NO_ERROR) {
3396 ALOGW("%s patch panel could not connect device patch, error %d",
3397 __FUNCTION__, status);
3398 return INVALID_OPERATION;
3399 }
3400 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003401 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003402
3403 if (status != NO_ERROR) {
3404 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3405 return status;
3406 }
3407 sourceDesc->mSwOutput = outputDesc;
3408 if (delayMs != 0) {
3409 usleep(delayMs * 1000);
3410 }
3411 }
3412
3413 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3414 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3415
3416 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003417}
3418
Glenn Kasten559d4392016-03-29 13:42:57 -07003419status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003420{
Eric Laurentd60560a2015-04-10 11:31:20 -07003421 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3422 ALOGV("%s handle %d", __FUNCTION__, handle);
3423 if (sourceDesc == 0) {
3424 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3425 return BAD_VALUE;
3426 }
3427 status_t status = disconnectAudioSource(sourceDesc);
3428
3429 mAudioSources.removeItem(handle);
3430 return status;
3431}
3432
Andy Hung2ddee192015-12-18 17:34:44 -08003433status_t AudioPolicyManager::setMasterMono(bool mono)
3434{
3435 if (mMasterMono == mono) {
3436 return NO_ERROR;
3437 }
3438 mMasterMono = mono;
3439 // if enabling mono we close all offloaded devices, which will invalidate the
3440 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3441 // for recreating the new AudioTrack as non-offloaded PCM.
3442 //
3443 // If disabling mono, we leave all tracks as is: we don't know which clients
3444 // and tracks are able to be recreated as offloaded. The next "song" should
3445 // play back offloaded.
3446 if (mMasterMono) {
3447 Vector<audio_io_handle_t> offloaded;
3448 for (size_t i = 0; i < mOutputs.size(); ++i) {
3449 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3450 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3451 offloaded.push(desc->mIoHandle);
3452 }
3453 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003454 for (const auto& handle : offloaded) {
3455 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003456 }
3457 }
3458 // update master mono for all remaining outputs
3459 for (size_t i = 0; i < mOutputs.size(); ++i) {
3460 updateMono(mOutputs.keyAt(i));
3461 }
3462 return NO_ERROR;
3463}
3464
3465status_t AudioPolicyManager::getMasterMono(bool *mono)
3466{
3467 *mono = mMasterMono;
3468 return NO_ERROR;
3469}
3470
Eric Laurentac9cef52017-06-09 15:46:26 -07003471float AudioPolicyManager::getStreamVolumeDB(
3472 audio_stream_type_t stream, int index, audio_devices_t device)
3473{
3474 return computeVolume(stream, index, device);
3475}
3476
jiabin81772902018-04-02 17:52:27 -07003477status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3478 FormatVector& formats) {
3479 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3480 return BAD_VALUE;
3481 }
3482 String8 reply;
3483 reply = mpClientInterface->getParameters(
3484 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3485 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3486 AudioParameter repliedParameters(reply);
3487 if (repliedParameters.get(
3488 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3489 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3490 return BAD_VALUE;
3491 }
3492 for (auto format : formatsFromString(reply.string())) {
3493 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3494 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3495 if (format == AAC_FORMATS[i]) {
3496 format = AUDIO_FORMAT_AAC_LC;
3497 break;
3498 }
3499 }
3500 bool exist = false;
3501 for (size_t i = 0; i < formats.size(); i++) {
3502 if (format == formats[i]) {
3503 exist = true;
3504 break;
3505 }
3506 }
3507 bool isSurroundFormat = false;
3508 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3509 if (SURROUND_FORMATS[i] == format) {
3510 isSurroundFormat = true;
3511 break;
3512 }
3513 }
3514 if (!exist && isSurroundFormat) {
3515 formats.add(format);
3516 }
3517 }
3518 return NO_ERROR;
3519}
3520
3521status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3522 audio_format_t *surroundFormats,
3523 bool *surroundFormatsEnabled,
3524 bool reported)
3525{
3526 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3527 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3528 return BAD_VALUE;
3529 }
3530 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3531 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3532
3533 // Only return value if there is HDMI output.
3534 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3535 return INVALID_OPERATION;
3536 }
3537
3538 size_t formatsWritten = 0;
3539 size_t formatsMax = *numSurroundFormats;
3540 *numSurroundFormats = 0;
3541 FormatVector formats;
3542 if (reported) {
3543 // Only get surround formats which are reported by device.
3544 // First list already open outputs that can be routed to this device
3545 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3546 SortedVector<audio_io_handle_t> outputs;
3547 bool reportedFormatFound = false;
3548 status_t status;
3549 sp<SwAudioOutputDescriptor> desc;
3550 for (size_t i = 0; i < mOutputs.size(); i++) {
3551 desc = mOutputs.valueAt(i);
3552 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3553 outputs.add(mOutputs.keyAt(i));
3554 }
3555 }
3556 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003557 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003558 AUDIO_DEVICE_OUT_HDMI);
3559 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3560 String8 address = hdmiOutputDevices[i]->mAddress;
3561 for (const auto& hwModule : mHwModules) {
3562 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3563 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3564 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3565 profile->supportDeviceAddress(address)) {
3566 size_t j;
3567 for (j = 0; j < outputs.size(); j++) {
3568 desc = mOutputs.valueFor(outputs.itemAt(j));
3569 if (!desc->isDuplicated() && desc->mProfile == profile) {
3570 break;
3571 }
3572 }
3573 if (j != outputs.size()) {
3574 status = getSupportedFormats(outputs.itemAt(j), formats);
3575 reportedFormatFound |= (status == NO_ERROR);
3576 continue;
3577 }
3578
3579 if (!profile->canOpenNewIo()) {
3580 ALOGW("Max Output number %u already opened for this profile %s",
3581 profile->maxOpenCount, profile->getTagName().c_str());
3582 continue;
3583 }
3584
3585 ALOGV("opening output for device %08x with params %s profile %p name %s",
3586 device, address.string(), profile.get(), profile->getName().string());
3587 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3588 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3589 status_t status = desc->open(nullptr, device, address,
3590 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3591 &output);
3592
3593 if (status == NO_ERROR) {
3594 status = getSupportedFormats(output, formats);
3595 reportedFormatFound |= (status == NO_ERROR);
3596 desc->close();
3597 output = AUDIO_IO_HANDLE_NONE;
3598 }
3599 }
3600 }
3601 }
3602 }
3603
3604 if (!reportedFormatFound) {
3605 return UNKNOWN_ERROR;
3606 }
3607 } else {
3608 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3609 formats.add(SURROUND_FORMATS[i]);
3610 }
3611 }
3612 for (size_t i = 0; i < formats.size(); i++) {
3613 if (formatsWritten < formatsMax) {
3614 surroundFormats[formatsWritten] = formats[i];
3615 bool formatEnabled = false;
3616 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3617 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3618 formatEnabled =
3619 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3620 break;
3621 }
3622 } else {
3623 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3624 }
3625 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3626 }
3627 (*numSurroundFormats)++;
3628 }
3629 return NO_ERROR;
3630}
3631
3632status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3633{
3634 // Check if audio format is a surround formats.
3635 bool isSurroundFormat = false;
3636 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3637 if (audioFormat == SURROUND_FORMATS[i]) {
3638 isSurroundFormat = true;
3639 break;
3640 }
3641 }
3642 if (!isSurroundFormat) {
3643 return BAD_VALUE;
3644 }
3645
3646 // Should only be called when MANUAL.
3647 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3648 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3649 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3650 return INVALID_OPERATION;
3651 }
3652
3653 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3654 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3655 return NO_ERROR;
3656 }
3657
3658 // The operation is valid only when there is HDMI output available.
3659 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3660 return INVALID_OPERATION;
3661 }
3662
3663 if (enabled) {
3664 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3665 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3666 mSurroundFormats.insert(AAC_FORMATS[i]);
3667 }
3668 } else {
3669 mSurroundFormats.insert(audioFormat);
3670 }
3671 } else {
3672 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3673 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3674 mSurroundFormats.erase(AAC_FORMATS[i]);
3675 }
3676 } else {
3677 mSurroundFormats.erase(audioFormat);
3678 }
3679 }
3680
3681 sp<SwAudioOutputDescriptor> outputDesc;
3682 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003683 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003684 AUDIO_DEVICE_OUT_HDMI);
3685 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3686 // Simulate reconnection to update enabled surround sound formats.
3687 String8 address = hdmiOutputDevices[i]->mAddress;
3688 String8 name = hdmiOutputDevices[i]->getName();
3689 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3690 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3691 address.c_str(),
3692 name.c_str());
3693 if (status != NO_ERROR) {
3694 continue;
3695 }
3696 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3697 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3698 address.c_str(),
3699 name.c_str());
3700 profileUpdated |= (status == NO_ERROR);
3701 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003702 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003703 AUDIO_DEVICE_IN_HDMI);
3704 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3705 // Simulate reconnection to update enabled surround sound formats.
3706 String8 address = hdmiInputDevices[i]->mAddress;
3707 String8 name = hdmiInputDevices[i]->getName();
3708 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3709 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3710 address.c_str(),
3711 name.c_str());
3712 if (status != NO_ERROR) {
3713 continue;
3714 }
3715 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3716 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3717 address.c_str(),
3718 name.c_str());
3719 profileUpdated |= (status == NO_ERROR);
3720 }
3721
3722 // Undo the surround formats change due to no audio profiles updated.
3723 if (!profileUpdated) {
3724 if (enabled) {
3725 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3726 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3727 mSurroundFormats.erase(AAC_FORMATS[i]);
3728 }
3729 } else {
3730 mSurroundFormats.erase(audioFormat);
3731 }
3732 } else {
3733 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3734 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3735 mSurroundFormats.insert(AAC_FORMATS[i]);
3736 }
3737 } else {
3738 mSurroundFormats.insert(audioFormat);
3739 }
3740 }
3741 }
3742
3743 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3744}
3745
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003746void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3747{
3748 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3749
3750 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3751 for (size_t i = 0; i < activeInputs.size(); i++) {
3752 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3753 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3754 for (size_t j = 0; j < activeSessions.size(); j++) {
3755 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3756 if (activeSession->uid() == uid) {
3757 activeSession->setSilenced(silenced);
3758 }
3759 }
3760 }
3761}
3762
Eric Laurentd60560a2015-04-10 11:31:20 -07003763status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3764{
3765 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3766
3767 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3768 if (patchDesc == 0) {
3769 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3770 sourceDesc->mPatchDesc->mHandle);
3771 return BAD_VALUE;
3772 }
3773 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3774
Eric Laurent28d09f02016-03-08 10:43:05 -08003775 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003776 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3777 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003778 status_t status = stopSource(swOutputDesc, stream, false);
3779 if (status == NO_ERROR) {
3780 swOutputDesc->stop();
3781 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003782 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3783 } else {
3784 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3785 if (hwOutputDesc != 0) {
3786 // release patch between src device and output device
3787 // close Hwoutput and remove from mHwOutputs
3788 } else {
3789 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3790 }
3791 }
3792 return NO_ERROR;
3793}
3794
3795sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3796 audio_io_handle_t output, routing_strategy strategy)
3797{
3798 sp<AudioSourceDescriptor> source;
3799 for (size_t i = 0; i < mAudioSources.size(); i++) {
3800 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3801 routing_strategy sourceStrategy =
3802 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3803 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3804 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3805 source = sourceDesc;
3806 break;
3807 }
3808 }
3809 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003810}
3811
Eric Laurente552edb2014-03-10 17:42:56 -07003812// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003813// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003814// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003815uint32_t AudioPolicyManager::nextAudioPortGeneration()
3816{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003817 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003818}
3819
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003820#ifdef USE_XML_AUDIO_POLICY_CONF
3821// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3822static const char *kConfigLocationList[] =
3823 {"/odm/etc", "/vendor/etc", "/system/etc"};
3824static const int kConfigLocationListSize =
3825 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3826
3827static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3828 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003829 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003830 status_t ret;
3831
Petri Gyntherf497f292018-04-17 18:46:10 -07003832 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3833 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3834 // A2DP offload supported but disabled: try to use special XML file
3835 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3836 }
3837 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3838
3839 for (const char* fileName : fileNames) {
3840 for (int i = 0; i < kConfigLocationListSize; i++) {
3841 PolicySerializer serializer;
3842 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3843 "%s/%s", kConfigLocationList[i], fileName);
3844 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3845 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003846 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003847 return ret;
3848 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003849 }
3850 }
3851 return ret;
3852}
3853#endif
3854
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003855AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3856 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003857 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003858 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003859 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003860 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003861 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003862#ifdef USE_XML_AUDIO_POLICY_CONF
3863 mVolumeCurves(new VolumeCurvesCollection()),
3864 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003865 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003866#else
3867 mVolumeCurves(new StreamDescriptorCollection()),
3868 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3869 mDefaultOutputDevice),
3870#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003871 mAudioPortGeneration(1),
3872 mBeaconMuteRefCount(0),
3873 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003874 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003875 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003876 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003877 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3878 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003879{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003880}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003881
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003882AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3883 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3884{
3885 loadConfig();
3886 initialize();
3887}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003888
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003889void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003890#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003891 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003892#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003893 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3894 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003895#endif
3896 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003897 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003898 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899}
3900
3901status_t AudioPolicyManager::initialize() {
3902 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003903
3904 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003905 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3906 if (!engineInstance) {
3907 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003908 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003909 }
3910 // Retrieve the Policy Manager Interface
3911 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3912 if (mEngine == NULL) {
3913 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003914 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003915 }
3916 mEngine->setObserver(this);
3917 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003918 if (status != NO_ERROR) {
3919 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3920 return status;
3921 }
François Gaffie2110e042015-03-24 08:41:51 +01003922
Eric Laurent3a4311c2014-03-17 12:00:47 -07003923 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003924 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003925 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3926 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003927 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003928 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003929 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3930 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003931 continue;
3932 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003933 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 // open all output streams needed to access attached devices
3935 // except for direct output streams that are only opened when they are actually
3936 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003937 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003938 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003939 if (!outProfile->canOpenNewIo()) {
3940 ALOGE("Invalid Output profile max open count %u for profile %s",
3941 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3942 continue;
3943 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003944 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003945 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003946 continue;
3947 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003948 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003949 mTtsOutputAvailable = true;
3950 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003951
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003952 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003953 continue;
3954 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003955 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003956 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3957 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003958 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003959 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003960 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003961 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003962 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003963 if ((profileType & outputDeviceTypes) == 0) {
3964 continue;
3965 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003966 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3967 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003968 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003969 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3970 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003971 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3972 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003973 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003974 status_t status = outputDesc->open(nullptr, profileType, address,
3975 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003976
3977 if (status != NO_ERROR) {
3978 ALOGW("Cannot open output stream for device %08x on hw module %s",
3979 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003980 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003981 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003982 for (const auto& dev : supportedDevices) {
3983 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003984 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003985 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003986 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003987 }
3988 }
3989 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003991 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003992 }
3993 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003994 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003995 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003996 true,
3997 0,
3998 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003999 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004000 }
Eric Laurente552edb2014-03-10 17:42:56 -07004001 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004002 // open input streams needed to access attached devices to validate
4003 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004004 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004005 if (!inProfile->canOpenNewIo()) {
4006 ALOGE("Invalid Input profile max open count %u for profile %s",
4007 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4008 continue;
4009 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004010 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004011 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004012 continue;
4013 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004014 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004015 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004016 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4017
Eric Laurentd78f1532014-09-16 16:38:20 -07004018 if ((profileType & inputDeviceTypes) == 0) {
4019 continue;
4020 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004021 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004022 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004023
Mikhail Naganov708e0382018-05-30 09:53:04 -07004024 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004025 // the inputs vector must be of size >= 1, but we don't want to crash here
4026 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4027 : String8("");
4028 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4029 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4030
Eric Laurentd78f1532014-09-16 16:38:20 -07004031 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004032 status_t status = inputDesc->open(nullptr,
4033 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004034 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004035 AUDIO_SOURCE_MIC,
4036 AUDIO_INPUT_FLAG_NONE,
4037 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004038
4039 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004040 for (const auto& dev : inProfile->getSupportedDevices()) {
4041 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004042 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004043 if (index >= 0) {
4044 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4045 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004046 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004047 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004048 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004049 }
4050 }
Eric Laurentfe231122017-11-17 17:48:06 -08004051 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004052 } else {
4053 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004054 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004055 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004056 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004057 }
4058 }
4059 // make sure all attached devices have been allocated a unique ID
4060 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004061 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004062 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4064 continue;
4065 }
François Gaffie2110e042015-03-24 08:41:51 +01004066 // The device is now validated and can be appended to the available devices of the engine
4067 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4068 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004069 i++;
4070 }
4071 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004072 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004073 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4075 continue;
4076 }
François Gaffie2110e042015-03-24 08:41:51 +01004077 // The device is now validated and can be appended to the available devices of the engine
4078 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4079 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 i++;
4081 }
4082 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004083 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004084 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004085 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 }
jiabin9ff780e2018-03-19 18:19:52 -07004087 // If microphones address is empty, set it according to device type
4088 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4089 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4090 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4091 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4092 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4093 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4094 }
4095 }
4096 }
Eric Laurente552edb2014-03-10 17:42:56 -07004097
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004098 if (mPrimaryOutput == 0) {
4099 ALOGE("Failed to open primary output");
4100 status = NO_INIT;
4101 }
Eric Laurente552edb2014-03-10 17:42:56 -07004102
4103 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004104 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004105}
4106
Eric Laurente0720872014-03-11 09:30:41 -07004107AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004108{
Eric Laurente552edb2014-03-10 17:42:56 -07004109 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004110 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004111 }
4112 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004113 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004114 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004115 mAvailableOutputDevices.clear();
4116 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004117 mOutputs.clear();
4118 mInputs.clear();
4119 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004120 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004121 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004122}
4123
Eric Laurente0720872014-03-11 09:30:41 -07004124status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004125{
Eric Laurent87ffa392015-05-22 10:32:38 -07004126 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004127}
4128
Eric Laurente552edb2014-03-10 17:42:56 -07004129// ---
4130
Eric Laurent98e38192018-02-15 18:31:53 -08004131void AudioPolicyManager::addOutput(audio_io_handle_t output,
4132 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004133{
Eric Laurent1c333e22014-05-20 10:48:17 -07004134 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004135 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004136 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004137 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004138 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004139}
4140
François Gaffie53615e22015-03-19 09:24:12 +01004141void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4142{
4143 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004144 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004145}
4146
Eric Laurent98e38192018-02-15 18:31:53 -08004147void AudioPolicyManager::addInput(audio_io_handle_t input,
4148 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004149{
Eric Laurent1c333e22014-05-20 10:48:17 -07004150 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004151 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004152}
Eric Laurente552edb2014-03-10 17:42:56 -07004153
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004154void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004155 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004156 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004157 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004158 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004159 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004160 if (devDesc != 0) {
4161 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4162 desc->mIoHandle, address.string());
4163 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004164 }
4165}
4166
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004167status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004168 audio_policy_dev_state_t state,
4169 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004170 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004171{
François Gaffie53615e22015-03-19 09:24:12 +01004172 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004173 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004174
4175 if (audio_device_is_digital(device)) {
4176 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004177 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004178 }
Eric Laurente552edb2014-03-10 17:42:56 -07004179
Eric Laurent3b73df72014-03-11 09:06:29 -07004180 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004181 // first list already open outputs that can be routed to this device
4182 for (size_t i = 0; i < mOutputs.size(); i++) {
4183 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004184 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004185 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004186 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4187 outputs.add(mOutputs.keyAt(i));
4188 } else {
4189 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004190 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004191 }
Eric Laurente552edb2014-03-10 17:42:56 -07004192 }
4193 }
4194 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004195 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004196 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004197 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4198 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004199 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004200 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004201 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004202 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004203 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4204 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004205 }
Eric Laurente552edb2014-03-10 17:42:56 -07004206 }
4207 }
4208 }
4209
Eric Laurent7b279bb2015-12-14 10:18:23 -08004210 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004211
Eric Laurente552edb2014-03-10 17:42:56 -07004212 if (profiles.isEmpty() && outputs.isEmpty()) {
4213 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4214 return BAD_VALUE;
4215 }
4216
4217 // open outputs for matching profiles if needed. Direct outputs are also opened to
4218 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4219 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004220 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004221
4222 // nothing to do if one output is already opened for this profile
4223 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004224 for (j = 0; j < outputs.size(); j++) {
4225 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004226 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004227 // matching profile: save the sample rates, format and channel masks supported
4228 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004229 if (audio_device_is_digital(device)) {
4230 devDesc->importAudioPort(profile);
4231 }
Eric Laurente552edb2014-03-10 17:42:56 -07004232 break;
4233 }
4234 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004235 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004236 continue;
4237 }
4238
Eric Laurent3974e3b2017-12-07 17:58:43 -08004239 if (!profile->canOpenNewIo()) {
4240 ALOGW("Max Output number %u already opened for this profile %s",
4241 profile->maxOpenCount, profile->getTagName().c_str());
4242 continue;
4243 }
4244
Eric Laurent83efe1c2017-07-09 16:51:08 -07004245 ALOGV("opening output for device %08x with params %s profile %p name %s",
4246 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004247 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004248 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004249 status_t status = desc->open(nullptr, device, address,
4250 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004251
Eric Laurentfe231122017-11-17 17:48:06 -08004252 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004253 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004254 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004255 char *param = audio_device_address_to_parameter(device, address);
4256 mpClientInterface->setParameters(output, String8(param));
4257 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004258 }
Phil Burk00eeb322016-03-31 12:41:00 -07004259 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004260 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004261 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004262 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004263 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004264 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004265 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004266 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004267 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4268 profile->pickAudioProfile(
4269 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004270 config.offload_info.sample_rate = config.sample_rate;
4271 config.offload_info.channel_mask = config.channel_mask;
4272 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004273
4274 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4275 AUDIO_OUTPUT_FLAG_NONE, &output);
4276 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004277 output = AUDIO_IO_HANDLE_NONE;
4278 }
Eric Laurentd4692962014-05-05 18:13:44 -07004279 }
4280
Eric Laurentcf2c0212014-07-25 16:20:43 -07004281 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004282 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004283 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004284 sp<AudioPolicyMix> policyMix;
4285 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004286 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4287 address.string());
4288 }
François Gaffie036e1e92015-03-19 10:16:24 +01004289 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004290 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004291
Eric Laurent87ffa392015-05-22 10:32:38 -07004292 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4293 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004294 // no duplicated output for direct outputs and
4295 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004296 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004297
Eric Laurentd4692962014-05-05 18:13:44 -07004298 //TODO: configure audio effect output stage here
4299
4300 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004301 sp<SwAudioOutputDescriptor> dupOutputDesc =
4302 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4303 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4304 &duplicatedOutput);
4305 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004306 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004307 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004308 } else {
4309 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004310 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004311 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004312 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004313 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004314 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004315 }
Eric Laurente552edb2014-03-10 17:42:56 -07004316 }
4317 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004318 } else {
4319 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004320 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004321 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004322 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004323 profiles.removeAt(profile_index);
4324 profile_index--;
4325 } else {
4326 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004327 // Load digital format info only for digital devices
4328 if (audio_device_is_digital(device)) {
4329 devDesc->importAudioPort(profile);
4330 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004331
François Gaffie53615e22015-03-19 09:24:12 +01004332 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004333 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4334 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004335 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004336 NULL/*patch handle*/, address.string());
4337 }
Eric Laurente552edb2014-03-10 17:42:56 -07004338 ALOGV("checkOutputsForDevice(): adding output %d", output);
4339 }
4340 }
4341
4342 if (profiles.isEmpty()) {
4343 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4344 return BAD_VALUE;
4345 }
Eric Laurentd4692962014-05-05 18:13:44 -07004346 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004347 // check if one opened output is not needed any more after disconnecting one device
4348 for (size_t i = 0; i < mOutputs.size(); i++) {
4349 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004350 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004351 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004352 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004353 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004354 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004355 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4357 mOutputs.keyAt(i));
4358 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004359 }
Eric Laurente552edb2014-03-10 17:42:56 -07004360 }
4361 }
Eric Laurentd4692962014-05-05 18:13:44 -07004362 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004363 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004364 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4365 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004366 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004367 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004368 "clearing direct output profile %zu on module %s",
4369 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004370 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
4372 }
4373 }
4374 }
4375 return NO_ERROR;
4376}
4377
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004378status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004379 audio_policy_dev_state_t state,
4380 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004381 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004382{
Paul McLean9080a4c2015-06-18 08:24:02 -07004383 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004384 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004385
4386 if (audio_device_is_digital(device)) {
4387 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004388 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004389 }
4390
Eric Laurentd4692962014-05-05 18:13:44 -07004391 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4392 // first list already open inputs that can be routed to this device
4393 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4394 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004395 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004396 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4397 inputs.add(mInputs.keyAt(input_index));
4398 }
4399 }
4400
4401 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004402 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004403 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004404 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004405 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004406 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004407 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004408
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004409 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004410 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004411 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004412 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004413 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4414 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004415 }
Eric Laurentd4692962014-05-05 18:13:44 -07004416 }
4417 }
4418 }
4419
4420 if (profiles.isEmpty() && inputs.isEmpty()) {
4421 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4422 return BAD_VALUE;
4423 }
4424
4425 // open inputs for matching profiles if needed. Direct inputs are also opened to
4426 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4427 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4428
Eric Laurent1c333e22014-05-20 10:48:17 -07004429 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004430
Eric Laurentd4692962014-05-05 18:13:44 -07004431 // nothing to do if one input is already opened for this profile
4432 size_t input_index;
4433 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4434 desc = mInputs.valueAt(input_index);
4435 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004436 if (audio_device_is_digital(device)) {
4437 devDesc->importAudioPort(profile);
4438 }
Eric Laurentd4692962014-05-05 18:13:44 -07004439 break;
4440 }
4441 }
4442 if (input_index != mInputs.size()) {
4443 continue;
4444 }
4445
Eric Laurent3974e3b2017-12-07 17:58:43 -08004446 if (!profile->canOpenNewIo()) {
4447 ALOGW("Max Input number %u already opened for this profile %s",
4448 profile->maxOpenCount, profile->getTagName().c_str());
4449 continue;
4450 }
4451
Eric Laurentfe231122017-11-17 17:48:06 -08004452 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004453 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004454 status_t status = desc->open(nullptr,
4455 device,
4456 address,
4457 AUDIO_SOURCE_MIC,
4458 AUDIO_INPUT_FLAG_NONE,
4459 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004460
Eric Laurentcf2c0212014-07-25 16:20:43 -07004461 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004462 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004463 char *param = audio_device_address_to_parameter(device, address);
4464 mpClientInterface->setParameters(input, String8(param));
4465 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004466 }
Phil Burk00eeb322016-03-31 12:41:00 -07004467 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004468 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004469 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004470 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004471 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004472 }
4473
4474 if (input != 0) {
4475 addInput(input, desc);
4476 }
4477 } // endif input != 0
4478
Eric Laurentcf2c0212014-07-25 16:20:43 -07004479 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004480 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004481 profiles.removeAt(profile_index);
4482 profile_index--;
4483 } else {
4484 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004485 if (audio_device_is_digital(device)) {
4486 devDesc->importAudioPort(profile);
4487 }
Eric Laurentd4692962014-05-05 18:13:44 -07004488 ALOGV("checkInputsForDevice(): adding input %d", input);
4489 }
4490 } // end scan profiles
4491
4492 if (profiles.isEmpty()) {
4493 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4494 return BAD_VALUE;
4495 }
4496 } else {
4497 // Disconnect
4498 // check if one opened input is not needed any more after disconnecting one device
4499 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4500 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004501 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004502 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4503 mInputs.keyAt(input_index));
4504 inputs.add(mInputs.keyAt(input_index));
4505 }
4506 }
4507 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004508 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004509 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004510 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004511 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004512 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004513 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004514 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4515 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004516 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004517 }
4518 }
4519 }
4520 } // end disconnect
4521
4522 return NO_ERROR;
4523}
4524
4525
Eric Laurente0720872014-03-11 09:30:41 -07004526void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004527{
4528 ALOGV("closeOutput(%d)", output);
4529
Eric Laurentc75307b2015-03-17 15:29:32 -07004530 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004531 if (outputDesc == NULL) {
4532 ALOGW("closeOutput() unknown output %d", output);
4533 return;
4534 }
François Gaffie036e1e92015-03-19 10:16:24 +01004535 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004536
Eric Laurente552edb2014-03-10 17:42:56 -07004537 // look for duplicated outputs connected to the output being removed.
4538 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004539 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (dupOutputDesc->isDuplicated() &&
4541 (dupOutputDesc->mOutput1 == outputDesc ||
4542 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004543 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004544 if (dupOutputDesc->mOutput1 == outputDesc) {
4545 outputDesc2 = dupOutputDesc->mOutput2;
4546 } else {
4547 outputDesc2 = dupOutputDesc->mOutput1;
4548 }
4549 // As all active tracks on duplicated output will be deleted,
4550 // and as they were also referenced on the other output, the reference
4551 // count for their stream type must be adjusted accordingly on
4552 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004553 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004554 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004555 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004556 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004557 }
Eric Laurent733ce942017-12-07 12:18:25 -08004558 // stop() will be a no op if the output is still active but is needed in case all
4559 // active streams refcounts where cleared above
4560 if (wasActive) {
4561 outputDesc2->stop();
4562 }
Eric Laurente552edb2014-03-10 17:42:56 -07004563 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4564 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4565
4566 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004567 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004568 }
4569 }
4570
Eric Laurent05b90f82014-08-27 15:32:29 -07004571 nextAudioPortGeneration();
4572
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004573 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004574 if (index >= 0) {
4575 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004576 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004577 mAudioPatches.removeItemsAt(index);
4578 mpClientInterface->onAudioPatchListUpdate();
4579 }
4580
Eric Laurentfe231122017-11-17 17:48:06 -08004581 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004582
François Gaffie53615e22015-03-19 09:24:12 +01004583 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004584 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004585}
4586
4587void AudioPolicyManager::closeInput(audio_io_handle_t input)
4588{
4589 ALOGV("closeInput(%d)", input);
4590
4591 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4592 if (inputDesc == NULL) {
4593 ALOGW("closeInput() unknown input %d", input);
4594 return;
4595 }
4596
Eric Laurent6a94d692014-05-20 11:18:06 -07004597 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004598
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004599 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004600 if (index >= 0) {
4601 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004602 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004603 mAudioPatches.removeItemsAt(index);
4604 mpClientInterface->onAudioPatchListUpdate();
4605 }
4606
Eric Laurentfe231122017-11-17 17:48:06 -08004607 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004608 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004609}
4610
Eric Laurentc75307b2015-03-17 15:29:32 -07004611SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4612 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004613 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004614{
4615 SortedVector<audio_io_handle_t> outputs;
4616
4617 ALOGVV("getOutputsForDevice() device %04x", device);
4618 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004619 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004620 i, openOutputs.valueAt(i)->isDuplicated(),
4621 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004622 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4623 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4624 outputs.add(openOutputs.keyAt(i));
4625 }
4626 }
4627 return outputs;
4628}
4629
Eric Laurente0720872014-03-11 09:30:41 -07004630bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004631 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004632{
4633 if (outputs1.size() != outputs2.size()) {
4634 return false;
4635 }
4636 for (size_t i = 0; i < outputs1.size(); i++) {
4637 if (outputs1[i] != outputs2[i]) {
4638 return false;
4639 }
4640 }
4641 return true;
4642}
4643
Mikhail Naganov37977152018-07-11 15:54:44 -07004644void AudioPolicyManager::checkForDeviceAndOutputChanges()
4645{
4646 checkForDeviceAndOutputChanges([](){ return false; });
4647}
4648
4649void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4650{
4651 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4652 // output is suspended before any tracks are moved to it
4653 checkA2dpSuspend();
4654 checkOutputForAllStrategies();
4655 if (onOutputsChecked()) checkA2dpSuspend();
4656 updateDevicesAndOutputs();
4657}
4658
Eric Laurente0720872014-03-11 09:30:41 -07004659void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004660{
4661 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4662 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4663 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4664 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4665
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004666 // also take into account external policy-related changes: add all outputs which are
4667 // associated with policies in the "before" and "after" output vectors
4668 ALOGVV("checkOutputForStrategy(): policy related outputs");
4669 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004670 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004671 if (desc != 0 && desc->mPolicyMix != NULL) {
4672 srcOutputs.add(desc->mIoHandle);
4673 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4674 }
4675 }
4676 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004677 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004678 if (desc != 0 && desc->mPolicyMix != NULL) {
4679 dstOutputs.add(desc->mIoHandle);
4680 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4681 }
4682 }
4683
Eric Laurente552edb2014-03-10 17:42:56 -07004684 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004685 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4686 // audio from invalidated tracks will be rendered when unmuting
4687 uint32_t maxLatency = 0;
4688 for (audio_io_handle_t srcOut : srcOutputs) {
4689 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4690 if (desc != 0 && maxLatency < desc->latency()) {
4691 maxLatency = desc->latency();
4692 }
4693 }
Eric Laurente552edb2014-03-10 17:42:56 -07004694 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4695 strategy, srcOutputs[0], dstOutputs[0]);
4696 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004697 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004698 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4699 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004700 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004701 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004702 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004703 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004704 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004705 if (source != 0){
4706 connectAudioSource(source);
4707 }
Eric Laurente552edb2014-03-10 17:42:56 -07004708 }
4709
4710 // Move effects associated to this strategy from previous output to new output
4711 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004712 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
4714 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004715 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004716 if (getStrategy((audio_stream_type_t)i) == strategy) {
4717 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 }
4719 }
4720 }
4721}
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004724{
François Gaffie2110e042015-03-24 08:41:51 +01004725 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004726 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004727 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004728 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004729 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004730 checkOutputForStrategy(STRATEGY_SONIFICATION);
4731 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004732 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004733 checkOutputForStrategy(STRATEGY_MEDIA);
4734 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004735 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004736}
4737
Eric Laurente0720872014-03-11 09:30:41 -07004738void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004739{
François Gaffie53615e22015-03-19 09:24:12 +01004740 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004741 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004742 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004743 return;
4744 }
4745
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004747 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4748 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4749 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004750
4751 // if suspended, restore A2DP output if:
4752 // ((SCO device is NOT connected) ||
4753 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4754 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004755 //
Eric Laurentf732e072016-08-03 19:30:28 -07004756 // if not suspended, suspend A2DP output if:
4757 // (SCO device is connected) &&
4758 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4759 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004760 //
4761 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004762 if (!isScoConnected ||
4763 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4764 AUDIO_POLICY_FORCE_BT_SCO) &&
4765 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4766 AUDIO_POLICY_FORCE_BT_SCO) &&
4767 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004768 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004769
4770 mpClientInterface->restoreOutput(a2dpOutput);
4771 mA2dpSuspended = false;
4772 }
4773 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004774 if (isScoConnected &&
4775 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4776 AUDIO_POLICY_FORCE_BT_SCO) ||
4777 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4778 AUDIO_POLICY_FORCE_BT_SCO) ||
4779 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004780 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004781
4782 mpClientInterface->suspendOutput(a2dpOutput);
4783 mA2dpSuspended = true;
4784 }
4785 }
4786}
4787
Eric Laurentc75307b2015-03-17 15:29:32 -07004788audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4789 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004790{
4791 audio_devices_t device = AUDIO_DEVICE_NONE;
4792
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004793 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 if (index >= 0) {
4795 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4796 if (patchDesc->mUid != mUidCached) {
4797 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004798 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 return outputDesc->device();
4800 }
4801 }
4802
Eric Laurentf3a5a602018-05-22 18:42:55 -07004803 // Check if an explicit routing request exists for an active stream on this output and
4804 // use it in priority before any other rule
4805 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4806 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4807 audio_devices_t forcedDevice =
4808 mOutputRoutes.getActiveDeviceForStream(
4809 (audio_stream_type_t)stream, mAvailableOutputDevices);
4810
4811 if (forcedDevice != AUDIO_DEVICE_NONE) {
4812 return forcedDevice;
4813 }
4814 }
4815 }
4816
Eric Laurente552edb2014-03-10 17:42:56 -07004817 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004818 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004819 // use device for strategy enforced audible
4820 // 2: we are in call or the strategy phone is active on the output:
4821 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004822 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004823 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004824 // 4: the strategy for enforced audible is active but not enforced on the output:
4825 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004826 // 5: the strategy accessibility is active on the output:
4827 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004828 // 6: the strategy "respectful" sonification is active on the output:
4829 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004830 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004831 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004832 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004833 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004834 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004835 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004836
4837 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4838 // with a refined rule considering mutually exclusive devices (using same backend)
4839 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004840 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004841 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004842 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4843 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004844 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004845 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004846 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004847 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004848 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4849 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004850 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4851 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004852 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004853 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004854 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004855 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004856 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004857 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004858 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004859 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004860 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004861 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004862 }
4863
Eric Laurent1c333e22014-05-20 10:48:17 -07004864 ALOGV("getNewOutputDevice() selected device %x", device);
4865 return device;
4866}
4867
Eric Laurentfb66dd92016-01-28 18:32:03 -08004868audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004869{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004870 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004871
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004872 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004873 if (index >= 0) {
4874 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4875 if (patchDesc->mUid != mUidCached) {
4876 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004877 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 return inputDesc->mDevice;
4879 }
4880 }
4881
Eric Laurentdc95a252018-04-12 12:46:56 -07004882 // If we are not in call and no client is active on this input, this methods returns
4883 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004884 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004885 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4886 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4887 }
4888 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004889 device = getDeviceAndMixForInputSource(source);
4890 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004891
Eric Laurente552edb2014-03-10 17:42:56 -07004892 return device;
4893}
4894
Eric Laurent794fde22016-03-11 09:50:45 -08004895bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4896 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004897 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004898}
4899
Eric Laurente0720872014-03-11 09:30:41 -07004900uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004901 return (uint32_t)getStrategy(stream);
4902}
4903
Eric Laurente0720872014-03-11 09:30:41 -07004904audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004905 // By checking the range of stream before calling getStrategy, we avoid
4906 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4907 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004908 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 return AUDIO_DEVICE_NONE;
4910 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004911 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004912 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4913 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004914 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004915 }
Eric Laurent794fde22016-03-11 09:50:45 -08004916 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004917 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004918 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004919 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4920 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004921 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004922 curDevices |= outputDesc->device();
4923 }
4924 }
4925 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004926 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004927
4928 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4929 and doesn't really need to.*/
4930 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4931 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4932 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4933 }
Eric Laurente552edb2014-03-10 17:42:56 -07004934 return devices;
4935}
4936
François Gaffie2110e042015-03-24 08:41:51 +01004937routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4938{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004939 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004940 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004941}
4942
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004943uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4944 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004945 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4946 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4947 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004948 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4949 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4950 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004951 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004952 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004953}
4954
Eric Laurente0720872014-03-11 09:30:41 -07004955void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004956 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004957 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004958 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4959 updateDevicesAndOutputs();
4960 break;
4961 default:
4962 break;
4963 }
4964}
4965
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004966uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004967
4968 // skip beacon mute management if a dedicated TTS output is available
4969 if (mTtsOutputAvailable) {
4970 return 0;
4971 }
4972
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004973 switch(event) {
4974 case STARTING_OUTPUT:
4975 mBeaconMuteRefCount++;
4976 break;
4977 case STOPPING_OUTPUT:
4978 if (mBeaconMuteRefCount > 0) {
4979 mBeaconMuteRefCount--;
4980 }
4981 break;
4982 case STARTING_BEACON:
4983 mBeaconPlayingRefCount++;
4984 break;
4985 case STOPPING_BEACON:
4986 if (mBeaconPlayingRefCount > 0) {
4987 mBeaconPlayingRefCount--;
4988 }
4989 break;
4990 }
4991
4992 if (mBeaconMuteRefCount > 0) {
4993 // any playback causes beacon to be muted
4994 return setBeaconMute(true);
4995 } else {
4996 // no other playback: unmute when beacon starts playing, mute when it stops
4997 return setBeaconMute(mBeaconPlayingRefCount == 0);
4998 }
4999}
5000
5001uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5002 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5003 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5004 // keep track of muted state to avoid repeating mute/unmute operations
5005 if (mBeaconMuted != mute) {
5006 // mute/unmute AUDIO_STREAM_TTS on all outputs
5007 ALOGV("\t muting %d", mute);
5008 uint32_t maxLatency = 0;
5009 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005010 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005011 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005012 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005013 0 /*delay*/, AUDIO_DEVICE_NONE);
5014 const uint32_t latency = desc->latency() * 2;
5015 if (latency > maxLatency) {
5016 maxLatency = latency;
5017 }
5018 }
5019 mBeaconMuted = mute;
5020 return maxLatency;
5021 }
5022 return 0;
5023}
5024
Eric Laurente0720872014-03-11 09:30:41 -07005025audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005026 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005027{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005028 // Check if an explicit routing request exists for a stream type corresponding to the
5029 // specified strategy and use it in priority over default routing rules.
5030 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5031 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5032 audio_devices_t forcedDevice =
5033 mOutputRoutes.getActiveDeviceForStream(
5034 (audio_stream_type_t)stream, mAvailableOutputDevices);
5035 if (forcedDevice != AUDIO_DEVICE_NONE) {
5036 return forcedDevice;
5037 }
Paul McLeanaa981192015-03-21 09:55:15 -07005038 }
5039 }
5040
Eric Laurente552edb2014-03-10 17:42:56 -07005041 if (fromCache) {
5042 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5043 strategy, mDeviceForStrategy[strategy]);
5044 return mDeviceForStrategy[strategy];
5045 }
François Gaffie2110e042015-03-24 08:41:51 +01005046 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005047}
5048
Eric Laurente0720872014-03-11 09:30:41 -07005049void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005050{
5051 for (int i = 0; i < NUM_STRATEGIES; i++) {
5052 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5053 }
5054 mPreviousOutputs = mOutputs;
5055}
5056
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005057uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005058 audio_devices_t prevDevice,
5059 uint32_t delayMs)
5060{
5061 // mute/unmute strategies using an incompatible device combination
5062 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5063 // if unmuting, unmute only after the specified delay
5064 if (outputDesc->isDuplicated()) {
5065 return 0;
5066 }
5067
5068 uint32_t muteWaitMs = 0;
5069 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005070 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005071
5072 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5073 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005074 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005075 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5076 bool doMute = false;
5077
5078 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5079 doMute = true;
5080 outputDesc->mStrategyMutedByDevice[i] = true;
5081 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5082 doMute = true;
5083 outputDesc->mStrategyMutedByDevice[i] = false;
5084 }
Eric Laurent99401132014-05-07 19:48:15 -07005085 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005086 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005087 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005088 // skip output if it does not share any device with current output
5089 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5090 == AUDIO_DEVICE_NONE) {
5091 continue;
5092 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005093 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005094 mute ? "muting" : "unmuting", i, curDevice);
5095 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005096 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005097 if (mute) {
5098 // FIXME: should not need to double latency if volume could be applied
5099 // immediately by the audioflinger mixer. We must account for the delay
5100 // between now and the next time the audioflinger thread for this output
5101 // will process a buffer (which corresponds to one buffer size,
5102 // usually 1/2 or 1/4 of the latency).
5103 if (muteWaitMs < desc->latency() * 2) {
5104 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005105 }
5106 }
5107 }
5108 }
5109 }
5110 }
5111
Eric Laurent99401132014-05-07 19:48:15 -07005112 // temporary mute output if device selection changes to avoid volume bursts due to
5113 // different per device volumes
5114 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005115 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5116 // temporary mute duration is conservatively set to 4 times the reported latency
5117 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5118 if (muteWaitMs < tempMuteWaitMs) {
5119 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005120 }
Eric Laurentdc462862016-07-19 12:29:53 -07005121
Eric Laurent99401132014-05-07 19:48:15 -07005122 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005123 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005124 // make sure that we do not start the temporary mute period too early in case of
5125 // delayed device change
5126 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005127 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005128 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005129 }
5130 }
5131 }
5132
Eric Laurente552edb2014-03-10 17:42:56 -07005133 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5134 if (muteWaitMs > delayMs) {
5135 muteWaitMs -= delayMs;
5136 usleep(muteWaitMs * 1000);
5137 return muteWaitMs;
5138 }
5139 return 0;
5140}
5141
Eric Laurentc75307b2015-03-17 15:29:32 -07005142uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005143 audio_devices_t device,
5144 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005146 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005147 const char *address,
5148 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005149{
Eric Laurentc75307b2015-03-17 15:29:32 -07005150 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005151 AudioParameter param;
5152 uint32_t muteWaitMs;
5153
5154 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005155 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5156 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5157 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5158 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005159 return muteWaitMs;
5160 }
5161 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5162 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005163 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005164 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005165 return 0;
5166 }
5167
5168 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005169 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005170
5171 audio_devices_t prevDevice = outputDesc->mDevice;
5172
Paul McLeanaa981192015-03-21 09:55:15 -07005173 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005174
5175 if (device != AUDIO_DEVICE_NONE) {
5176 outputDesc->mDevice = device;
5177 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005178
5179 // if the outputs are not materially active, there is no need to mute.
5180 if (requiresMuteCheck) {
5181 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5182 } else {
5183 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5184 muteWaitMs = 0;
5185 }
Eric Laurente552edb2014-03-10 17:42:56 -07005186
5187 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005188 // the requested device is AUDIO_DEVICE_NONE
5189 // OR the requested device is the same as current device
5190 // AND force is not specified
5191 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005192 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005193 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5194 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005195 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005196 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005197 return muteWaitMs;
5198 }
5199
5200 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005201
Eric Laurente552edb2014-03-10 17:42:56 -07005202 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005203 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005204 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005205 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005206 DeviceVector deviceList;
5207 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005208 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005209 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005210 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5211 device, String8(address));
5212 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005213 }
5214
Eric Laurent1c333e22014-05-20 10:48:17 -07005215 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005216 PatchBuilder patchBuilder;
5217 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005218 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005219 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005220 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005221 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005222 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005223
5224 // inform all input as well
5225 for (size_t i = 0; i < mInputs.size(); i++) {
5226 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005227 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005228 AudioParameter inputCmd = AudioParameter();
5229 ALOGV("%s: inform input %d of device:%d", __func__,
5230 inputDescriptor->mIoHandle, device);
5231 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5232 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5233 inputCmd.toString(),
5234 delayMs);
5235 }
5236 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005237 }
Eric Laurente552edb2014-03-10 17:42:56 -07005238
5239 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005240 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005241
5242 return muteWaitMs;
5243}
5244
Eric Laurentc75307b2015-03-17 15:29:32 -07005245status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 int delayMs,
5247 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005248{
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 ssize_t index;
5250 if (patchHandle) {
5251 index = mAudioPatches.indexOfKey(*patchHandle);
5252 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005253 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 }
5255 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005256 return INVALID_OPERATION;
5257 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5259 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005260 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005261 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 removeAudioPatch(patchDesc->mHandle);
5263 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005264 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005265 return status;
5266}
5267
5268status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5269 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 bool force,
5271 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005272{
5273 status_t status = NO_ERROR;
5274
Eric Laurent1f2f2232014-06-02 12:01:23 -07005275 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005276 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5277 inputDesc->mDevice = device;
5278
Mikhail Naganov708e0382018-05-30 09:53:04 -07005279 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005281 PatchBuilder patchBuilder;
5282 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005283 // AUDIO_SOURCE_HOTWORD is for internal use only:
5284 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005285 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5286 auto result = usecase;
5287 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5288 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5289 }
5290 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005291 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005292 addSource(deviceList.itemAt(0));
5293 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005294 }
5295 }
5296 return status;
5297}
5298
Eric Laurent6a94d692014-05-20 11:18:06 -07005299status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5300 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005301{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005302 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 ssize_t index;
5304 if (patchHandle) {
5305 index = mAudioPatches.indexOfKey(*patchHandle);
5306 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005307 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 }
5309 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 return INVALID_OPERATION;
5311 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5313 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005314 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005315 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 removeAudioPatch(patchDesc->mHandle);
5317 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005318 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005319 return status;
5320}
5321
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005322sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005323 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005324 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005325 audio_format_t& format,
5326 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005327 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005328{
5329 // Choose an input profile based on the requested capture parameters: select the first available
5330 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005331 //
5332 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5333 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005334
Glenn Kasten730b9262018-03-29 15:01:26 -07005335 sp<IOProfile> firstInexact;
5336 uint32_t updatedSamplingRate = 0;
5337 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5338 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005339 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005340 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005341 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005342 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005343 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005344 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005345 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005346 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005347 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005348 &channelMask /*updatedChannelMask*/,
5349 // FIXME ugly cast
5350 (audio_output_flags_t) flags,
5351 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005352 return profile;
5353 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005354 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5355 samplingRate,
5356 &updatedSamplingRate,
5357 format,
5358 &updatedFormat,
5359 channelMask,
5360 &updatedChannelMask,
5361 // FIXME ugly cast
5362 (audio_output_flags_t) flags,
5363 false /*exactMatchRequiredForInputFlags*/)) {
5364 firstInexact = profile;
5365 }
5366
Eric Laurente552edb2014-03-10 17:42:56 -07005367 }
5368 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005369 if (firstInexact != nullptr) {
5370 samplingRate = updatedSamplingRate;
5371 format = updatedFormat;
5372 channelMask = updatedChannelMask;
5373 return firstInexact;
5374 }
Eric Laurente552edb2014-03-10 17:42:56 -07005375 return NULL;
5376}
5377
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005378
5379audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005380 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005381{
François Gaffie036e1e92015-03-19 10:16:24 +01005382 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5383 audio_devices_t selectedDeviceFromMix =
5384 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005385
François Gaffie036e1e92015-03-19 10:16:24 +01005386 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5387 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005388 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005389 return getDeviceForInputSource(inputSource);
5390}
5391
5392audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5393{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005394 // Routing
5395 // Scan the whole RouteMap to see if we have an explicit route:
5396 // if the input source in the RouteMap is the same as the argument above,
5397 // and activity count is non-zero and the device in the route descriptor is available
5398 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005399 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5400 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005401 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005402 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005403 return route->mDeviceDescriptor->type();
5404 }
5405 }
5406
5407 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005408}
5409
Eric Laurente0720872014-03-11 09:30:41 -07005410float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005411 int index,
5412 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005413{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005414 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005415
5416 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5417 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5418 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5419 // the ringtone volume
5420 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5421 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5422 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5423 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5424 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5425 }
5426
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005427 // in-call: always cap volume by voice volume + some low headroom
5428 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005429 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005430 switch (stream) {
5431 case AUDIO_STREAM_SYSTEM:
5432 case AUDIO_STREAM_RING:
5433 case AUDIO_STREAM_MUSIC:
5434 case AUDIO_STREAM_ALARM:
5435 case AUDIO_STREAM_NOTIFICATION:
5436 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5437 case AUDIO_STREAM_DTMF:
5438 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005439 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005440 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005441 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005442 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005443 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005444 if (volumeDB > maxVoiceVolDb) {
5445 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5446 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5447 volumeDB = maxVoiceVolDb;
5448 }
5449 } break;
5450 default:
5451 break;
5452 }
5453 }
5454
Eric Laurente552edb2014-03-10 17:42:56 -07005455 // if a headset is connected, apply the following rules to ring tones and notifications
5456 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005457 // - always attenuate notifications volume by 6dB
5458 // - attenuate ring tones volume by 6dB unless music is not playing and
5459 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005460 // - if music is playing, always limit the volume to current music volume,
5461 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005462 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005463 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5464 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5465 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005466 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005467 AUDIO_DEVICE_OUT_USB_HEADSET |
5468 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005469 ((stream_strategy == STRATEGY_SONIFICATION)
5470 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005471 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005472 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005473 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005474 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005475 // when the phone is ringing we must consider that music could have been paused just before
5476 // by the music application and behave as if music was active if the last music track was
5477 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005478 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005479 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005480 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005481 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005482 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005483 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5484 musicDevice),
5485 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005486 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5487 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005488 if (volumeDB > minVolDB) {
5489 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005490 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005491 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005492 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5493 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5494 // on A2DP, also ensure notification volume is not too low compared to media when
5495 // intended to be played
5496 if ((volumeDB > -96.0f) &&
5497 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5498 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5499 stream, device,
5500 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5501 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5502 }
5503 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005504 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5505 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005506 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005507 }
5508 }
5509
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005510 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005511}
5512
Eric Laurent3839bc02018-07-10 18:33:34 -07005513int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5514 audio_stream_type_t srcStream,
5515 audio_stream_type_t dstStream)
5516{
5517 if (srcStream == dstStream) {
5518 return srcIndex;
5519 }
5520 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5521 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5522 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5523 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5524
5525 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5526}
5527
Eric Laurente0720872014-03-11 09:30:41 -07005528status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005529 int index,
5530 const sp<AudioOutputDescriptor>& outputDesc,
5531 audio_devices_t device,
5532 int delayMs,
5533 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005534{
Eric Laurente552edb2014-03-10 17:42:56 -07005535 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005536 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005537 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005538 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005539 return NO_ERROR;
5540 }
François Gaffie2110e042015-03-24 08:41:51 +01005541 audio_policy_forced_cfg_t forceUseForComm =
5542 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005543 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005544 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5545 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005546 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005547 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005548 return INVALID_OPERATION;
5549 }
5550
Eric Laurentc75307b2015-03-17 15:29:32 -07005551 if (device == AUDIO_DEVICE_NONE) {
5552 device = outputDesc->device();
5553 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005554
Eric Laurentffbc80f2015-03-18 18:30:19 -07005555 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005556 if (outputDesc->isFixedVolume(device) ||
5557 // Force VoIP volume to max for bluetooth SCO
5558 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5559 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005560 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005561 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005562
Eric Laurentffbc80f2015-03-18 18:30:19 -07005563 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005564
Eric Laurent3b73df72014-03-11 09:06:29 -07005565 if (stream == AUDIO_STREAM_VOICE_CALL ||
5566 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005567 float voiceVolume;
5568 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005569 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005570 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005571 } else {
5572 voiceVolume = 1.0;
5573 }
5574
Eric Laurent18fba842016-03-31 14:41:26 -07005575 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005576 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5577 mLastVoiceVolume = voiceVolume;
5578 }
5579 }
5580
5581 return NO_ERROR;
5582}
5583
Eric Laurentc75307b2015-03-17 15:29:32 -07005584void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5585 audio_devices_t device,
5586 int delayMs,
5587 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005588{
Eric Laurentc75307b2015-03-17 15:29:32 -07005589 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005590
Eric Laurent794fde22016-03-11 09:50:45 -08005591 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005592 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005593 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005594 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005595 device,
5596 delayMs,
5597 force);
5598 }
5599}
5600
Eric Laurente0720872014-03-11 09:30:41 -07005601void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005602 bool on,
5603 const sp<AudioOutputDescriptor>& outputDesc,
5604 int delayMs,
5605 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005606{
Eric Laurent72249d52015-06-08 11:12:15 -07005607 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5608 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005609 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005610 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005611 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005612 }
5613 }
5614}
5615
Eric Laurente0720872014-03-11 09:30:41 -07005616void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005617 bool on,
5618 const sp<AudioOutputDescriptor>& outputDesc,
5619 int delayMs,
5620 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005621{
Eric Laurente552edb2014-03-10 17:42:56 -07005622 if (device == AUDIO_DEVICE_NONE) {
5623 device = outputDesc->device();
5624 }
5625
Eric Laurentc75307b2015-03-17 15:29:32 -07005626 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5627 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005628
5629 if (on) {
5630 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005631 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005632 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005633 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005634 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005635 }
5636 }
5637 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5638 outputDesc->mMuteCount[stream]++;
5639 } else {
5640 if (outputDesc->mMuteCount[stream] == 0) {
5641 ALOGV("setStreamMute() unmuting non muted stream!");
5642 return;
5643 }
5644 if (--outputDesc->mMuteCount[stream] == 0) {
5645 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005646 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005647 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005648 device,
5649 delayMs);
5650 }
5651 }
5652}
5653
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005654audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5655{
5656 // flags to stream type mapping
5657 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5658 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5659 }
5660 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5661 return AUDIO_STREAM_BLUETOOTH_SCO;
5662 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005663 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5664 return AUDIO_STREAM_TTS;
5665 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005666
5667 // usage to stream type mapping
5668 switch (attr->usage) {
5669 case AUDIO_USAGE_MEDIA:
5670 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005671 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005672 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5673 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005674 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5675 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005676 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5677 return AUDIO_STREAM_SYSTEM;
5678 case AUDIO_USAGE_VOICE_COMMUNICATION:
5679 return AUDIO_STREAM_VOICE_CALL;
5680
5681 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5682 return AUDIO_STREAM_DTMF;
5683
5684 case AUDIO_USAGE_ALARM:
5685 return AUDIO_STREAM_ALARM;
5686 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5687 return AUDIO_STREAM_RING;
5688
5689 case AUDIO_USAGE_NOTIFICATION:
5690 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5691 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5692 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5693 case AUDIO_USAGE_NOTIFICATION_EVENT:
5694 return AUDIO_STREAM_NOTIFICATION;
5695
5696 case AUDIO_USAGE_UNKNOWN:
5697 default:
5698 return AUDIO_STREAM_MUSIC;
5699 }
5700}
Eric Laurente83b55d2014-11-14 10:06:21 -08005701
François Gaffie53615e22015-03-19 09:24:12 +01005702bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5703{
Eric Laurente83b55d2014-11-14 10:06:21 -08005704 // has flags that map to a strategy?
5705 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5706 return true;
5707 }
5708
5709 // has known usage?
5710 switch (paa->usage) {
5711 case AUDIO_USAGE_UNKNOWN:
5712 case AUDIO_USAGE_MEDIA:
5713 case AUDIO_USAGE_VOICE_COMMUNICATION:
5714 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5715 case AUDIO_USAGE_ALARM:
5716 case AUDIO_USAGE_NOTIFICATION:
5717 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5718 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5719 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5720 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5721 case AUDIO_USAGE_NOTIFICATION_EVENT:
5722 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5723 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5724 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5725 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005726 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005727 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005728 break;
5729 default:
5730 return false;
5731 }
5732 return true;
5733}
5734
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005735bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005736 routing_strategy strategy, uint32_t inPastMs,
5737 nsecs_t sysTime) const
5738{
5739 if ((sysTime == 0) && (inPastMs != 0)) {
5740 sysTime = systemTime();
5741 }
Eric Laurent794fde22016-03-11 09:50:45 -08005742 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005743 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5744 (NUM_STRATEGIES == strategy)) &&
5745 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5746 return true;
5747 }
5748 }
5749 return false;
5750}
5751
Eric Laurent484e9272018-06-07 17:29:23 -07005752bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5753 routing_strategy strategy, uint32_t inPastMs,
5754 nsecs_t sysTime) const
5755{
5756 for (size_t i = 0; i < mOutputs.size(); i++) {
5757 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5758 if (outputDesc->sharesHwModuleWith(desc)
5759 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5760 return true;
5761 }
5762 }
5763 return false;
5764}
5765
François Gaffie2110e042015-03-24 08:41:51 +01005766audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5767{
5768 return mEngine->getForceUse(usage);
5769}
5770
5771bool AudioPolicyManager::isInCall()
5772{
5773 return isStateInCall(mEngine->getPhoneState());
5774}
5775
5776bool AudioPolicyManager::isStateInCall(int state)
5777{
5778 return is_state_in_call(state);
5779}
5780
Eric Laurentd60560a2015-04-10 11:31:20 -07005781void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5782{
5783 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5784 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5785 if (sourceDesc->mDevice->equals(deviceDesc)) {
5786 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5787 stopAudioSource(sourceDesc->getHandle());
5788 }
5789 }
5790
5791 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5792 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5793 bool release = false;
5794 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5795 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5796 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5797 source->ext.device.type == deviceDesc->type()) {
5798 release = true;
5799 }
5800 }
5801 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5802 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5803 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5804 sink->ext.device.type == deviceDesc->type()) {
5805 release = true;
5806 }
5807 }
5808 if (release) {
5809 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5810 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5811 }
5812 }
5813}
5814
Phil Burk09bc4612016-02-24 15:58:15 -08005815// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005816void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5817 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005818 // TODO Set this based on Config properties.
5819 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005820
5821 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5822 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005823 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005824
jiabin81772902018-04-02 17:52:27 -07005825 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5826 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5827 formats.clear();
5828 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5829 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005830 }
jiabin81772902018-04-02 17:52:27 -07005831 // Always enable IEC61937 when in MANUAL mode.
5832 formats.add(AUDIO_FORMAT_IEC61937);
5833 } else { // NEVER, AUTO or ALWAYS
5834 // Analyze original support for various formats.
5835 bool supportsAC3 = false;
5836 bool supportsOtherSurround = false;
5837 bool supportsIEC61937 = false;
5838 mSurroundFormats.clear();
5839 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5840 audio_format_t format = formats[formatIndex];
5841 switch (format) {
5842 case AUDIO_FORMAT_AC3:
5843 supportsAC3 = true;
5844 break;
5845 case AUDIO_FORMAT_E_AC3:
5846 case AUDIO_FORMAT_DTS:
5847 case AUDIO_FORMAT_DTS_HD:
5848 // If ALWAYS, remove all other surround formats here
5849 // since we will add them later.
5850 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5851 formats.removeAt(formatIndex);
5852 formatIndex--;
5853 }
5854 supportsOtherSurround = true;
5855 break;
5856 case AUDIO_FORMAT_IEC61937:
5857 supportsIEC61937 = true;
5858 break;
5859 default:
5860 break;
5861 }
5862 }
Phil Burk09bc4612016-02-24 15:58:15 -08005863
jiabin81772902018-04-02 17:52:27 -07005864 // Modify formats based on surround preferences.
5865 // If NEVER, remove support for surround formats.
5866 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5867 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5868 // Remove surround sound related formats.
5869 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5870 audio_format_t format = formats[formatIndex];
5871 switch(format) {
5872 case AUDIO_FORMAT_AC3:
5873 case AUDIO_FORMAT_E_AC3:
5874 case AUDIO_FORMAT_DTS:
5875 case AUDIO_FORMAT_DTS_HD:
5876 case AUDIO_FORMAT_IEC61937:
5877 formats.removeAt(formatIndex);
5878 break;
5879 default:
5880 formatIndex++; // keep it
5881 break;
5882 }
5883 }
5884 supportsAC3 = false;
5885 supportsOtherSurround = false;
5886 supportsIEC61937 = false;
5887 }
5888 } else { // AUTO or ALWAYS
5889 // Most TVs support AC3 even if they do not report it in the EDID.
5890 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5891 && !supportsAC3) {
5892 formats.add(AUDIO_FORMAT_AC3);
5893 supportsAC3 = true;
5894 }
5895
5896 // If ALWAYS, add support for raw surround formats if all are missing.
5897 // This assumes that if any of these formats are reported by the HAL
5898 // then the report is valid and should not be modified.
5899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5900 formats.add(AUDIO_FORMAT_E_AC3);
5901 formats.add(AUDIO_FORMAT_DTS);
5902 formats.add(AUDIO_FORMAT_DTS_HD);
5903 supportsOtherSurround = true;
5904 }
5905
5906 // Add support for IEC61937 if any raw surround supported.
5907 // The HAL could do this but add it here, just in case.
5908 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5909 formats.add(AUDIO_FORMAT_IEC61937);
5910 supportsIEC61937 = true;
5911 }
5912
5913 // Add reported surround sound formats to enabled surround formats.
5914 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005915 audio_format_t format = formats[formatIndex];
5916 switch(format) {
5917 case AUDIO_FORMAT_AC3:
5918 case AUDIO_FORMAT_E_AC3:
5919 case AUDIO_FORMAT_DTS:
5920 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005921 case AUDIO_FORMAT_AAC_LC:
5922 case AUDIO_FORMAT_DOLBY_TRUEHD:
5923 case AUDIO_FORMAT_E_AC3_JOC:
5924 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005925 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005926 break;
5927 }
Phil Burk09bc4612016-02-24 15:58:15 -08005928 }
Phil Burk07ac1142016-03-25 13:39:29 -07005929 }
Phil Burk09bc4612016-02-24 15:58:15 -08005930 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005931}
5932
5933// Modify the list of channel masks supported.
5934void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5935 ChannelsVector &channelMasks = *channelMasksPtr;
5936 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5937 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5938
5939 // If NEVER, then remove support for channelMasks > stereo.
5940 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5941 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5942 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5943 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5944 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5945 channelMasks.removeAt(maskIndex);
5946 } else {
5947 maskIndex++;
5948 }
5949 }
jiabin81772902018-04-02 17:52:27 -07005950 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5951 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5952 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005953 bool supports5dot1 = false;
5954 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005955 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005956 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5957 supports5dot1 = true;
5958 break;
5959 }
5960 }
5961 // If not then add 5.1 support.
5962 if (!supports5dot1) {
5963 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5964 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5965 }
Phil Burk09bc4612016-02-24 15:58:15 -08005966 }
5967}
5968
Phil Burk00eeb322016-03-31 12:41:00 -07005969void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5970 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005971 AudioProfileVector &profiles)
5972{
5973 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005974
François Gaffie112b0af2015-11-19 16:13:25 +01005975 // Format MUST be checked first to update the list of AudioProfile
5976 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005977 reply = mpClientInterface->getParameters(
5978 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005979 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005980 AudioParameter repliedParameters(reply);
5981 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005982 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005983 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5984 return;
5985 }
Phil Burk09bc4612016-02-24 15:58:15 -08005986 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005987 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005988 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005989 }
Phil Burk09bc4612016-02-24 15:58:15 -08005990 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005991 }
François Gaffie112b0af2015-11-19 16:13:25 +01005992
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005993 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005994 ChannelsVector channelMasks;
5995 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005996 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005997 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005998
5999 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006000 reply = mpClientInterface->getParameters(
6001 ioHandle,
6002 requestedParameters.toString() + ";" +
6003 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006004 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006005 AudioParameter repliedParameters(reply);
6006 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006007 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006008 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006009 }
6010 }
6011 if (profiles.hasDynamicChannelsFor(format)) {
6012 reply = mpClientInterface->getParameters(ioHandle,
6013 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006014 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006015 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006016 AudioParameter repliedParameters(reply);
6017 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006018 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006019 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006020 if (device == AUDIO_DEVICE_OUT_HDMI) {
6021 filterSurroundChannelMasks(&channelMasks);
6022 }
François Gaffie112b0af2015-11-19 16:13:25 +01006023 }
6024 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006025 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006026 }
6027}
Eric Laurentd60560a2015-04-10 11:31:20 -07006028
Mikhail Naganovdc769682018-05-04 15:34:08 -07006029status_t AudioPolicyManager::installPatch(const char *caller,
6030 audio_patch_handle_t *patchHandle,
6031 AudioIODescriptorInterface *ioDescriptor,
6032 const struct audio_patch *patch,
6033 int delayMs)
6034{
6035 ssize_t index = mAudioPatches.indexOfKey(
6036 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6037 *patchHandle : ioDescriptor->getPatchHandle());
6038 sp<AudioPatch> patchDesc;
6039 status_t status = installPatch(
6040 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6041 if (status == NO_ERROR) {
6042 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6043 }
6044 return status;
6045}
6046
6047status_t AudioPolicyManager::installPatch(const char *caller,
6048 ssize_t index,
6049 audio_patch_handle_t *patchHandle,
6050 const struct audio_patch *patch,
6051 int delayMs,
6052 uid_t uid,
6053 sp<AudioPatch> *patchDescPtr)
6054{
6055 sp<AudioPatch> patchDesc;
6056 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6057 if (index >= 0) {
6058 patchDesc = mAudioPatches.valueAt(index);
6059 afPatchHandle = patchDesc->mAfPatchHandle;
6060 }
6061
6062 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6063 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6064 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6065 if (status == NO_ERROR) {
6066 if (index < 0) {
6067 patchDesc = new AudioPatch(patch, uid);
6068 addAudioPatch(patchDesc->mHandle, patchDesc);
6069 } else {
6070 patchDesc->mPatch = *patch;
6071 }
6072 patchDesc->mAfPatchHandle = afPatchHandle;
6073 if (patchHandle) {
6074 *patchHandle = patchDesc->mHandle;
6075 }
6076 nextAudioPortGeneration();
6077 mpClientInterface->onAudioPatchListUpdate();
6078 }
6079 if (patchDescPtr) *patchDescPtr = patchDesc;
6080 return status;
6081}
6082
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006083} // namespace android