blob: a141f49d3da812c77154c0b601554a9cc1fa832d [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 Gynther150b9842018-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>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070041#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070042#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070043#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010045#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010046#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010048#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010050#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010051#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurent3b73df72014-03-11 09:06:29 -070053namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurentdc462862016-07-19 12:29:53 -070055//FIXME: workaround for truncated touch sounds
56// to be removed when the problem is handled by system UI
57#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070058
59// Largest difference in dB on earpiece in call between the voice volume and another
60// media / notification / system volume.
61constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
62
jiabin81772902018-04-02 17:52:27 -070063#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64// Array of all surround formats.
65static const audio_format_t SURROUND_FORMATS[] = {
66 AUDIO_FORMAT_AC3,
67 AUDIO_FORMAT_E_AC3,
68 AUDIO_FORMAT_DTS,
69 AUDIO_FORMAT_DTS_HD,
70 AUDIO_FORMAT_AAC_LC,
71 AUDIO_FORMAT_DOLBY_TRUEHD,
72 AUDIO_FORMAT_E_AC3_JOC,
73};
74// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
75static const audio_format_t AAC_FORMATS[] = {
76 AUDIO_FORMAT_AAC_LC,
77 AUDIO_FORMAT_AAC_HE_V1,
78 AUDIO_FORMAT_AAC_HE_V2,
79 AUDIO_FORMAT_AAC_ELD,
80 AUDIO_FORMAT_AAC_XHE,
81};
82
Eric Laurente552edb2014-03-10 17:42:56 -070083// ----------------------------------------------------------------------------
84// AudioPolicyInterface implementation
85// ----------------------------------------------------------------------------
86
Eric Laurente0720872014-03-11 09:30:41 -070087status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080088 audio_policy_dev_state_t state,
89 const char *device_address,
90 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070091{
jiabina7b43792018-02-15 16:04:46 -080092 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
93 nextAudioPortGeneration();
94 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080095}
96
François Gaffie44481e72016-04-20 07:49:57 +020097void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
98 audio_policy_dev_state_t state,
99 const String8 &device_address)
100{
101 AudioParameter param(device_address);
102 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700103 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200104 param.addInt(key, device);
105 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
106}
107
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800109 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800110 const char *device_address,
111 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800112{
Paul McLeane743a472015-01-28 11:07:31 -0800113 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800114 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700115
116 // connect/disconnect only 1 device at a time
117 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
118
François Gaffie53615e22015-03-19 09:24:12 +0100119 sp<DeviceDescriptor> devDesc =
120 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800121
Eric Laurente552edb2014-03-10 17:42:56 -0700122 // handle output devices
123 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700124 SortedVector <audio_io_handle_t> outputs;
125
Eric Laurent3a4311c2014-03-17 12:00:47 -0700126 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
127
Eric Laurente552edb2014-03-10 17:42:56 -0700128 // save a copy of the opened output descriptors before any output is opened or closed
129 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
130 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 switch (state)
132 {
133 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800134 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700136 ALOGW("setDeviceConnectionState() device already connected: %x", device);
137 return INVALID_OPERATION;
138 }
139 ALOGV("setDeviceConnectionState() connecting device %x", device);
140
Eric Laurente552edb2014-03-10 17:42:56 -0700141 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700142 index = mAvailableOutputDevices.add(devDesc);
143 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100144 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700145 if (module == 0) {
146 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
147 device);
148 mAvailableOutputDevices.remove(devDesc);
149 return INVALID_OPERATION;
150 }
Paul McLeane743a472015-01-28 11:07:31 -0800151 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700152 } else {
153 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 }
155
François Gaffie44481e72016-04-20 07:49:57 +0200156 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
157 // parameters on newly connected devices (instead of opening the outputs...)
158 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
159
Eric Laurenta1d525f2015-01-29 13:36:45 -0800160 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700161 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200162
163 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
164 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700165 return INVALID_OPERATION;
166 }
François Gaffie2110e042015-03-24 08:41:51 +0100167 // Propagate device availability to Engine
168 mEngine->setDeviceConnectionState(devDesc, state);
169
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700170 // outputs should never be empty here
171 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
172 "checkOutputsForDevice() returned no outputs but status OK");
173 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
174 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800175
Eric Laurent3ae5f312015-02-03 17:12:08 -0800176 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700177 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700178 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700179 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700180 ALOGW("setDeviceConnectionState() device not connected: %x", device);
181 return INVALID_OPERATION;
182 }
183
Paul McLean5c477aa2014-08-20 16:47:57 -0700184 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
185
Paul McLeane743a472015-01-28 11:07:31 -0800186 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200187 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700188
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700190 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700191
Eric Laurenta1d525f2015-01-29 13:36:45 -0800192 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100193
194 // Propagate device availability to Engine
195 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700196 } break;
197
198 default:
199 ALOGE("setDeviceConnectionState() invalid state: %x", state);
200 return BAD_VALUE;
201 }
202
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
204 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700205 checkA2dpSuspend();
206 checkOutputForAllStrategies();
207 // outputs must be closed after checkOutputForAllStrategies() is executed
208 if (!outputs.isEmpty()) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800209 for (audio_io_handle_t output : outputs) {
210 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700211 // close unused outputs after device disconnection or direct outputs that have been
212 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700213 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700214 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
215 (desc->mDirectOpenCount == 0))) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800216 closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700219 // check again after closing A2DP output to reset mA2dpSuspended if needed
220 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700221 }
222
223 updateDevicesAndOutputs();
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;
371
372 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
373 device, device_address, device_name);
374
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800375 // connect/disconnect only 1 device at a time
376 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
377
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800378 // Check if the device is currently connected
379 sp<DeviceDescriptor> devDesc =
380 mHwModules.getDeviceDescriptor(device, device_address, device_name);
381 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
382 if (index < 0) {
383 // Nothing to do: device is not connected
384 return NO_ERROR;
385 }
386
387 // Toggle the device state: UNAVAILABLE -> AVAILABLE
388 // This will force reading again the device configuration
389 status = setDeviceConnectionState(device,
390 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
391 device_address, device_name);
392 if (status != NO_ERROR) {
393 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
394 status);
395 return status;
396 }
397
398 status = setDeviceConnectionState(device,
399 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
400 device_address, device_name);
401 if (status != NO_ERROR) {
402 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
403 status);
404 return status;
405 }
406
407 return NO_ERROR;
408}
409
Eric Laurentdc462862016-07-19 12:29:53 -0700410uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700411{
412 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700413 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700414
Andy Hunga76c7de2016-12-13 19:14:31 -0800415 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700416 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700417 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800418 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700419 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
420
421 // release existing RX patch if any
422 if (mCallRxPatch != 0) {
423 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
424 mCallRxPatch.clear();
425 }
426 // release TX patch if any
427 if (mCallTxPatch != 0) {
428 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
429 mCallTxPatch.clear();
430 }
431
432 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
433 // via setOutputDevice() on primary output.
434 // Otherwise, create two audio patches for TX and RX path.
435 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700436 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437 // If the TX device is also on the primary HW module, setOutputDevice() will take care
438 // of it due to legacy implementation. If not, create a patch.
439 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
440 == AUDIO_DEVICE_NONE) {
441 createTxPatch = true;
442 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700443 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800444 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 createTxPatch = true;
446 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700447 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800448 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
449 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700450
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800451 return muteWaitMs;
452}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800454sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
455 bool isRx, audio_devices_t device, uint32_t delayMs) {
456 struct audio_patch patch;
457 patch.num_sources = 1;
458 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700459
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800460 sp<DeviceDescriptor> txSourceDeviceDesc;
461 if (isRx) {
462 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
463 fillAudioPortConfigForDevice(
464 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
465 } else {
466 txSourceDeviceDesc = fillAudioPortConfigForDevice(
467 mAvailableInputDevices, device, &patch.sources[0]);
468 fillAudioPortConfigForDevice(
469 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
470 }
471
472 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
473 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
474 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
475 // request to reuse existing output stream if one is already opened to reach the target device
476 if (output != AUDIO_IO_HANDLE_NONE) {
477 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
478 ALOG_ASSERT(!outputDesc->isDuplicated(),
479 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
480 outputDesc->toAudioPortConfig(&patch.sources[1]);
481 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
482 patch.num_sources = 2;
483 }
484
485 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700486 // terminate active capture if on the same HW module as the call TX source device
487 // FIXME: would be better to refine to only inputs whose profile connects to the
488 // call TX device but this information is not in the audio patch and logic here must be
489 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800490 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800491 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
492 AudioSessionCollection activeSessions =
493 activeDesc->getAudioSessions(true /*activeOnly*/);
494 for (size_t j = 0; j < activeSessions.size(); j++) {
495 audio_session_t activeSession = activeSessions.keyAt(j);
496 stopInput(activeDesc->mIoHandle, activeSession);
497 releaseInput(activeDesc->mIoHandle, activeSession);
498 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700499 }
500 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700501 }
Eric Laurentdc462862016-07-19 12:29:53 -0700502
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800503 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
504 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
505 ALOGW_IF(status != NO_ERROR,
506 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
507 sp<AudioPatch> audioPatch;
508 if (status == NO_ERROR) {
509 audioPatch = new AudioPatch(&patch, mUidCached);
510 audioPatch->mAfPatchHandle = afPatchHandle;
511 audioPatch->mUid = mUidCached;
512 }
513 return audioPatch;
514}
515
516sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
517 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
518 DeviceVector deviceList = devices.getDevicesFromType(device);
519 ALOG_ASSERT(!deviceList.isEmpty(),
520 "%s() selected device type %#x is not in devices list", __func__, device);
521 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
522 deviceDesc->toAudioPortConfig(config);
523 return deviceDesc;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700524}
525
Eric Laurente0720872014-03-11 09:30:41 -0700526void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700527{
528 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100529 // store previous phone state for management of sonification strategy below
530 int oldState = mEngine->getPhoneState();
531
532 if (mEngine->setPhoneState(state) != NO_ERROR) {
533 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700534 return;
535 }
François Gaffie2110e042015-03-24 08:41:51 +0100536 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700537 // if leaving call state, handle special case of active streams
538 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800541 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700542 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700543 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800544
Eric Laurent63dea1d2015-07-02 17:10:28 -0700545 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800546 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700547 }
548
François Gaffie2110e042015-03-24 08:41:51 +0100549 /**
550 * Switching to or from incall state or switching between telephony and VoIP lead to force
551 * routing command.
552 */
553 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
554 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700555
556 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700557 checkA2dpSuspend();
558 checkOutputForAllStrategies();
559 updateDevicesAndOutputs();
560
Eric Laurente552edb2014-03-10 17:42:56 -0700561 int delayMs = 0;
562 if (isStateInCall(state)) {
563 nsecs_t sysTime = systemTime();
564 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700565 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700566 // mute media and sonification strategies and delay device switch by the largest
567 // latency of any output where either strategy is active.
568 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100569 if ((isStrategyActive(desc, STRATEGY_MEDIA,
570 SONIFICATION_HEADSET_MUSIC_DELAY,
571 sysTime) ||
572 isStrategyActive(desc, STRATEGY_SONIFICATION,
573 SONIFICATION_HEADSET_MUSIC_DELAY,
574 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 (delayMs < (int)desc->latency()*2)) {
576 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700577 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700578 setStrategyMute(STRATEGY_MEDIA, true, desc);
579 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700580 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700581 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
582 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700583 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
584 }
585 }
586
Eric Laurent87ffa392015-05-22 10:32:38 -0700587 if (hasPrimaryOutput()) {
588 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
589 // the device returned is not necessarily reachable via this output
590 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
591 // force routing command to audio hardware when ending call
592 // even if no device change is needed
593 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
594 rxDevice = mPrimaryOutput->device();
595 }
Eric Laurente552edb2014-03-10 17:42:56 -0700596
Eric Laurent87ffa392015-05-22 10:32:38 -0700597 if (state == AUDIO_MODE_IN_CALL) {
598 updateCallRouting(rxDevice, delayMs);
599 } else if (oldState == AUDIO_MODE_IN_CALL) {
600 if (mCallRxPatch != 0) {
601 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
602 mCallRxPatch.clear();
603 }
604 if (mCallTxPatch != 0) {
605 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
606 mCallTxPatch.clear();
607 }
608 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
609 } else {
610 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700611 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700612 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700613
614 // reevaluate routing on all outputs in case tracks have been started during the call
615 for (size_t i = 0; i < mOutputs.size(); i++) {
616 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
617 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
618 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
619 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), delayMs);
620 }
621 }
622
Eric Laurente552edb2014-03-10 17:42:56 -0700623 // if entering in call state, handle special case of active streams
624 // pertaining to sonification strategy see handleIncallSonification()
625 if (isStateInCall(state)) {
626 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800627 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700628 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700629 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700630
631 // force reevaluating accessibility routing when call starts
632 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700633 }
634
635 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700636 if (state == AUDIO_MODE_RINGTONE &&
637 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700638 mLimitRingtoneVolume = true;
639 } else {
640 mLimitRingtoneVolume = false;
641 }
642}
643
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700644audio_mode_t AudioPolicyManager::getPhoneState() {
645 return mEngine->getPhoneState();
646}
647
Eric Laurente0720872014-03-11 09:30:41 -0700648void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700649 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700650{
François Gaffie2110e042015-03-24 08:41:51 +0100651 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700652 if (config == mEngine->getForceUse(usage)) {
653 return;
654 }
Eric Laurente552edb2014-03-10 17:42:56 -0700655
François Gaffie2110e042015-03-24 08:41:51 +0100656 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
657 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
658 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700659 }
François Gaffie2110e042015-03-24 08:41:51 +0100660 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
661 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
662 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700663
664 // check for device and output changes triggered by new force usage
665 checkA2dpSuspend();
666 checkOutputForAllStrategies();
667 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800668
Eric Laurentdc462862016-07-19 12:29:53 -0700669 //FIXME: workaround for truncated touch sounds
670 // to be removed when the problem is handled by system UI
671 uint32_t delayMs = 0;
672 uint32_t waitMs = 0;
673 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
674 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
675 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700676 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700678 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700679 }
Eric Laurente552edb2014-03-10 17:42:56 -0700680 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700681 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
682 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
683 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700684 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
685 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700688 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700689 }
690 }
691
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800692 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800693 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700694 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800695 if (activeDesc->mProfile->getSupportedDevices().types() &
696 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
697 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700698 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800699 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700700 }
Eric Laurente552edb2014-03-10 17:42:56 -0700701 }
Eric Laurente552edb2014-03-10 17:42:56 -0700702}
703
Eric Laurente0720872014-03-11 09:30:41 -0700704void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700705{
706 ALOGV("setSystemProperty() property %s, value %s", property, value);
707}
708
709// Find a direct output profile compatible with the parameters passed, even if the input flags do
710// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800711sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700712 audio_devices_t device,
713 uint32_t samplingRate,
714 audio_format_t format,
715 audio_channel_mask_t channelMask,
716 audio_output_flags_t flags)
717{
Eric Laurent861a6282015-05-18 15:40:16 -0700718 // only retain flags that will drive the direct output profile selection
719 // if explicitly requested
720 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700721 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
722 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700723 flags =
724 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
725
726 sp<IOProfile> profile;
727
Mikhail Naganovd4120142017-12-06 15:49:22 -0800728 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800729 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700730 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700731 samplingRate, NULL /*updatedSamplingRate*/,
732 format, NULL /*updatedFormat*/,
733 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700734 flags)) {
735 continue;
736 }
737 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100738 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700739 continue;
740 }
741 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100742 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700743 continue;
744 }
745 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100746 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700747 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700748 }
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750 }
Eric Laurent861a6282015-05-18 15:40:16 -0700751 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Eric Laurentf4e63452017-11-06 19:31:46 +0000754audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700755{
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800758
759 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
760 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
761 // format, flags, etc. This may result in some discrepancy for functions that utilize
762 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
763 // and AudioSystem::getOutputSamplingRate().
764
Eric Laurentf4e63452017-11-06 19:31:46 +0000765 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
766 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700767
Eric Laurentf4e63452017-11-06 19:31:46 +0000768 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
769 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770}
771
Eric Laurente83b55d2014-11-14 10:06:21 -0800772status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
773 audio_io_handle_t *output,
774 audio_session_t session,
775 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700776 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800777 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200778 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700779 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800780 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700781{
Eric Laurente83b55d2014-11-14 10:06:21 -0800782 audio_attributes_t attributes;
783 if (attr != NULL) {
784 if (!isValidAttributes(attr)) {
785 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
786 attr->usage, attr->content_type, attr->flags,
787 attr->tags);
788 return BAD_VALUE;
789 }
790 attributes = *attr;
791 } else {
792 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
793 ALOGE("getOutputForAttr(): invalid stream type");
794 return BAD_VALUE;
795 }
796 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700797 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800798
799 // TODO: check for existing client for this port ID
800 if (*portId == AUDIO_PORT_HANDLE_NONE) {
801 *portId = AudioPort::getNextUniqueId();
802 }
803
Eric Laurentc75307b2015-03-17 15:29:32 -0700804 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800805 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100806 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800807 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100808 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800809 }
François Gaffie036e1e92015-03-19 10:16:24 +0100810 *stream = streamTypefromAttributesInt(&attributes);
811 *output = desc->mIoHandle;
812 ALOGV("getOutputForAttr() returns output %d", *output);
813 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800814 }
815 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
816 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
817 return BAD_VALUE;
818 }
819
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700820 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
821 " session %d selectedDeviceId %d",
822 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700823 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700824
825 *stream = streamTypefromAttributesInt(&attributes);
826
827 // Explicit routing?
828 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700829 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800830 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700831 }
832 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700833
Eric Laurente83b55d2014-11-14 10:06:21 -0800834 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700835 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700836
Eric Laurente83b55d2014-11-14 10:06:21 -0800837 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200838 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700839 }
840
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800841 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
842 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200843 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700844
Andy Hungc88b0642018-04-27 15:42:35 -0700845 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800846 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700847 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800848 return INVALID_OPERATION;
849 }
Paul McLeanaa981192015-03-21 09:55:15 -0700850
Eric Laurent2ac76942017-06-22 17:17:09 -0700851 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
852 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
853 : AUDIO_PORT_HANDLE_NONE;
854
855 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
856
Eric Laurente83b55d2014-11-14 10:06:21 -0800857 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858}
859
860audio_io_handle_t AudioPolicyManager::getOutputForDevice(
861 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800862 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700863 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800864 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200865 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700866{
Andy Hungc88b0642018-04-27 15:42:35 -0700867 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700868 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700869
Eric Laurente552edb2014-03-10 17:42:56 -0700870 // open a direct output if required by specified parameters
871 //force direct flag if offload flag is set: offloading implies a direct output stream
872 // and all common behaviors are driven by checking only the direct flag
873 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200874 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
875 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700876 }
Nadav Bar766fb022018-01-07 12:18:03 +0200877 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
878 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700879 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800880 // only allow deep buffering for music stream type
881 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200882 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700883 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200884 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700885 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
886 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200887 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800888 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700889 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200890 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700891 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800892 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200893 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700894 AUDIO_OUTPUT_FLAG_DIRECT);
895 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200896 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
897 stream == AUDIO_STREAM_MUSIC &&
898 audio_is_linear_pcm(config->format) &&
899 isInCall()) {
900 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700901 }
Eric Laurente552edb2014-03-10 17:42:56 -0700902
Nadav Bar766fb022018-01-07 12:18:03 +0200903
Eric Laurentb732cf52014-09-24 19:08:21 -0700904 sp<IOProfile> profile;
905
906 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700907 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200908 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800909 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
910 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700911 goto non_direct_output;
912 }
913
Andy Hung2ddee192015-12-18 17:34:44 -0800914 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
915 // This prevents creating an offloaded track and tearing it down immediately after start
916 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700917 // FIXME: We should check the audio session here but we do not have it in this context.
918 // This may prevent offloading in rare situations where effects are left active by apps
919 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700920
Nadav Bar766fb022018-01-07 12:18:03 +0200921 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800922 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700923 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800924 config->sample_rate,
925 config->format,
926 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200927 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700928 }
929
Eric Laurent1c333e22014-05-20 10:48:17 -0700930 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700931 // exclusive outputs for MMAP and Offload are enforced by different session ids.
932 for (size_t i = 0; i < mOutputs.size(); i++) {
933 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
934 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
935 // reuse direct output if currently open by the same client
936 // and configured with same parameters
937 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700938 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700939 (config->channel_mask == desc->mChannelMask) &&
940 (session == desc->mDirectClientSession)) {
941 desc->mDirectOpenCount++;
942 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
943 mOutputs.keyAt(i), session);
944 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700945 }
946 }
947 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800948
949 if (!profile->canOpenNewIo()) {
950 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700951 }
Eric Laurent861a6282015-05-18 15:40:16 -0700952
Eric Laurent3974e3b2017-12-07 17:58:43 -0800953 sp<SwAudioOutputDescriptor> outputDesc =
954 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800955
956 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
957 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
958 : String8("");
959
Nadav Bar766fb022018-01-07 12:18:03 +0200960 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700961
962 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700963 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800964 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700965 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800966 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
967 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
968 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
969 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
970 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700971 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800972 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700973 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800974 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800975 if (audio_is_linear_pcm(config->format) &&
976 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800977 goto non_direct_output;
978 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700979 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700981 outputDesc->mRefCount[stream] = 0;
982 outputDesc->mStopTime[stream] = 0;
983 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800984 outputDesc->mDirectClientSession = session;
985
Eric Laurente552edb2014-03-10 17:42:56 -0700986 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700987 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +0000988 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700989 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700990 return output;
991 }
992
Eric Laurentb732cf52014-09-24 19:08:21 -0700993non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700994
995 // A request for HW A/V sync cannot fallback to a mixed output because time
996 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -0800997 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -0700998 return AUDIO_IO_HANDLE_NONE;
999 }
1000
Eric Laurente552edb2014-03-10 17:42:56 -07001001 // ignoring channel mask due to downmix capability in mixer
1002
1003 // open a non direct output
1004
1005 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001006 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001007 // get which output is suitable for the specified stream. The actual
1008 // routing change will happen when startOutput() will be called
1009 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1010
Eric Laurent8838a382014-09-08 16:44:28 -07001011 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001012 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1013 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001015 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001016 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001017 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001018
Eric Laurente552edb2014-03-10 17:42:56 -07001019 return output;
1020}
1021
Eric Laurente0720872014-03-11 09:30:41 -07001022audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001023 audio_output_flags_t flags,
1024 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001025{
1026 // select one output among several that provide a path to a particular device or set of
1027 // devices (the list was previously build by getOutputsForDevice()).
1028 // The priority is as follows:
1029 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001030 // 2: the output with the bit depth the closest to the requested one
1031 // 3: the primary output
1032 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001033
1034 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
1037 if (outputs.size() == 1) {
1038 return outputs[0];
1039 }
1040
1041 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001042 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1043 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1044 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001045 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1046 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001047
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001048 for (audio_io_handle_t output : outputs) {
1049 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001050 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001051 // if a valid format is specified, skip output if not compatible
1052 if (format != AUDIO_FORMAT_INVALID) {
1053 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001054 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001055 continue;
1056 }
1057 } else if (!audio_is_linear_pcm(format)) {
1058 continue;
1059 }
Eric Laurente6930022016-02-11 10:20:40 -08001060 if (AudioPort::isBetterFormatMatch(
1061 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001062 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001063 bestFormat = outputDesc->mFormat;
1064 }
Eric Laurent8838a382014-09-08 16:44:28 -07001065 }
1066
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001067 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001068 if (commonFlags >= maxCommonFlags) {
1069 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001070 if (format != AUDIO_FORMAT_INVALID
1071 && AudioPort::isBetterFormatMatch(
1072 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001073 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001074 bestFormatForFlags = outputDesc->mFormat;
1075 }
1076 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001077 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001078 maxCommonFlags = commonFlags;
1079 bestFormatForFlags = outputDesc->mFormat;
1080 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001081 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001082 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001083 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001084 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001085 }
1086 }
1087 }
1088
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001089 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001090 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001091 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001092 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001093 return outputForFormat;
1094 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001095 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001096 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001097 }
1098
1099 return outputs[0];
1100}
1101
Eric Laurente0720872014-03-11 09:30:41 -07001102status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001103 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001104 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001105{
Paul McLeanaa981192015-03-21 09:55:15 -07001106 ALOGV("startOutput() output %d, stream %d, session %d",
1107 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001108 ssize_t index = mOutputs.indexOfKey(output);
1109 if (index < 0) {
1110 ALOGW("startOutput() unknown output %d", output);
1111 return BAD_VALUE;
1112 }
1113
Eric Laurentc75307b2015-03-17 15:29:32 -07001114 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1115
Eric Laurent733ce942017-12-07 12:18:25 -08001116 status_t status = outputDesc->start();
1117 if (status != NO_ERROR) {
1118 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001119 }
1120
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001121 // Routing?
1122 mOutputRoutes.incRouteActivity(session);
1123
Eric Laurentc75307b2015-03-17 15:29:32 -07001124 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001125 AudioMix *policyMix = NULL;
1126 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001127 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001128 policyMix = outputDesc->mPolicyMix;
1129 address = policyMix->mDeviceAddress.string();
1130 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1131 newDevice = policyMix->mDeviceType;
1132 } else {
1133 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1134 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001135 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001136 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001137 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001138 } else {
1139 newDevice = AUDIO_DEVICE_NONE;
1140 }
1141
1142 uint32_t delayMs = 0;
1143
Eric Laurent733ce942017-12-07 12:18:25 -08001144 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001145
1146 if (status != NO_ERROR) {
1147 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001148 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001149 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001150 }
1151 // Automatically enable the remote submix input when output is started on a re routing mix
1152 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001153 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1154 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001155 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1156 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001157 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001158 "remote-submix");
1159 }
1160
1161 if (delayMs != 0) {
1162 usleep(delayMs * 1000);
1163 }
1164
1165 return status;
1166}
1167
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001168status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001169 audio_stream_type_t stream,
1170 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001171 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001172 uint32_t *delayMs)
1173{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001174 // cannot start playback of STREAM_TTS if any other output is being used
1175 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001176
1177 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001178 if (stream == AUDIO_STREAM_TTS) {
1179 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001180 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001181 return INVALID_OPERATION;
1182 } else {
1183 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1184 }
1185 } else {
1186 // some playback other than beacon starts
1187 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1188 }
1189
Eric Laurent77305a62016-07-25 16:39:22 -07001190 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001191 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001192 bool force = !outputDesc->isActive() &&
1193 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001194
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001195 // requiresMuteCheck is false when we can bypass mute strategy.
1196 // It covers a common case when there is no materially active audio
1197 // and muting would result in unnecessary delay and dropped audio.
1198 const uint32_t outputLatencyMs = outputDesc->latency();
1199 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1200
Eric Laurente552edb2014-03-10 17:42:56 -07001201 // increment usage count for this stream on the requested output:
1202 // NOTE that the usage count is the same for duplicated output and hardware output which is
1203 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1204 outputDesc->changeRefCount(stream, 1);
1205
Eric Laurent36829f92017-04-07 19:04:42 -07001206 if (stream == AUDIO_STREAM_MUSIC) {
1207 selectOutputForMusicEffects();
1208 }
1209
Eric Laurent493404d2015-04-21 15:07:36 -07001210 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001211 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001212 if (device == AUDIO_DEVICE_NONE) {
1213 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001214 }
Eric Laurent36829f92017-04-07 19:04:42 -07001215
Eric Laurente552edb2014-03-10 17:42:56 -07001216 routing_strategy strategy = getStrategy(stream);
1217 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001218 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1219 (beaconMuteLatency > 0);
1220 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001222 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001223 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001224 // An output has a shared device if
1225 // - managed by the same hw module
1226 // - supports the currently selected device
1227 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1228 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1229
Eric Laurent77305a62016-07-25 16:39:22 -07001230 // force a device change if any other output is:
1231 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001232 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001233 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001234 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001235 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001236 // change the device currently selected by the other output.
1237 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001238 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001239 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001240 force = true;
1241 }
1242 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 // a notification so that audio focus effect can propagate, or that a mute/unmute
1244 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001245 const uint32_t latencyMs = desc->latency();
1246 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1247
1248 if (shouldWait && isActive && (waitMs < latencyMs)) {
1249 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001250 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001251
1252 // Require mute check if another output is on a shared device
1253 // and currently active to have proper drain and avoid pops.
1254 // Note restoring AudioTracks onto this output needs to invoke
1255 // a volume ramp if there is no mute.
1256 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001257 }
1258 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001259
1260 const uint32_t muteWaitMs =
1261 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001262
1263 // handle special case for sonification while in call
1264 if (isInCall()) {
1265 handleIncallSonification(stream, true, false);
1266 }
1267
1268 // apply volume rules for current stream and device if necessary
1269 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001270 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001271 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001272 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001273
1274 // update the outputs if starting an output with a stream that can affect notification
1275 // routing
1276 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001277
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001278 // force reevaluating accessibility routing when ringtone or alarm starts
1279 if (strategy == STRATEGY_SONIFICATION) {
1280 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1281 }
Eric Laurentdc462862016-07-19 12:29:53 -07001282
1283 if (waitMs > muteWaitMs) {
1284 *delayMs = waitMs - muteWaitMs;
1285 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001286
1287 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1288 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1289 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1290 // change occurs after the MixerThread starts and causes a stream volume
1291 // glitch.
1292 //
1293 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001294 }
Eric Laurentdc462862016-07-19 12:29:53 -07001295
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001296 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1297 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1298 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1299 }
1300
Eric Laurente552edb2014-03-10 17:42:56 -07001301 return NO_ERROR;
1302}
1303
1304
Eric Laurente0720872014-03-11 09:30:41 -07001305status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001306 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001307 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001308{
1309 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1310 ssize_t index = mOutputs.indexOfKey(output);
1311 if (index < 0) {
1312 ALOGW("stopOutput() unknown output %d", output);
1313 return BAD_VALUE;
1314 }
1315
Eric Laurentc75307b2015-03-17 15:29:32 -07001316 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001317
Eric Laurentc75307b2015-03-17 15:29:32 -07001318 if (outputDesc->mRefCount[stream] == 1) {
1319 // Automatically disable the remote submix input when output is stopped on a
1320 // re routing mix of type MIX_TYPE_RECORDERS
1321 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1322 outputDesc->mPolicyMix != NULL &&
1323 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1324 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1325 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001326 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001327 "remote-submix");
1328 }
1329 }
1330
1331 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001332 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001334 int activityCount = mOutputRoutes.decRouteActivity(session);
1335 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1336
1337 if (forceDeviceUpdate) {
1338 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1339 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 }
1341
Eric Laurent3974e3b2017-12-07 17:58:43 -08001342 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1343
Eric Laurent733ce942017-12-07 12:18:25 -08001344 if (status == NO_ERROR ) {
1345 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001346 }
1347 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001348}
1349
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001350status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001351 audio_stream_type_t stream,
1352 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001353{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001354 // always handle stream stop, check which stream type is stopping
1355 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1356
Eric Laurente552edb2014-03-10 17:42:56 -07001357 // handle special case for sonification while in call
1358 if (isInCall()) {
1359 handleIncallSonification(stream, false, false);
1360 }
1361
1362 if (outputDesc->mRefCount[stream] > 0) {
1363 // decrement usage count of this stream on the output
1364 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001365
Eric Laurente552edb2014-03-10 17:42:56 -07001366 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001367 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001368 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001369 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001370 // delay the device switch by twice the latency because stopOutput() is executed when
1371 // the track stop() command is received and at that time the audio track buffer can
1372 // still contain data that needs to be drained. The latency only covers the audio HAL
1373 // and kernel buffers. Also the latency does not always include additional delay in the
1374 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001375 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001376
1377 // force restoring the device selection on other active outputs if it differs from the
1378 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001379 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001380 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001381 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001382 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001383 desc->isActive() &&
1384 outputDesc->sharesHwModuleWith(desc) &&
1385 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001386 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1387 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001388 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001389 newDevice2,
1390 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001391 delayMs);
1392 // re-apply device specific volume if not done by setOutputDevice()
1393 if (!force) {
1394 applyStreamVolumes(desc, newDevice2, delayMs);
1395 }
Eric Laurente552edb2014-03-10 17:42:56 -07001396 }
1397 }
1398 // update the outputs if stopping one with a stream that can affect notification routing
1399 handleNotificationRoutingForStream(stream);
1400 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001401
1402 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1403 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1404 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1405 }
1406
Eric Laurent36829f92017-04-07 19:04:42 -07001407 if (stream == AUDIO_STREAM_MUSIC) {
1408 selectOutputForMusicEffects();
1409 }
Eric Laurente552edb2014-03-10 17:42:56 -07001410 return NO_ERROR;
1411 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001412 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001413 return INVALID_OPERATION;
1414 }
1415}
1416
Eric Laurente83b55d2014-11-14 10:06:21 -08001417void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001418 audio_stream_type_t stream __unused,
1419 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001420{
1421 ALOGV("releaseOutput() %d", output);
1422 ssize_t index = mOutputs.indexOfKey(output);
1423 if (index < 0) {
1424 ALOGW("releaseOutput() releasing unknown output %d", output);
1425 return;
1426 }
1427
Paul McLeanaa981192015-03-21 09:55:15 -07001428 // Routing
1429 mOutputRoutes.removeRoute(session);
1430
Eric Laurentc75307b2015-03-17 15:29:32 -07001431 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001432 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001433 if (desc->mDirectOpenCount <= 0) {
1434 ALOGW("releaseOutput() invalid open count %d for output %d",
1435 desc->mDirectOpenCount, output);
1436 return;
1437 }
1438 if (--desc->mDirectOpenCount == 0) {
1439 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001440 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001441 }
1442 }
1443}
1444
1445
Eric Laurentcaf7f482014-11-25 17:50:47 -08001446status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1447 audio_io_handle_t *input,
1448 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001449 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001450 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001451 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001452 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001453 input_type_t *inputType,
1454 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001455{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001456 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001457 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001458 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001459
Eric Laurentad2e7b92017-09-14 20:06:42 -07001460 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001461 // handle legacy remote submix case where the address was not always specified
1462 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001463 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001464 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001465 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001466 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001467
Eric Laurentfe231122017-11-17 17:48:06 -08001468 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1469 inputSource = AUDIO_SOURCE_MIC;
1470 }
1471
Paul McLean466dc8e2015-04-17 13:15:36 -06001472 // Explicit routing?
1473 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001474 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001475 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001476 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001477 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001478
Eric Laurentad2e7b92017-09-14 20:06:42 -07001479 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1480 // possible
1481 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1482 *input != AUDIO_IO_HANDLE_NONE) {
1483 ssize_t index = mInputs.indexOfKey(*input);
1484 if (index < 0) {
1485 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1486 status = BAD_VALUE;
1487 goto error;
1488 }
1489 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1490 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1491 if (audioSession == 0) {
1492 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1493 status = BAD_VALUE;
1494 goto error;
1495 }
1496 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1497 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001498 // corresponds to a new client and is only permitted from the same UID.
1499 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001500 if (audioSession->openCount() == 1) {
1501 audioSession->setUid(uid);
1502 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001503 if (!audioSession->isSilenced()) {
1504 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1505 uid, session, audioSession->uid());
1506 status = INVALID_OPERATION;
1507 goto error;
1508 }
1509 audioSession->setUid(uid);
1510 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001511 }
1512 audioSession->changeOpenCount(1);
1513 *inputType = API_INPUT_LEGACY;
1514 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1515 *portId = AudioPort::getNextUniqueId();
1516 }
1517 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1518 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1519 : AUDIO_PORT_HANDLE_NONE;
1520 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1521
1522 return NO_ERROR;
1523 }
1524
1525 *input = AUDIO_IO_HANDLE_NONE;
1526 *inputType = API_INPUT_INVALID;
1527
Eric Laurentad2e7b92017-09-14 20:06:42 -07001528 halInputSource = inputSource;
1529
1530 // TODO: check for existing client for this port ID
1531 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1532 *portId = AudioPort::getNextUniqueId();
1533 }
1534
1535 audio_devices_t device;
1536
Eric Laurentc447ded2015-01-06 08:47:05 -08001537 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001538 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001539 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1540 if (status != NO_ERROR) {
1541 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001542 }
1543 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001544 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1545 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001546 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001547 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001548 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001549 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001550 status = BAD_VALUE;
1551 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001552 }
Eric Laurentc722f302014-12-10 11:21:49 -08001553 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001554 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001555 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1556 // there is an external policy, but this input is attached to a mix of recorders,
1557 // meaning it receives audio injected into the framework, so the recorder doesn't
1558 // know about it and is therefore considered "legacy"
1559 *inputType = API_INPUT_LEGACY;
1560 } else {
1561 // recording a mix of players defined by an external policy, we're rerouting for
1562 // an external policy
1563 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1564 }
Eric Laurentc722f302014-12-10 11:21:49 -08001565 } else if (audio_is_remote_submix_device(device)) {
1566 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001567 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001568 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1569 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001570 } else {
1571 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001572 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001573
Eric Laurent599c7582015-12-07 18:05:55 -08001574 }
1575
1576 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001577 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001578 policyMix);
1579 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001580 status = INVALID_OPERATION;
1581 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001582 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001583
Eric Laurentad2e7b92017-09-14 20:06:42 -07001584 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001585 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1586 : AUDIO_PORT_HANDLE_NONE;
1587
1588 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1589 *input, *inputType, *selectedDeviceId);
1590
Eric Laurent599c7582015-12-07 18:05:55 -08001591 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001592
1593error:
1594 mInputRoutes.removeRoute(session);
1595 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001596}
1597
1598
1599audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1600 String8 address,
1601 audio_session_t session,
1602 uid_t uid,
1603 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001604 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001605 audio_input_flags_t flags,
1606 AudioMix *policyMix)
1607{
1608 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1609 audio_source_t halInputSource = inputSource;
1610 bool isSoundTrigger = false;
1611
1612 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1613 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1614 if (index >= 0) {
1615 input = mSoundTriggerSessions.valueFor(session);
1616 isSoundTrigger = true;
1617 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1618 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1619 } else {
1620 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001621 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001622 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001623 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001624 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001625 }
1626
Andy Hungf129b032015-04-07 13:45:50 -07001627 // find a compatible input profile (not necessarily identical in parameters)
1628 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001629 // sampling rate and flags may be updated by getInputProfile
1630 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1631 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001632 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001633 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001634 audio_input_flags_t profileFlags = flags;
1635 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001636 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001637 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001638 profileSamplingRate, profileFormat, profileChannelMask,
1639 profileFlags);
1640 if (profile != 0) {
1641 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001642 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1643 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001644 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1645 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1646 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001647 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001648 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1649 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001650 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001651 }
Eric Laurente552edb2014-03-10 17:42:56 -07001652 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001653 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001654 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001655 if (samplingRate == 0) {
1656 samplingRate = profileSamplingRate;
1657 }
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurent322b4d22015-04-03 15:57:54 -07001659 if (profile->getModuleHandle() == 0) {
1660 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001661 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001662 }
1663
Eric Laurent599c7582015-12-07 18:05:55 -08001664 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001665 inputSource,
1666 config->format,
1667 samplingRate,
1668 config->channel_mask,
1669 flags,
1670 uid,
1671 isSoundTrigger,
1672 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001673
Eric Laurent74708e72017-04-07 17:13:42 -07001674// FIXME: disable concurrent capture until UI is ready
1675#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001676 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001677 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001678 for (size_t i = 0; i < mInputs.size(); i++) {
1679 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001680 // reuse input if:
1681 // - it shares the same profile
1682 // AND
1683 // - it is not a reroute submix input
1684 // AND
1685 // - it is: not used for sound trigger
1686 // OR
1687 // used for sound trigger and all clients use the same session ID
1688 //
1689 if ((profile == desc->mProfile) &&
1690 (isSoundTrigger == desc->isSoundTrigger()) &&
1691 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001692
1693 sp<AudioSession> as = desc->getAudioSession(session);
1694 if (as != 0) {
1695 // do not allow unmatching properties on same session
1696 if (as->matches(audioSession)) {
1697 as->changeOpenCount(1);
1698 } else {
1699 ALOGW("getInputForDevice() record with different attributes"
1700 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001701 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001702 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001703 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001704 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001705 }
Eric Laurentbb948092017-01-23 18:33:30 -08001706
Eric Laurent555530a2017-02-07 18:17:24 -08001707 // Reuse the already opened input stream on this profile if:
1708 // - the new capture source is background OR
1709 // - the path requested configurations match OR
1710 // - the new source priority is less than the highest source priority on this input
1711 // If the input stream cannot be reused, close it before opening a new stream
1712 // on the same profile for the new client so that the requested path configuration
1713 // can be selected.
1714 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001715 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001716 desc->mChannelMask != config->channel_mask ||
1717 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001718 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001719 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001720 reusedInputDesc = desc;
1721 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001722 } else {
1723 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001724 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1725 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001726 }
Eric Laurent599c7582015-12-07 18:05:55 -08001727 }
1728 }
Eric Laurent599c7582015-12-07 18:05:55 -08001729
Eric Laurent555530a2017-02-07 18:17:24 -08001730 if (reusedInputDesc != 0) {
1731 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1732 for (size_t j = 0; j < sessions.size(); j++) {
1733 audio_session_t currentSession = sessions.keyAt(j);
1734 stopInput(reusedInputDesc->mIoHandle, currentSession);
1735 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1736 }
1737 }
Eric Laurent74708e72017-04-07 17:13:42 -07001738#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001739
Eric Laurent3974e3b2017-12-07 17:58:43 -08001740 if (!profile->canOpenNewIo()) {
1741 return AUDIO_IO_HANDLE_NONE;
1742 }
1743
Eric Laurentfe231122017-11-17 17:48:06 -08001744 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001745
Eric Laurentfe231122017-11-17 17:48:06 -08001746 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1747 lConfig.sample_rate = profileSamplingRate;
1748 lConfig.channel_mask = profileChannelMask;
1749 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001750
Eric Laurent53b810e2017-12-10 17:25:10 -08001751 if (address == "") {
1752 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1753 // the inputs vector must be of size >= 1, but we don't want to crash here
1754 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1755 }
1756
Eric Laurentfe231122017-11-17 17:48:06 -08001757 status_t status = inputDesc->open(&lConfig, device, address,
1758 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001759
1760 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001761 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001762 (profileSamplingRate != lConfig.sample_rate) ||
1763 !audio_formats_match(profileFormat, lConfig.format) ||
1764 (profileChannelMask != lConfig.channel_mask)) {
1765 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001766 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001767 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001768 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001769 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001770 }
Eric Laurent599c7582015-12-07 18:05:55 -08001771 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001772 }
1773
Eric Laurentc722f302014-12-10 11:21:49 -08001774 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001775 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001776
Eric Laurent599c7582015-12-07 18:05:55 -08001777 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001778 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001779
Eric Laurent599c7582015-12-07 18:05:55 -08001780 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001781}
1782
Eric Laurentbb948092017-01-23 18:33:30 -08001783//static
1784bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1785{
1786 return (source == AUDIO_SOURCE_HOTWORD) ||
1787 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1788 (source == AUDIO_SOURCE_FM_TUNER);
1789}
1790
Eric Laurentfb66dd92016-01-28 18:32:03 -08001791bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1792 const sp<AudioSession>& audioSession)
1793{
1794 // Do not allow capture if an active voice call is using a software patch and
1795 // the call TX source device is on the same HW module.
1796 // FIXME: would be better to refine to only inputs whose profile connects to the
1797 // call TX device but this information is not in the audio patch
1798 if (mCallTxPatch != 0 &&
1799 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1800 return false;
1801 }
1802
1803 // starting concurrent capture is enabled if:
1804 // 1) capturing for re-routing
1805 // 2) capturing for HOTWORD source
1806 // 3) capturing for FM TUNER source
1807 // 3) All other active captures are either for re-routing or HOTWORD
1808
1809 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001810 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001811 return true;
1812 }
1813
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001814 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001815 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001816 !is_virtual_input_device(activeInput->mDevice)) {
1817 return false;
1818 }
1819 }
1820
1821 return true;
1822}
1823
Chris Thornton2b864642017-06-27 21:26:07 -07001824// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1825bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1826 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1827 bool soundTriggerSupportsConcurrentCapture = false;
1828 unsigned int numModules = 0;
1829 struct sound_trigger_module_descriptor* nModules = NULL;
1830
1831 status_t status = SoundTrigger::listModules(nModules, &numModules);
1832 if (status == NO_ERROR && numModules != 0) {
1833 nModules = (struct sound_trigger_module_descriptor*) calloc(
1834 numModules, sizeof(struct sound_trigger_module_descriptor));
1835 if (nModules == NULL) {
1836 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1837 // ram the next time this function is called.
1838 ALOGE("Failed to allocate buffer for module descriptors");
1839 return false;
1840 }
1841
1842 status = SoundTrigger::listModules(nModules, &numModules);
1843 if (status == NO_ERROR) {
1844 soundTriggerSupportsConcurrentCapture = true;
1845 for (size_t i = 0; i < numModules; ++i) {
1846 soundTriggerSupportsConcurrentCapture &=
1847 nModules[i].properties.concurrent_capture;
1848 }
1849 }
1850 free(nModules);
1851 }
1852 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1853 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1854 }
1855 return mSoundTriggerSupportsConcurrentCapture;
1856}
1857
Eric Laurentfb66dd92016-01-28 18:32:03 -08001858
Eric Laurent4dc68062014-07-28 17:26:49 -07001859status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001860 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001861 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001862 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001863{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001864
1865 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1866 input, session, silenced, *concurrency);
1867
Eric Laurentfb66dd92016-01-28 18:32:03 -08001868 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001869
Eric Laurente552edb2014-03-10 17:42:56 -07001870 ssize_t index = mInputs.indexOfKey(input);
1871 if (index < 0) {
1872 ALOGW("startInput() unknown input %d", input);
1873 return BAD_VALUE;
1874 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001875 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001876
Eric Laurent599c7582015-12-07 18:05:55 -08001877 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1878 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001879 ALOGW("startInput() unknown session %d on input %d", session, input);
1880 return BAD_VALUE;
1881 }
1882
Eric Laurent74708e72017-04-07 17:13:42 -07001883// FIXME: disable concurrent capture until UI is ready
1884#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001885 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1886 ALOGW("startInput(%d) failed: other input already started", input);
1887 return INVALID_OPERATION;
1888 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001889
Eric Laurentfb66dd92016-01-28 18:32:03 -08001890 if (isInCall()) {
1891 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1892 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001893 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001894 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001895 }
Eric Laurent74708e72017-04-07 17:13:42 -07001896#else
1897 if (!is_virtual_input_device(inputDesc->mDevice)) {
1898 if (mCallTxPatch != 0 &&
1899 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1900 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001901 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001902 return INVALID_OPERATION;
1903 }
1904
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001905 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001906
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001907 // If a UID is idle and records silence and another not silenced recording starts
1908 // from another UID (idle or active) we stop the current idle UID recording in
1909 // favor of the new one - "There can be only one" TM
1910 if (!silenced) {
1911 for (const auto& activeDesc : activeInputs) {
1912 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1913 activeDesc->getId() == inputDesc->getId()) {
1914 continue;
1915 }
1916
1917 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1918 true /*activeOnly*/);
1919 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1920 if (activeSession->isSilenced()) {
1921 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1922 audio_session_t activeSessionId = activeSession->session();
1923 stopInput(activeInput, activeSessionId);
1924 releaseInput(activeInput, activeSessionId);
1925 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1926 activeInputs = mInputs.getActiveInputs();
1927 }
1928 }
1929 }
1930
1931 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001932 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1933 activeDesc->getId() == inputDesc->getId()) {
1934 continue;
1935 }
1936
Eric Laurent74708e72017-04-07 17:13:42 -07001937 audio_source_t activeSource = activeDesc->inputSource(true);
1938 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1939 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1940 if (activeDesc->hasPreemptedSession(session)) {
1941 ALOGW("startInput(%d) failed for HOTWORD: "
1942 "other input %d already started for HOTWORD",
1943 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001944 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001945 return INVALID_OPERATION;
1946 }
1947 } else {
1948 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1949 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001950 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001951 return INVALID_OPERATION;
1952 }
1953 } else {
1954 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1955 ALOGW("startInput(%d) failed: other input %d already started",
1956 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001957 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001958 return INVALID_OPERATION;
1959 }
1960 }
1961 }
1962
Chris Thornton2b864642017-06-27 21:26:07 -07001963 // We only need to check if the sound trigger session supports concurrent capture if the
1964 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1965 // that's running.
1966 const bool allowConcurrentWithSoundTrigger =
1967 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1968
Eric Laurent74708e72017-04-07 17:13:42 -07001969 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001970 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001971 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1972 continue;
1973 }
1974
Eric Laurent74708e72017-04-07 17:13:42 -07001975 audio_source_t activeSource = activeDesc->inputSource(true);
1976 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1977 AudioSessionCollection activeSessions =
1978 activeDesc->getAudioSessions(true /*activeOnly*/);
1979 audio_session_t activeSession = activeSessions.keyAt(0);
1980 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1981 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001982 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001983 sessions.add(activeSession);
1984 inputDesc->setPreemptedSessions(sessions);
1985 stopInput(activeHandle, activeSession);
1986 releaseInput(activeHandle, activeSession);
1987 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1988 input, activeDesc->mIoHandle);
1989 }
1990 }
1991 }
1992#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001993
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001994 // Make sure we start with the correct silence state
1995 audioSession->setSilenced(silenced);
1996
Eric Laurent313d1e72016-01-29 09:56:57 -08001997 // increment activity count before calling getNewInputDevice() below as only active sessions
1998 // are considered for device selection
1999 audioSession->changeActiveCount(1);
2000
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002001 // Routing?
2002 mInputRoutes.incRouteActivity(session);
2003
Eric Laurent2157f5b2018-04-25 18:33:02 -07002004 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002005 // indicate active capture to sound trigger service if starting capture from a mic on
2006 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002007 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002008 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002009
Eric Laurent733ce942017-12-07 12:18:25 -08002010 status_t status = inputDesc->start();
2011 if (status != NO_ERROR) {
2012 mInputRoutes.decRouteActivity(session);
2013 audioSession->changeActiveCount(-1);
2014 return status;
2015 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002016
Eric Laurent733ce942017-12-07 12:18:25 -08002017 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002018 // if input maps to a dynamic policy with an activity listener, notify of state change
2019 if ((inputDesc->mPolicyMix != NULL)
2020 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2021 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2022 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002023 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002024
Eric Laurentf7c50102016-09-30 15:19:43 -07002025 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2026 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002027 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002028 SoundTrigger::setCaptureState(true);
2029 }
2030
2031 // automatically enable the remote submix output when input is started if not
2032 // used by a policy mix of type MIX_TYPE_RECORDERS
2033 // For remote submix (a virtual device), we open only one input per capture request.
2034 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2035 String8 address = String8("");
2036 if (inputDesc->mPolicyMix == NULL) {
2037 address = String8("0");
2038 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2039 address = inputDesc->mPolicyMix->mDeviceAddress;
2040 }
2041 if (address != "") {
2042 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2043 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2044 address, "remote-submix");
2045 }
Eric Laurentc722f302014-12-10 11:21:49 -08002046 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002047 }
Eric Laurente552edb2014-03-10 17:42:56 -07002048 }
2049
Eric Laurent599c7582015-12-07 18:05:55 -08002050 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002051
Eric Laurente552edb2014-03-10 17:42:56 -07002052 return NO_ERROR;
2053}
2054
Eric Laurent4dc68062014-07-28 17:26:49 -07002055status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2056 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002057{
2058 ALOGV("stopInput() input %d", input);
2059 ssize_t index = mInputs.indexOfKey(input);
2060 if (index < 0) {
2061 ALOGW("stopInput() unknown input %d", input);
2062 return BAD_VALUE;
2063 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002064 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002065
Eric Laurent599c7582015-12-07 18:05:55 -08002066 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002067 if (index < 0) {
2068 ALOGW("stopInput() unknown session %d on input %d", session, input);
2069 return BAD_VALUE;
2070 }
2071
Eric Laurent599c7582015-12-07 18:05:55 -08002072 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002073 ALOGW("stopInput() input %d already stopped", input);
2074 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002075 }
2076
Eric Laurent599c7582015-12-07 18:05:55 -08002077 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002078
2079 // Routing?
2080 mInputRoutes.decRouteActivity(session);
2081
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002082 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002083 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002084 if (inputDesc->isActive()) {
2085 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2086 } else {
2087 // if input maps to a dynamic policy with an activity listener, notify of state change
2088 if ((inputDesc->mPolicyMix != NULL)
2089 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2090 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2091 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002092 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002093
2094 // automatically disable the remote submix output when input is stopped if not
2095 // used by a policy mix of type MIX_TYPE_RECORDERS
2096 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2097 String8 address = String8("");
2098 if (inputDesc->mPolicyMix == NULL) {
2099 address = String8("0");
2100 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2101 address = inputDesc->mPolicyMix->mDeviceAddress;
2102 }
2103 if (address != "") {
2104 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2105 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2106 address, "remote-submix");
2107 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002108 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002109
Eric Laurentf7c50102016-09-30 15:19:43 -07002110 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002111 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002112
Eric Laurentf7c50102016-09-30 15:19:43 -07002113 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2114 // primary HW module
2115 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2116 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2117 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002118 SoundTrigger::setCaptureState(false);
2119 }
2120 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002121 }
Eric Laurente552edb2014-03-10 17:42:56 -07002122 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002123 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002124}
2125
Eric Laurent4dc68062014-07-28 17:26:49 -07002126void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2127 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002128{
2129 ALOGV("releaseInput() %d", input);
2130 ssize_t index = mInputs.indexOfKey(input);
2131 if (index < 0) {
2132 ALOGW("releaseInput() releasing unknown input %d", input);
2133 return;
2134 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002135
2136 // Routing
2137 mInputRoutes.removeRoute(session);
2138
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002139 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2140 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002141
Eric Laurent599c7582015-12-07 18:05:55 -08002142 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002143 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002144 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2145 return;
2146 }
Eric Laurent599c7582015-12-07 18:05:55 -08002147
2148 if (audioSession->openCount() == 0) {
2149 ALOGW("releaseInput() invalid open count %d on session %d",
2150 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002151 return;
2152 }
Eric Laurent599c7582015-12-07 18:05:55 -08002153
2154 if (audioSession->changeOpenCount(-1) == 0) {
2155 inputDesc->removeAudioSession(session);
2156 }
2157
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002158 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002159 ALOGV("releaseInput() exit > 0");
2160 return;
2161 }
2162
Eric Laurent05b90f82014-08-27 15:32:29 -07002163 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002164 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002165 ALOGV("releaseInput() exit");
2166}
2167
Eric Laurentd4692962014-05-05 18:13:44 -07002168void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002169 bool patchRemoved = false;
2170
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002171 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002172 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002173 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 if (patch_index >= 0) {
2175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002176 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002177 mAudioPatches.removeItemsAt(patch_index);
2178 patchRemoved = true;
2179 }
Eric Laurentfe231122017-11-17 17:48:06 -08002180 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002181 }
jiabin829a00b2018-04-04 16:28:32 -07002182 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002183 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002184 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002185 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002186
2187 if (patchRemoved) {
2188 mpClientInterface->onAudioPatchListUpdate();
2189 }
Eric Laurentd4692962014-05-05 18:13:44 -07002190}
2191
Eric Laurente0720872014-03-11 09:30:41 -07002192void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002193 int indexMin,
2194 int indexMax)
2195{
2196 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002197 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002198
2199 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002200 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2201 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002202 continue;
2203 }
2204 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002205 }
Eric Laurente552edb2014-03-10 17:42:56 -07002206}
2207
Eric Laurente0720872014-03-11 09:30:41 -07002208status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002209 int index,
2210 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002211{
2212
Nadav Bar7c605f62017-12-25 00:01:52 +02002213 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2214 // app that has MODIFY_PHONE_STATE permission.
2215 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2216 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002217 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002218 return BAD_VALUE;
2219 }
2220 if (!audio_is_output_device(device)) {
2221 return BAD_VALUE;
2222 }
2223
2224 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002225 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002226
Eric Laurent1fd372e2016-04-06 14:23:53 -07002227 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002228 stream, device, index);
2229
Eric Laurent28d09f02016-03-08 10:43:05 -08002230 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002231 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2232 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002233 continue;
2234 }
2235 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2236 }
Eric Laurente552edb2014-03-10 17:42:56 -07002237
Eric Laurent1fd372e2016-04-06 14:23:53 -07002238 // update volume on all outputs and streams matching the following:
2239 // - The requested stream (or a stream matching for volume control) is active on the output
2240 // - The device (or devices) selected by the strategy corresponding to this stream includes
2241 // the requested device
2242 // - For non default requested device, currently selected device on the output is either the
2243 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002244 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2245 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002246 status_t status = NO_ERROR;
2247 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002248 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2249 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002250 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2251 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002252 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002253 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002254 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2255 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002256 continue;
2257 }
Eric Laurent794fde22016-03-11 09:50:45 -08002258 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002259 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2260 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002261 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2262 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002263 continue;
2264 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002265 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002266 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002267 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002268 applyVolume = (curDevice & curStreamDevice) != 0;
2269 } else {
2270 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002271 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002273
Eric Laurente76f29c2016-09-14 17:17:53 -07002274 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002275 //FIXME: workaround for truncated touch sounds
2276 // delayed volume change for system stream to be removed when the problem is
2277 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002278 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002279 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2280 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002281 if (volStatus != NO_ERROR) {
2282 status = volStatus;
2283 }
2284 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002285 }
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
2287 return status;
2288}
2289
Eric Laurente0720872014-03-11 09:30:41 -07002290status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002291 int *index,
2292 audio_devices_t device)
2293{
2294 if (index == NULL) {
2295 return BAD_VALUE;
2296 }
2297 if (!audio_is_output_device(device)) {
2298 return BAD_VALUE;
2299 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002300 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002301 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002302 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002303 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2304 }
François Gaffiedfd74092015-03-19 12:10:59 +01002305 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002306
François Gaffied1ab2bd2015-12-02 18:20:06 +01002307 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002308 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2309 return NO_ERROR;
2310}
2311
Eric Laurent36829f92017-04-07 19:04:42 -07002312audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
2314 // select one output among several suitable for global effects.
2315 // The priority is as follows:
2316 // 1: An offloaded output. If the effect ends up not being offloadable,
2317 // AudioFlinger will invalidate the track and the offloaded output
2318 // will be closed causing the effect to be moved to a PCM output.
2319 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002320 // 3: The primary output
2321 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002322
Eric Laurent3b73df72014-03-11 09:06:29 -07002323 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002324 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002325 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002326
Eric Laurent36829f92017-04-07 19:04:42 -07002327 if (outputs.size() == 0) {
2328 return AUDIO_IO_HANDLE_NONE;
2329 }
Eric Laurente552edb2014-03-10 17:42:56 -07002330
Eric Laurent36829f92017-04-07 19:04:42 -07002331 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2332 bool activeOnly = true;
2333
2334 while (output == AUDIO_IO_HANDLE_NONE) {
2335 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2336 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2337 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2338
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002339 for (audio_io_handle_t output : outputs) {
2340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002341 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2342 continue;
2343 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002344 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2345 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002346 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002347 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002348 }
2349 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002350 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002351 }
2352 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002353 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002354 }
2355 }
2356 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2357 output = outputOffloaded;
2358 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2359 output = outputDeepBuffer;
2360 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2361 output = outputPrimary;
2362 } else {
2363 output = outputs[0];
2364 }
2365 activeOnly = false;
2366 }
2367
2368 if (output != mMusicEffectOutput) {
2369 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2370 mMusicEffectOutput = output;
2371 }
2372
2373 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002374 return output;
2375}
2376
Eric Laurent36829f92017-04-07 19:04:42 -07002377audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2378{
2379 return selectOutputForMusicEffects();
2380}
2381
Eric Laurente0720872014-03-11 09:30:41 -07002382status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002383 audio_io_handle_t io,
2384 uint32_t strategy,
2385 int session,
2386 int id)
2387{
2388 ssize_t index = mOutputs.indexOfKey(io);
2389 if (index < 0) {
2390 index = mInputs.indexOfKey(io);
2391 if (index < 0) {
2392 ALOGW("registerEffect() unknown io %d", io);
2393 return INVALID_OPERATION;
2394 }
2395 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002396 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002397}
2398
Eric Laurentc75307b2015-03-17 15:29:32 -07002399bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2400{
Eric Laurent28d09f02016-03-08 10:43:05 -08002401 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002402 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2403 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002404 continue;
2405 }
2406 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2407 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002408 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002409}
2410
2411bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2412{
2413 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2414}
2415
Eric Laurente0720872014-03-11 09:30:41 -07002416bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002417{
2418 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002419 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002420 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002421 return true;
2422 }
2423 }
2424 return false;
2425}
2426
Eric Laurent275e8e92014-11-30 15:14:47 -08002427// Register a list of custom mixes with their attributes and format.
2428// When a mix is registered, corresponding input and output profiles are
2429// added to the remote submix hw module. The profile contains only the
2430// parameters (sampling rate, format...) specified by the mix.
2431// The corresponding input remote submix device is also connected.
2432//
2433// When a remote submix device is connected, the address is checked to select the
2434// appropriate profile and the corresponding input or output stream is opened.
2435//
2436// When capture starts, getInputForAttr() will:
2437// - 1 look for a mix matching the address passed in attribtutes tags if any
2438// - 2 if none found, getDeviceForInputSource() will:
2439// - 2.1 look for a mix matching the attributes source
2440// - 2.2 if none found, default to device selection by policy rules
2441// At this time, the corresponding output remote submix device is also connected
2442// and active playback use cases can be transferred to this mix if needed when reconnecting
2443// after AudioTracks are invalidated
2444//
2445// When playback starts, getOutputForAttr() will:
2446// - 1 look for a mix matching the address passed in attribtutes tags if any
2447// - 2 if none found, look for a mix matching the attributes usage
2448// - 3 if none found, default to device and output selection by policy rules.
2449
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002450status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002451{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002452 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2453 status_t res = NO_ERROR;
2454
2455 sp<HwModule> rSubmixModule;
2456 // examine each mix's route type
2457 for (size_t i = 0; i < mixes.size(); i++) {
2458 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2459 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2460 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002461 break;
2462 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002463 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002464 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002465 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002466 rSubmixModule = mHwModules.getModuleFromName(
2467 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2468 if (rSubmixModule == 0) {
2469 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2470 i);
2471 res = INVALID_OPERATION;
2472 break;
2473 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002475
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002477
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002478 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002479 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 res = INVALID_OPERATION;
2481 break;
2482 }
2483 audio_config_t outputConfig = mixes[i].mFormat;
2484 audio_config_t inputConfig = mixes[i].mFormat;
2485 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2486 // stereo and let audio flinger do the channel conversion if needed.
2487 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2488 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2489 rSubmixModule->addOutputProfile(address, &outputConfig,
2490 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2491 rSubmixModule->addInputProfile(address, &inputConfig,
2492 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002493
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2495 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2496 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2497 address.string(), "remote-submix");
2498 } else {
2499 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2500 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2501 address.string(), "remote-submix");
2502 }
2503 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002504 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002506 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2507 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002509 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2511 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2512 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2513 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2514 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2515 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002516 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2517 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002518 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2519 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002520 } else {
2521 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 }
2523 break;
2524 }
2525 }
2526
2527 if (res != NO_ERROR) {
2528 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002529 i, device, address.string());
2530 res = INVALID_OPERATION;
2531 break;
2532 } else if (!foundOutput) {
2533 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2534 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 res = INVALID_OPERATION;
2536 break;
2537 }
Eric Laurentc722f302014-12-10 11:21:49 -08002538 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002539 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 if (res != NO_ERROR) {
2541 unregisterPolicyMixes(mixes);
2542 }
2543 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002544}
2545
2546status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2547{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002548 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 status_t res = NO_ERROR;
2550 sp<HwModule> rSubmixModule;
2551 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002552 for (const auto& mix : mixes) {
2553 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002554
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002556 rSubmixModule = mHwModules.getModuleFromName(
2557 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2558 if (rSubmixModule == 0) {
2559 res = INVALID_OPERATION;
2560 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002561 }
2562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002563
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002564 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002565
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2567 res = INVALID_OPERATION;
2568 continue;
2569 }
2570
2571 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2572 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2573 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2574 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2575 address.string(), "remote-submix");
2576 }
2577 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2578 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2579 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2580 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2581 address.string(), "remote-submix");
2582 }
2583 rSubmixModule->removeOutputProfile(address);
2584 rSubmixModule->removeInputProfile(address);
2585
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002586 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2587 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002588 res = INVALID_OPERATION;
2589 continue;
2590 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002591 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002592 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002593 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002594}
2595
Eric Laurente552edb2014-03-10 17:42:56 -07002596
Eric Laurente0720872014-03-11 09:30:41 -07002597status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002598{
2599 const size_t SIZE = 256;
2600 char buffer[SIZE];
2601 String8 result;
2602
2603 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2604 result.append(buffer);
2605
Eric Laurent87ffa392015-05-22 10:32:38 -07002606 snprintf(buffer, SIZE, " Primary Output: %d\n",
2607 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002608 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002609 std::string stateLiteral;
2610 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2611 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002612 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002613 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002614 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002615 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002616 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002617 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002618 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002619 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002620 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002621 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002622 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002623 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002624 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002625 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002626 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002627 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2628 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2629 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002630 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2631 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002632 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2633 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002634
François Gaffie2110e042015-03-24 08:41:51 +01002635 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002636
François Gaffie112b0af2015-11-19 16:13:25 +01002637 mAvailableOutputDevices.dump(fd, String8("Available output"));
2638 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002639 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002640 mOutputs.dump(fd);
2641 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002642 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002643 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002644 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002645 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002646
2647 return NO_ERROR;
2648}
2649
2650// This function checks for the parameters which can be offloaded.
2651// This can be enhanced depending on the capability of the DSP and policy
2652// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002653bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002654{
2655 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002656 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002657 offloadInfo.sample_rate, offloadInfo.channel_mask,
2658 offloadInfo.format,
2659 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2660 offloadInfo.has_video);
2661
Andy Hung2ddee192015-12-18 17:34:44 -08002662 if (mMasterMono) {
2663 return false; // no offloading if mono is set.
2664 }
2665
Eric Laurente552edb2014-03-10 17:42:56 -07002666 // Check if offload has been disabled
2667 char propValue[PROPERTY_VALUE_MAX];
2668 if (property_get("audio.offload.disable", propValue, "0")) {
2669 if (atoi(propValue) != 0) {
2670 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2671 return false;
2672 }
2673 }
2674
2675 // Check if stream type is music, then only allow offload as of now.
2676 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2677 {
2678 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2679 return false;
2680 }
2681
2682 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002683 const bool allowOffloadWithVideo =
2684 property_get_bool("audio.offload.video", false /* default_value */);
2685 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002686 ALOGV("isOffloadSupported: has_video == true, returning false");
2687 return false;
2688 }
2689
2690 //If duration is less than minimum value defined in property, return false
2691 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2692 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2693 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2694 return false;
2695 }
2696 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2697 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2698 return false;
2699 }
2700
2701 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2702 // creating an offloaded track and tearing it down immediately after start when audioflinger
2703 // detects there is an active non offloadable effect.
2704 // FIXME: We should check the audio session here but we do not have it in this context.
2705 // This may prevent offloading in rare situations where effects are left active by apps
2706 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002707 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002708 return false;
2709 }
2710
2711 // See if there is a profile to support this.
2712 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002713 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002714 offloadInfo.sample_rate,
2715 offloadInfo.format,
2716 offloadInfo.channel_mask,
2717 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002718 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2719 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002720}
2721
Eric Laurent6a94d692014-05-20 11:18:06 -07002722status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2723 audio_port_type_t type,
2724 unsigned int *num_ports,
2725 struct audio_port *ports,
2726 unsigned int *generation)
2727{
2728 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2729 generation == NULL) {
2730 return BAD_VALUE;
2731 }
2732 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2733 if (ports == NULL) {
2734 *num_ports = 0;
2735 }
2736
2737 size_t portsWritten = 0;
2738 size_t portsMax = *num_ports;
2739 *num_ports = 0;
2740 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002741 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2742 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002744 for (const auto& dev : mAvailableOutputDevices) {
2745 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002746 continue;
2747 }
2748 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002749 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002750 }
2751 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002752 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002753 }
2754 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002755 for (const auto& dev : mAvailableInputDevices) {
2756 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002757 continue;
2758 }
2759 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002760 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002761 }
2762 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002763 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002764 }
2765 }
2766 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2767 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2768 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2769 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2770 }
2771 *num_ports += mInputs.size();
2772 }
2773 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002774 size_t numOutputs = 0;
2775 for (size_t i = 0; i < mOutputs.size(); i++) {
2776 if (!mOutputs[i]->isDuplicated()) {
2777 numOutputs++;
2778 if (portsWritten < portsMax) {
2779 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2780 }
2781 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002782 }
Eric Laurent84c70242014-06-23 08:46:27 -07002783 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 }
2785 }
2786 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002787 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002788 return NO_ERROR;
2789}
2790
2791status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2792{
2793 return NO_ERROR;
2794}
2795
Eric Laurent6a94d692014-05-20 11:18:06 -07002796status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2797 audio_patch_handle_t *handle,
2798 uid_t uid)
2799{
2800 ALOGV("createAudioPatch()");
2801
2802 if (handle == NULL || patch == NULL) {
2803 return BAD_VALUE;
2804 }
2805 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2806
Eric Laurent874c42872014-08-08 15:13:39 -07002807 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2808 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2809 return BAD_VALUE;
2810 }
2811 // only one source per audio patch supported for now
2812 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 return INVALID_OPERATION;
2814 }
Eric Laurent874c42872014-08-08 15:13:39 -07002815
2816 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002817 return INVALID_OPERATION;
2818 }
Eric Laurent874c42872014-08-08 15:13:39 -07002819 for (size_t i = 0; i < patch->num_sinks; i++) {
2820 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2821 return INVALID_OPERATION;
2822 }
2823 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002824
2825 sp<AudioPatch> patchDesc;
2826 ssize_t index = mAudioPatches.indexOfKey(*handle);
2827
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2829 patch->sources[0].role,
2830 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002831#if LOG_NDEBUG == 0
2832 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002833 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002834 patch->sinks[i].role,
2835 patch->sinks[i].type);
2836 }
2837#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002838
2839 if (index >= 0) {
2840 patchDesc = mAudioPatches.valueAt(index);
2841 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2842 mUidCached, patchDesc->mUid, uid);
2843 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2844 return INVALID_OPERATION;
2845 }
2846 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002847 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002848 }
2849
2850 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002851 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 if (outputDesc == NULL) {
2853 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2854 return BAD_VALUE;
2855 }
Eric Laurent84c70242014-06-23 08:46:27 -07002856 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2857 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002858 if (patchDesc != 0) {
2859 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2860 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2861 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2862 return BAD_VALUE;
2863 }
2864 }
Eric Laurent874c42872014-08-08 15:13:39 -07002865 DeviceVector devices;
2866 for (size_t i = 0; i < patch->num_sinks; i++) {
2867 // Only support mix to devices connection
2868 // TODO add support for mix to mix connection
2869 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2870 ALOGV("createAudioPatch() source mix but sink is not a device");
2871 return INVALID_OPERATION;
2872 }
2873 sp<DeviceDescriptor> devDesc =
2874 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2875 if (devDesc == 0) {
2876 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2877 return BAD_VALUE;
2878 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002879
François Gaffie53615e22015-03-19 09:24:12 +01002880 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002881 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002882 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002883 NULL, // updatedSamplingRate
2884 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002885 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002886 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002887 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002888 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002889 ALOGV("createAudioPatch() profile not supported for device %08x",
2890 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002891 return INVALID_OPERATION;
2892 }
2893 devices.add(devDesc);
2894 }
2895 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002896 return INVALID_OPERATION;
2897 }
Eric Laurent874c42872014-08-08 15:13:39 -07002898
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 // TODO: reconfigure output format and channels here
2900 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002901 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002902 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 index = mAudioPatches.indexOfKey(*handle);
2904 if (index >= 0) {
2905 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2906 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2907 }
2908 patchDesc = mAudioPatches.valueAt(index);
2909 patchDesc->mUid = uid;
2910 ALOGV("createAudioPatch() success");
2911 } else {
2912 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2913 return INVALID_OPERATION;
2914 }
2915 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2916 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2917 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002918 // only one sink supported when connecting an input device to a mix
2919 if (patch->num_sinks > 1) {
2920 return INVALID_OPERATION;
2921 }
François Gaffie53615e22015-03-19 09:24:12 +01002922 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002923 if (inputDesc == NULL) {
2924 return BAD_VALUE;
2925 }
2926 if (patchDesc != 0) {
2927 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2928 return BAD_VALUE;
2929 }
2930 }
2931 sp<DeviceDescriptor> devDesc =
2932 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2933 if (devDesc == 0) {
2934 return BAD_VALUE;
2935 }
2936
François Gaffie53615e22015-03-19 09:24:12 +01002937 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002938 devDesc->mAddress,
2939 patch->sinks[0].sample_rate,
2940 NULL, /*updatedSampleRate*/
2941 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002942 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002943 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002944 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002945 // FIXME for the parameter type,
2946 // and the NONE
2947 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002948 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002949 return INVALID_OPERATION;
2950 }
2951 // TODO: reconfigure output format and channels here
2952 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002953 devDesc->type(), inputDesc->mIoHandle);
2954 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 index = mAudioPatches.indexOfKey(*handle);
2956 if (index >= 0) {
2957 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2958 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2959 }
2960 patchDesc = mAudioPatches.valueAt(index);
2961 patchDesc->mUid = uid;
2962 ALOGV("createAudioPatch() success");
2963 } else {
2964 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2965 return INVALID_OPERATION;
2966 }
2967 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2968 // device to device connection
2969 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002970 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 return BAD_VALUE;
2972 }
2973 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 sp<DeviceDescriptor> srcDeviceDesc =
2975 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002976 if (srcDeviceDesc == 0) {
2977 return BAD_VALUE;
2978 }
Eric Laurent874c42872014-08-08 15:13:39 -07002979
Eric Laurent6a94d692014-05-20 11:18:06 -07002980 //update source and sink with our own data as the data passed in the patch may
2981 // be incomplete.
2982 struct audio_patch newPatch = *patch;
2983 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002984
Eric Laurent874c42872014-08-08 15:13:39 -07002985 for (size_t i = 0; i < patch->num_sinks; i++) {
2986 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2987 ALOGV("createAudioPatch() source device but one sink is not a device");
2988 return INVALID_OPERATION;
2989 }
2990
2991 sp<DeviceDescriptor> sinkDeviceDesc =
2992 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2993 if (sinkDeviceDesc == 0) {
2994 return BAD_VALUE;
2995 }
2996 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2997
Eric Laurent3bcf8592015-04-03 12:13:24 -07002998 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002999 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003000 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003001 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003002 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003003 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003004 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003005 return INVALID_OPERATION;
3006 }
Eric Laurent874c42872014-08-08 15:13:39 -07003007 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003008 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003009 // if the sink device is reachable via an opened output stream, request to go via
3010 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003011 audio_io_handle_t output = selectOutput(outputs,
3012 AUDIO_OUTPUT_FLAG_NONE,
3013 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003014 if (output != AUDIO_IO_HANDLE_NONE) {
3015 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3016 if (outputDesc->isDuplicated()) {
3017 return INVALID_OPERATION;
3018 }
3019 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003020 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003021 newPatch.num_sources = 2;
3022 }
Eric Laurent83b88082014-06-20 18:31:16 -07003023 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003024 }
3025 // TODO: check from routing capabilities in config file and other conflicting patches
3026
3027 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3028 if (index >= 0) {
3029 afPatchHandle = patchDesc->mAfPatchHandle;
3030 }
3031
3032 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3033 &afPatchHandle,
3034 0);
3035 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3036 status, afPatchHandle);
3037 if (status == NO_ERROR) {
3038 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003039 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003040 addAudioPatch(patchDesc->mHandle, patchDesc);
3041 } else {
3042 patchDesc->mPatch = newPatch;
3043 }
3044 patchDesc->mAfPatchHandle = afPatchHandle;
3045 *handle = patchDesc->mHandle;
3046 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003047 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003048 } else {
3049 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3050 status);
3051 return INVALID_OPERATION;
3052 }
3053 } else {
3054 return BAD_VALUE;
3055 }
3056 } else {
3057 return BAD_VALUE;
3058 }
3059 return NO_ERROR;
3060}
3061
3062status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3063 uid_t uid)
3064{
3065 ALOGV("releaseAudioPatch() patch %d", handle);
3066
3067 ssize_t index = mAudioPatches.indexOfKey(handle);
3068
3069 if (index < 0) {
3070 return BAD_VALUE;
3071 }
3072 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3073 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3074 mUidCached, patchDesc->mUid, uid);
3075 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3076 return INVALID_OPERATION;
3077 }
3078
3079 struct audio_patch *patch = &patchDesc->mPatch;
3080 patchDesc->mUid = mUidCached;
3081 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003082 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003083 if (outputDesc == NULL) {
3084 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3085 return BAD_VALUE;
3086 }
3087
Eric Laurentc75307b2015-03-17 15:29:32 -07003088 setOutputDevice(outputDesc,
3089 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003090 true,
3091 0,
3092 NULL);
3093 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3094 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003095 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003096 if (inputDesc == NULL) {
3097 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3098 return BAD_VALUE;
3099 }
3100 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003101 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003102 true,
3103 NULL);
3104 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003105 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3106 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3107 status, patchDesc->mAfPatchHandle);
3108 removeAudioPatch(patchDesc->mHandle);
3109 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003110 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003111 } else {
3112 return BAD_VALUE;
3113 }
3114 } else {
3115 return BAD_VALUE;
3116 }
3117 return NO_ERROR;
3118}
3119
3120status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3121 struct audio_patch *patches,
3122 unsigned int *generation)
3123{
François Gaffie53615e22015-03-19 09:24:12 +01003124 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003125 return BAD_VALUE;
3126 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003127 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003128 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003129}
3130
Eric Laurente1715a42014-05-20 11:30:42 -07003131status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003132{
Eric Laurente1715a42014-05-20 11:30:42 -07003133 ALOGV("setAudioPortConfig()");
3134
3135 if (config == NULL) {
3136 return BAD_VALUE;
3137 }
3138 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3139 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003140 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3141 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003142 }
3143
Eric Laurenta121f902014-06-03 13:32:54 -07003144 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003145 if (config->type == AUDIO_PORT_TYPE_MIX) {
3146 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003147 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003148 if (outputDesc == NULL) {
3149 return BAD_VALUE;
3150 }
Eric Laurent84c70242014-06-23 08:46:27 -07003151 ALOG_ASSERT(!outputDesc->isDuplicated(),
3152 "setAudioPortConfig() called on duplicated output %d",
3153 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003154 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003155 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003156 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003157 if (inputDesc == NULL) {
3158 return BAD_VALUE;
3159 }
Eric Laurenta121f902014-06-03 13:32:54 -07003160 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003161 } else {
3162 return BAD_VALUE;
3163 }
3164 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3165 sp<DeviceDescriptor> deviceDesc;
3166 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3167 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3168 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3169 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3170 } else {
3171 return BAD_VALUE;
3172 }
3173 if (deviceDesc == NULL) {
3174 return BAD_VALUE;
3175 }
Eric Laurenta121f902014-06-03 13:32:54 -07003176 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003177 } else {
3178 return BAD_VALUE;
3179 }
3180
Eric Laurenta121f902014-06-03 13:32:54 -07003181 struct audio_port_config backupConfig;
3182 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3183 if (status == NO_ERROR) {
3184 struct audio_port_config newConfig;
3185 audioPortConfig->toAudioPortConfig(&newConfig, config);
3186 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003187 }
Eric Laurenta121f902014-06-03 13:32:54 -07003188 if (status != NO_ERROR) {
3189 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003190 }
Eric Laurente1715a42014-05-20 11:30:42 -07003191
3192 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003193}
3194
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003195void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3196{
Eric Laurentd60560a2015-04-10 11:31:20 -07003197 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003198 clearAudioPatches(uid);
3199 clearSessionRoutes(uid);
3200}
3201
Eric Laurent6a94d692014-05-20 11:18:06 -07003202void AudioPolicyManager::clearAudioPatches(uid_t uid)
3203{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003204 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003205 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3206 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003207 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003208 }
3209 }
3210}
3211
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003212void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3213 audio_io_handle_t ouptutToSkip)
3214{
3215 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3216 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3217 for (size_t j = 0; j < mOutputs.size(); j++) {
3218 if (mOutputs.keyAt(j) == ouptutToSkip) {
3219 continue;
3220 }
3221 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3222 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3223 continue;
3224 }
3225 // If the default device for this strategy is on another output mix,
3226 // invalidate all tracks in this strategy to force re connection.
3227 // Otherwise select new device on the output mix.
3228 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003229 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003230 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3231 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3232 }
3233 }
3234 } else {
3235 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3236 setOutputDevice(outputDesc, newDevice, false);
3237 }
3238 }
3239}
3240
3241void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3242{
3243 // remove output routes associated with this uid
3244 SortedVector<routing_strategy> affectedStrategies;
3245 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3246 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3247 if (route->mUid == uid) {
3248 mOutputRoutes.removeItemsAt(i);
3249 if (route->mDeviceDescriptor != 0) {
3250 affectedStrategies.add(getStrategy(route->mStreamType));
3251 }
3252 }
3253 }
3254 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003255 for (const auto& strategy : affectedStrategies) {
3256 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003257 }
3258
3259 // remove input routes associated with this uid
3260 SortedVector<audio_source_t> affectedSources;
3261 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3262 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3263 if (route->mUid == uid) {
3264 mInputRoutes.removeItemsAt(i);
3265 if (route->mDeviceDescriptor != 0) {
3266 affectedSources.add(route->mSource);
3267 }
3268 }
3269 }
3270 // reroute inputs if necessary
3271 SortedVector<audio_io_handle_t> inputsToClose;
3272 for (size_t i = 0; i < mInputs.size(); i++) {
3273 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003274 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003275 inputsToClose.add(inputDesc->mIoHandle);
3276 }
3277 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003278 for (const auto& input : inputsToClose) {
3279 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003280 }
3281}
3282
Eric Laurentd60560a2015-04-10 11:31:20 -07003283void AudioPolicyManager::clearAudioSources(uid_t uid)
3284{
3285 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3286 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3287 if (sourceDesc->mUid == uid) {
3288 stopAudioSource(mAudioSources.keyAt(i));
3289 }
3290 }
3291}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003292
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003293status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3294 audio_io_handle_t *ioHandle,
3295 audio_devices_t *device)
3296{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003297 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3298 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003299 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003300
François Gaffiedf372692015-03-19 10:43:27 +01003301 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003302}
3303
Eric Laurentd60560a2015-04-10 11:31:20 -07003304status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3305 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003306 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003307 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003308{
Eric Laurentd60560a2015-04-10 11:31:20 -07003309 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3310 if (source == NULL || attributes == NULL || handle == NULL) {
3311 return BAD_VALUE;
3312 }
3313
Glenn Kasten559d4392016-03-29 13:42:57 -07003314 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003315
3316 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3317 source->type != AUDIO_PORT_TYPE_DEVICE) {
3318 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3319 return INVALID_OPERATION;
3320 }
3321
3322 sp<DeviceDescriptor> srcDeviceDesc =
3323 mAvailableInputDevices.getDevice(source->ext.device.type,
3324 String8(source->ext.device.address));
3325 if (srcDeviceDesc == 0) {
3326 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3327 return BAD_VALUE;
3328 }
3329 sp<AudioSourceDescriptor> sourceDesc =
3330 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3331
3332 struct audio_patch dummyPatch;
3333 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3334 sourceDesc->mPatchDesc = patchDesc;
3335
3336 status_t status = connectAudioSource(sourceDesc);
3337 if (status == NO_ERROR) {
3338 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3339 *handle = sourceDesc->getHandle();
3340 }
3341 return status;
3342}
3343
3344status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3345{
3346 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3347
3348 // make sure we only have one patch per source.
3349 disconnectAudioSource(sourceDesc);
3350
3351 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003352 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003353 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3354
3355 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3356 sp<DeviceDescriptor> sinkDeviceDesc =
3357 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3358
3359 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3360 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3361
3362 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3363 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003364 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003365 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3366 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3367 // create patch between src device and output device
3368 // create Hwoutput and add to mHwOutputs
3369 } else {
3370 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3371 audio_io_handle_t output =
3372 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3373 if (output == AUDIO_IO_HANDLE_NONE) {
3374 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3375 return INVALID_OPERATION;
3376 }
3377 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3378 if (outputDesc->isDuplicated()) {
3379 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3380 return INVALID_OPERATION;
3381 }
Eric Laurent733ce942017-12-07 12:18:25 -08003382 status_t status = outputDesc->start();
3383 if (status != NO_ERROR) {
3384 return status;
3385 }
3386
Eric Laurentd60560a2015-04-10 11:31:20 -07003387 // create a special patch with no sink and two sources:
3388 // - the second source indicates to PatchPanel through which output mix this patch should
3389 // be connected as well as the stream type for volume control
3390 // - the sink is defined by whatever output device is currently selected for the output
3391 // though which this patch is routed.
3392 patch->num_sinks = 0;
3393 patch->num_sources = 2;
3394 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3395 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3396 patch->sources[1].ext.mix.usecase.stream = stream;
Eric Laurent733ce942017-12-07 12:18:25 -08003397 status = mpClientInterface->createAudioPatch(patch,
Eric Laurentd60560a2015-04-10 11:31:20 -07003398 &afPatchHandle,
3399 0);
3400 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3401 status, afPatchHandle);
3402 if (status != NO_ERROR) {
3403 ALOGW("%s patch panel could not connect device patch, error %d",
3404 __FUNCTION__, status);
3405 return INVALID_OPERATION;
3406 }
3407 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003408 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003409
3410 if (status != NO_ERROR) {
3411 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3412 return status;
3413 }
3414 sourceDesc->mSwOutput = outputDesc;
3415 if (delayMs != 0) {
3416 usleep(delayMs * 1000);
3417 }
3418 }
3419
3420 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3421 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3422
3423 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003424}
3425
Glenn Kasten559d4392016-03-29 13:42:57 -07003426status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003427{
Eric Laurentd60560a2015-04-10 11:31:20 -07003428 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3429 ALOGV("%s handle %d", __FUNCTION__, handle);
3430 if (sourceDesc == 0) {
3431 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3432 return BAD_VALUE;
3433 }
3434 status_t status = disconnectAudioSource(sourceDesc);
3435
3436 mAudioSources.removeItem(handle);
3437 return status;
3438}
3439
Andy Hung2ddee192015-12-18 17:34:44 -08003440status_t AudioPolicyManager::setMasterMono(bool mono)
3441{
3442 if (mMasterMono == mono) {
3443 return NO_ERROR;
3444 }
3445 mMasterMono = mono;
3446 // if enabling mono we close all offloaded devices, which will invalidate the
3447 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3448 // for recreating the new AudioTrack as non-offloaded PCM.
3449 //
3450 // If disabling mono, we leave all tracks as is: we don't know which clients
3451 // and tracks are able to be recreated as offloaded. The next "song" should
3452 // play back offloaded.
3453 if (mMasterMono) {
3454 Vector<audio_io_handle_t> offloaded;
3455 for (size_t i = 0; i < mOutputs.size(); ++i) {
3456 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3457 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3458 offloaded.push(desc->mIoHandle);
3459 }
3460 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003461 for (const auto& handle : offloaded) {
3462 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003463 }
3464 }
3465 // update master mono for all remaining outputs
3466 for (size_t i = 0; i < mOutputs.size(); ++i) {
3467 updateMono(mOutputs.keyAt(i));
3468 }
3469 return NO_ERROR;
3470}
3471
3472status_t AudioPolicyManager::getMasterMono(bool *mono)
3473{
3474 *mono = mMasterMono;
3475 return NO_ERROR;
3476}
3477
Eric Laurentac9cef52017-06-09 15:46:26 -07003478float AudioPolicyManager::getStreamVolumeDB(
3479 audio_stream_type_t stream, int index, audio_devices_t device)
3480{
3481 return computeVolume(stream, index, device);
3482}
3483
jiabin81772902018-04-02 17:52:27 -07003484status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3485 FormatVector& formats) {
3486 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3487 return BAD_VALUE;
3488 }
3489 String8 reply;
3490 reply = mpClientInterface->getParameters(
3491 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3492 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3493 AudioParameter repliedParameters(reply);
3494 if (repliedParameters.get(
3495 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3496 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3497 return BAD_VALUE;
3498 }
3499 for (auto format : formatsFromString(reply.string())) {
3500 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3501 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3502 if (format == AAC_FORMATS[i]) {
3503 format = AUDIO_FORMAT_AAC_LC;
3504 break;
3505 }
3506 }
3507 bool exist = false;
3508 for (size_t i = 0; i < formats.size(); i++) {
3509 if (format == formats[i]) {
3510 exist = true;
3511 break;
3512 }
3513 }
3514 bool isSurroundFormat = false;
3515 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3516 if (SURROUND_FORMATS[i] == format) {
3517 isSurroundFormat = true;
3518 break;
3519 }
3520 }
3521 if (!exist && isSurroundFormat) {
3522 formats.add(format);
3523 }
3524 }
3525 return NO_ERROR;
3526}
3527
3528status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3529 audio_format_t *surroundFormats,
3530 bool *surroundFormatsEnabled,
3531 bool reported)
3532{
3533 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3534 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3535 return BAD_VALUE;
3536 }
3537 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3538 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3539
3540 // Only return value if there is HDMI output.
3541 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3542 return INVALID_OPERATION;
3543 }
3544
3545 size_t formatsWritten = 0;
3546 size_t formatsMax = *numSurroundFormats;
3547 *numSurroundFormats = 0;
3548 FormatVector formats;
3549 if (reported) {
3550 // Only get surround formats which are reported by device.
3551 // First list already open outputs that can be routed to this device
3552 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3553 SortedVector<audio_io_handle_t> outputs;
3554 bool reportedFormatFound = false;
3555 status_t status;
3556 sp<SwAudioOutputDescriptor> desc;
3557 for (size_t i = 0; i < mOutputs.size(); i++) {
3558 desc = mOutputs.valueAt(i);
3559 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3560 outputs.add(mOutputs.keyAt(i));
3561 }
3562 }
3563 // Open an output to query dynamic parameters.
3564 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3565 AUDIO_DEVICE_OUT_HDMI);
3566 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3567 String8 address = hdmiOutputDevices[i]->mAddress;
3568 for (const auto& hwModule : mHwModules) {
3569 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3570 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3571 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3572 profile->supportDeviceAddress(address)) {
3573 size_t j;
3574 for (j = 0; j < outputs.size(); j++) {
3575 desc = mOutputs.valueFor(outputs.itemAt(j));
3576 if (!desc->isDuplicated() && desc->mProfile == profile) {
3577 break;
3578 }
3579 }
3580 if (j != outputs.size()) {
3581 status = getSupportedFormats(outputs.itemAt(j), formats);
3582 reportedFormatFound |= (status == NO_ERROR);
3583 continue;
3584 }
3585
3586 if (!profile->canOpenNewIo()) {
3587 ALOGW("Max Output number %u already opened for this profile %s",
3588 profile->maxOpenCount, profile->getTagName().c_str());
3589 continue;
3590 }
3591
3592 ALOGV("opening output for device %08x with params %s profile %p name %s",
3593 device, address.string(), profile.get(), profile->getName().string());
3594 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3595 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3596 status_t status = desc->open(nullptr, device, address,
3597 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3598 &output);
3599
3600 if (status == NO_ERROR) {
3601 status = getSupportedFormats(output, formats);
3602 reportedFormatFound |= (status == NO_ERROR);
3603 desc->close();
3604 output = AUDIO_IO_HANDLE_NONE;
3605 }
3606 }
3607 }
3608 }
3609 }
3610
3611 if (!reportedFormatFound) {
3612 return UNKNOWN_ERROR;
3613 }
3614 } else {
3615 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3616 formats.add(SURROUND_FORMATS[i]);
3617 }
3618 }
3619 for (size_t i = 0; i < formats.size(); i++) {
3620 if (formatsWritten < formatsMax) {
3621 surroundFormats[formatsWritten] = formats[i];
3622 bool formatEnabled = false;
3623 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3624 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3625 formatEnabled =
3626 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3627 break;
3628 }
3629 } else {
3630 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3631 }
3632 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3633 }
3634 (*numSurroundFormats)++;
3635 }
3636 return NO_ERROR;
3637}
3638
3639status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3640{
3641 // Check if audio format is a surround formats.
3642 bool isSurroundFormat = false;
3643 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3644 if (audioFormat == SURROUND_FORMATS[i]) {
3645 isSurroundFormat = true;
3646 break;
3647 }
3648 }
3649 if (!isSurroundFormat) {
3650 return BAD_VALUE;
3651 }
3652
3653 // Should only be called when MANUAL.
3654 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3655 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3656 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3657 return INVALID_OPERATION;
3658 }
3659
3660 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3661 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3662 return NO_ERROR;
3663 }
3664
3665 // The operation is valid only when there is HDMI output available.
3666 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3667 return INVALID_OPERATION;
3668 }
3669
3670 if (enabled) {
3671 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3672 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3673 mSurroundFormats.insert(AAC_FORMATS[i]);
3674 }
3675 } else {
3676 mSurroundFormats.insert(audioFormat);
3677 }
3678 } else {
3679 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3680 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3681 mSurroundFormats.erase(AAC_FORMATS[i]);
3682 }
3683 } else {
3684 mSurroundFormats.erase(audioFormat);
3685 }
3686 }
3687
3688 sp<SwAudioOutputDescriptor> outputDesc;
3689 bool profileUpdated = false;
3690 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3691 AUDIO_DEVICE_OUT_HDMI);
3692 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3693 // Simulate reconnection to update enabled surround sound formats.
3694 String8 address = hdmiOutputDevices[i]->mAddress;
3695 String8 name = hdmiOutputDevices[i]->getName();
3696 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3697 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3698 address.c_str(),
3699 name.c_str());
3700 if (status != NO_ERROR) {
3701 continue;
3702 }
3703 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3704 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3705 address.c_str(),
3706 name.c_str());
3707 profileUpdated |= (status == NO_ERROR);
3708 }
3709 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3710 AUDIO_DEVICE_IN_HDMI);
3711 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3712 // Simulate reconnection to update enabled surround sound formats.
3713 String8 address = hdmiInputDevices[i]->mAddress;
3714 String8 name = hdmiInputDevices[i]->getName();
3715 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3716 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3717 address.c_str(),
3718 name.c_str());
3719 if (status != NO_ERROR) {
3720 continue;
3721 }
3722 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3723 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3724 address.c_str(),
3725 name.c_str());
3726 profileUpdated |= (status == NO_ERROR);
3727 }
3728
3729 // Undo the surround formats change due to no audio profiles updated.
3730 if (!profileUpdated) {
3731 if (enabled) {
3732 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3733 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3734 mSurroundFormats.erase(AAC_FORMATS[i]);
3735 }
3736 } else {
3737 mSurroundFormats.erase(audioFormat);
3738 }
3739 } else {
3740 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3741 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3742 mSurroundFormats.insert(AAC_FORMATS[i]);
3743 }
3744 } else {
3745 mSurroundFormats.insert(audioFormat);
3746 }
3747 }
3748 }
3749
3750 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3751}
3752
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003753void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3754{
3755 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3756
3757 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3758 for (size_t i = 0; i < activeInputs.size(); i++) {
3759 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3760 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3761 for (size_t j = 0; j < activeSessions.size(); j++) {
3762 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3763 if (activeSession->uid() == uid) {
3764 activeSession->setSilenced(silenced);
3765 }
3766 }
3767 }
3768}
3769
Eric Laurentd60560a2015-04-10 11:31:20 -07003770status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3771{
3772 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3773
3774 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3775 if (patchDesc == 0) {
3776 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3777 sourceDesc->mPatchDesc->mHandle);
3778 return BAD_VALUE;
3779 }
3780 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3781
Eric Laurent28d09f02016-03-08 10:43:05 -08003782 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003783 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3784 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003785 status_t status = stopSource(swOutputDesc, stream, false);
3786 if (status == NO_ERROR) {
3787 swOutputDesc->stop();
3788 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003789 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3790 } else {
3791 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3792 if (hwOutputDesc != 0) {
3793 // release patch between src device and output device
3794 // close Hwoutput and remove from mHwOutputs
3795 } else {
3796 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3797 }
3798 }
3799 return NO_ERROR;
3800}
3801
3802sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3803 audio_io_handle_t output, routing_strategy strategy)
3804{
3805 sp<AudioSourceDescriptor> source;
3806 for (size_t i = 0; i < mAudioSources.size(); i++) {
3807 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3808 routing_strategy sourceStrategy =
3809 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3810 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3811 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3812 source = sourceDesc;
3813 break;
3814 }
3815 }
3816 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003817}
3818
Eric Laurente552edb2014-03-10 17:42:56 -07003819// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003820// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003821// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003822uint32_t AudioPolicyManager::nextAudioPortGeneration()
3823{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003824 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003825}
3826
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003827#ifdef USE_XML_AUDIO_POLICY_CONF
3828// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3829static const char *kConfigLocationList[] =
3830 {"/odm/etc", "/vendor/etc", "/system/etc"};
3831static const int kConfigLocationListSize =
3832 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3833
3834static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3835 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gynther150b9842018-04-17 18:46:10 -07003836 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003837 status_t ret;
3838
Petri Gynther150b9842018-04-17 18:46:10 -07003839 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3840 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3841 // A2DP offload supported but disabled: try to use special XML file
3842 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3843 }
3844 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3845
3846 for (const char* fileName : fileNames) {
3847 for (int i = 0; i < kConfigLocationListSize; i++) {
3848 PolicySerializer serializer;
3849 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3850 "%s/%s", kConfigLocationList[i], fileName);
3851 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3852 if (ret == NO_ERROR) {
3853 return ret;
3854 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003855 }
3856 }
3857 return ret;
3858}
3859#endif
3860
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3862 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003863 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003864 mUidCached(getuid()),
3865 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003866 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003867 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003868#ifdef USE_XML_AUDIO_POLICY_CONF
3869 mVolumeCurves(new VolumeCurvesCollection()),
3870 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003871 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003872#else
3873 mVolumeCurves(new StreamDescriptorCollection()),
3874 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3875 mDefaultOutputDevice),
3876#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003877 mAudioPortGeneration(1),
3878 mBeaconMuteRefCount(0),
3879 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003880 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003881 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003882 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003883 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3884 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003885{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003886}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003887
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3889 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3890{
3891 loadConfig();
3892 initialize();
3893}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003895void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003896#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003897 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003898#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3900 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003901#endif
3902 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003903 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003904 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003905}
3906
3907status_t AudioPolicyManager::initialize() {
3908 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003909
3910 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003911 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3912 if (!engineInstance) {
3913 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003914 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003915 }
3916 // Retrieve the Policy Manager Interface
3917 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3918 if (mEngine == NULL) {
3919 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003920 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003921 }
3922 mEngine->setObserver(this);
3923 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003924 if (status != NO_ERROR) {
3925 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3926 return status;
3927 }
François Gaffie2110e042015-03-24 08:41:51 +01003928
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003930 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003931 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3932 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003933 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003934 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003935 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3936 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003937 continue;
3938 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003940 // open all output streams needed to access attached devices
3941 // except for direct output streams that are only opened when they are actually
3942 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003943 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003944 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003945 if (!outProfile->canOpenNewIo()) {
3946 ALOGE("Invalid Output profile max open count %u for profile %s",
3947 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3948 continue;
3949 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003950 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003951 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 continue;
3953 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003954 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003955 mTtsOutputAvailable = true;
3956 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003957
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 continue;
3960 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003961 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003962 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3963 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003964 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003965 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003966 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003967 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003968 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003969 if ((profileType & outputDeviceTypes) == 0) {
3970 continue;
3971 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003972 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3973 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003974 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3975 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3976 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3977 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003978 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003979 status_t status = outputDesc->open(nullptr, profileType, address,
3980 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003981
3982 if (status != NO_ERROR) {
3983 ALOGW("Cannot open output stream for device %08x on hw module %s",
3984 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003985 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003986 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003987 for (const auto& dev : supportedDevices) {
3988 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003989 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003990 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003991 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003992 }
3993 }
3994 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003995 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003996 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003997 }
3998 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003999 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004000 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004001 true,
4002 0,
4003 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004004 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004005 }
Eric Laurente552edb2014-03-10 17:42:56 -07004006 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004007 // open input streams needed to access attached devices to validate
4008 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004009 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004010 if (!inProfile->canOpenNewIo()) {
4011 ALOGE("Invalid Input profile max open count %u for profile %s",
4012 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4013 continue;
4014 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004015 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004016 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004017 continue;
4018 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004019 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004020 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004021 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4022
Eric Laurentd78f1532014-09-16 16:38:20 -07004023 if ((profileType & inputDeviceTypes) == 0) {
4024 continue;
4025 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004026 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004027 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004028
Eric Laurent53b810e2017-12-10 17:25:10 -08004029 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4030 // the inputs vector must be of size >= 1, but we don't want to crash here
4031 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4032 : String8("");
4033 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4034 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4035
Eric Laurentd78f1532014-09-16 16:38:20 -07004036 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004037 status_t status = inputDesc->open(nullptr,
4038 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004039 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004040 AUDIO_SOURCE_MIC,
4041 AUDIO_INPUT_FLAG_NONE,
4042 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004043
4044 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004045 for (const auto& dev : inProfile->getSupportedDevices()) {
4046 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004047 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004048 if (index >= 0) {
4049 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4050 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004051 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004052 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004053 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004054 }
4055 }
Eric Laurentfe231122017-11-17 17:48:06 -08004056 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004057 } else {
4058 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004059 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004060 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004061 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 }
4063 }
4064 // make sure all attached devices have been allocated a unique ID
4065 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004066 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004067 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4069 continue;
4070 }
François Gaffie2110e042015-03-24 08:41:51 +01004071 // The device is now validated and can be appended to the available devices of the engine
4072 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4073 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004074 i++;
4075 }
4076 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004077 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004078 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004079 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4080 continue;
4081 }
François Gaffie2110e042015-03-24 08:41:51 +01004082 // The device is now validated and can be appended to the available devices of the engine
4083 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4084 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 i++;
4086 }
4087 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004088 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004089 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004090 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 }
jiabin9ff780e2018-03-19 18:19:52 -07004092 // If microphones address is empty, set it according to device type
4093 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4094 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4095 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4096 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4097 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4098 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4099 }
4100 }
4101 }
Eric Laurente552edb2014-03-10 17:42:56 -07004102
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004103 if (mPrimaryOutput == 0) {
4104 ALOGE("Failed to open primary output");
4105 status = NO_INIT;
4106 }
Eric Laurente552edb2014-03-10 17:42:56 -07004107
4108 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004109 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004110}
4111
Eric Laurente0720872014-03-11 09:30:41 -07004112AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004113{
Eric Laurente552edb2014-03-10 17:42:56 -07004114 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004115 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004116 }
4117 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004118 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004119 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004120 mAvailableOutputDevices.clear();
4121 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004122 mOutputs.clear();
4123 mInputs.clear();
4124 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004125 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004126 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004127}
4128
Eric Laurente0720872014-03-11 09:30:41 -07004129status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004130{
Eric Laurent87ffa392015-05-22 10:32:38 -07004131 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004132}
4133
Eric Laurente552edb2014-03-10 17:42:56 -07004134// ---
4135
Eric Laurent98e38192018-02-15 18:31:53 -08004136void AudioPolicyManager::addOutput(audio_io_handle_t output,
4137 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004138{
Eric Laurent1c333e22014-05-20 10:48:17 -07004139 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004140 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004141 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004142 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004143 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004144}
4145
François Gaffie53615e22015-03-19 09:24:12 +01004146void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4147{
4148 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004149 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004150}
4151
Eric Laurent98e38192018-02-15 18:31:53 -08004152void AudioPolicyManager::addInput(audio_io_handle_t input,
4153 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004154{
Eric Laurent1c333e22014-05-20 10:48:17 -07004155 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004156 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004157}
Eric Laurente552edb2014-03-10 17:42:56 -07004158
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004159void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004160 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004161 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004162 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004163 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004164 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004165 if (devDesc != 0) {
4166 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4167 desc->mIoHandle, address.string());
4168 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004169 }
4170}
4171
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004172status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004173 audio_policy_dev_state_t state,
4174 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004175 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
François Gaffie53615e22015-03-19 09:24:12 +01004177 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004178 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004179
4180 if (audio_device_is_digital(device)) {
4181 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004182 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004183 }
Eric Laurente552edb2014-03-10 17:42:56 -07004184
Eric Laurent3b73df72014-03-11 09:06:29 -07004185 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004186 // first list already open outputs that can be routed to this device
4187 for (size_t i = 0; i < mOutputs.size(); i++) {
4188 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004189 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004190 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004191 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4192 outputs.add(mOutputs.keyAt(i));
4193 } else {
4194 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004195 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004196 }
Eric Laurente552edb2014-03-10 17:42:56 -07004197 }
4198 }
4199 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004200 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004201 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004202 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4203 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004204 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004205 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004206 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004207 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004208 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4209 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004210 }
Eric Laurente552edb2014-03-10 17:42:56 -07004211 }
4212 }
4213 }
4214
Eric Laurent7b279bb2015-12-14 10:18:23 -08004215 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004216
Eric Laurente552edb2014-03-10 17:42:56 -07004217 if (profiles.isEmpty() && outputs.isEmpty()) {
4218 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4219 return BAD_VALUE;
4220 }
4221
4222 // open outputs for matching profiles if needed. Direct outputs are also opened to
4223 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4224 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004225 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004226
4227 // nothing to do if one output is already opened for this profile
4228 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004229 for (j = 0; j < outputs.size(); j++) {
4230 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004231 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004232 // matching profile: save the sample rates, format and channel masks supported
4233 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004234 if (audio_device_is_digital(device)) {
4235 devDesc->importAudioPort(profile);
4236 }
Eric Laurente552edb2014-03-10 17:42:56 -07004237 break;
4238 }
4239 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004240 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004241 continue;
4242 }
4243
Eric Laurent3974e3b2017-12-07 17:58:43 -08004244 if (!profile->canOpenNewIo()) {
4245 ALOGW("Max Output number %u already opened for this profile %s",
4246 profile->maxOpenCount, profile->getTagName().c_str());
4247 continue;
4248 }
4249
Eric Laurent83efe1c2017-07-09 16:51:08 -07004250 ALOGV("opening output for device %08x with params %s profile %p name %s",
4251 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004252 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004253 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004254 status_t status = desc->open(nullptr, device, address,
4255 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004256
Eric Laurentfe231122017-11-17 17:48:06 -08004257 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004258 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004259 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004260 char *param = audio_device_address_to_parameter(device, address);
4261 mpClientInterface->setParameters(output, String8(param));
4262 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004263 }
Phil Burk00eeb322016-03-31 12:41:00 -07004264 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004265 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004266 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004267 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004268 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004269 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004270 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004271 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004272 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4273 profile->pickAudioProfile(
4274 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004275 config.offload_info.sample_rate = config.sample_rate;
4276 config.offload_info.channel_mask = config.channel_mask;
4277 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004278
4279 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4280 AUDIO_OUTPUT_FLAG_NONE, &output);
4281 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004282 output = AUDIO_IO_HANDLE_NONE;
4283 }
Eric Laurentd4692962014-05-05 18:13:44 -07004284 }
4285
Eric Laurentcf2c0212014-07-25 16:20:43 -07004286 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004287 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004288 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004289 sp<AudioPolicyMix> policyMix;
4290 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004291 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4292 address.string());
4293 }
François Gaffie036e1e92015-03-19 10:16:24 +01004294 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004295 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004296
Eric Laurent87ffa392015-05-22 10:32:38 -07004297 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4298 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004299 // no duplicated output for direct outputs and
4300 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004301 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004302
Eric Laurentd4692962014-05-05 18:13:44 -07004303 //TODO: configure audio effect output stage here
4304
4305 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004306 sp<SwAudioOutputDescriptor> dupOutputDesc =
4307 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4308 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4309 &duplicatedOutput);
4310 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004311 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004312 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004313 } else {
4314 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004315 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004316 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004317 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004318 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004320 }
Eric Laurente552edb2014-03-10 17:42:56 -07004321 }
4322 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004323 } else {
4324 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004325 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004326 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004327 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004328 profiles.removeAt(profile_index);
4329 profile_index--;
4330 } else {
4331 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004332 // Load digital format info only for digital devices
4333 if (audio_device_is_digital(device)) {
4334 devDesc->importAudioPort(profile);
4335 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004336
François Gaffie53615e22015-03-19 09:24:12 +01004337 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004338 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4339 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004340 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004341 NULL/*patch handle*/, address.string());
4342 }
Eric Laurente552edb2014-03-10 17:42:56 -07004343 ALOGV("checkOutputsForDevice(): adding output %d", output);
4344 }
4345 }
4346
4347 if (profiles.isEmpty()) {
4348 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4349 return BAD_VALUE;
4350 }
Eric Laurentd4692962014-05-05 18:13:44 -07004351 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004352 // check if one opened output is not needed any more after disconnecting one device
4353 for (size_t i = 0; i < mOutputs.size(); i++) {
4354 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004355 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004356 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004357 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004358 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004359 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004360 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004361 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4362 mOutputs.keyAt(i));
4363 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004364 }
Eric Laurente552edb2014-03-10 17:42:56 -07004365 }
4366 }
Eric Laurentd4692962014-05-05 18:13:44 -07004367 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004368 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004369 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4370 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004371 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004372 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004373 "clearing direct output profile %zu on module %s",
4374 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004375 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004376 }
4377 }
4378 }
4379 }
4380 return NO_ERROR;
4381}
4382
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004383status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004384 audio_policy_dev_state_t state,
4385 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004386 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004387{
Paul McLean9080a4c2015-06-18 08:24:02 -07004388 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004389 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004390
4391 if (audio_device_is_digital(device)) {
4392 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004393 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004394 }
4395
Eric Laurentd4692962014-05-05 18:13:44 -07004396 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4397 // first list already open inputs that can be routed to this device
4398 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4399 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004400 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004401 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4402 inputs.add(mInputs.keyAt(input_index));
4403 }
4404 }
4405
4406 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004407 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004408 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004409 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004410 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004411 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004412 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004413
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004414 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004415 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004416 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004417 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004418 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4419 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004420 }
Eric Laurentd4692962014-05-05 18:13:44 -07004421 }
4422 }
4423 }
4424
4425 if (profiles.isEmpty() && inputs.isEmpty()) {
4426 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4427 return BAD_VALUE;
4428 }
4429
4430 // open inputs for matching profiles if needed. Direct inputs are also opened to
4431 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4432 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4433
Eric Laurent1c333e22014-05-20 10:48:17 -07004434 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004435
Eric Laurentd4692962014-05-05 18:13:44 -07004436 // nothing to do if one input is already opened for this profile
4437 size_t input_index;
4438 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4439 desc = mInputs.valueAt(input_index);
4440 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004441 if (audio_device_is_digital(device)) {
4442 devDesc->importAudioPort(profile);
4443 }
Eric Laurentd4692962014-05-05 18:13:44 -07004444 break;
4445 }
4446 }
4447 if (input_index != mInputs.size()) {
4448 continue;
4449 }
4450
Eric Laurent3974e3b2017-12-07 17:58:43 -08004451 if (!profile->canOpenNewIo()) {
4452 ALOGW("Max Input number %u already opened for this profile %s",
4453 profile->maxOpenCount, profile->getTagName().c_str());
4454 continue;
4455 }
4456
Eric Laurentfe231122017-11-17 17:48:06 -08004457 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004458 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004459 status_t status = desc->open(nullptr,
4460 device,
4461 address,
4462 AUDIO_SOURCE_MIC,
4463 AUDIO_INPUT_FLAG_NONE,
4464 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004465
Eric Laurentcf2c0212014-07-25 16:20:43 -07004466 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004467 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004468 char *param = audio_device_address_to_parameter(device, address);
4469 mpClientInterface->setParameters(input, String8(param));
4470 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004471 }
Phil Burk00eeb322016-03-31 12:41:00 -07004472 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004473 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004474 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004475 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004476 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004477 }
4478
4479 if (input != 0) {
4480 addInput(input, desc);
4481 }
4482 } // endif input != 0
4483
Eric Laurentcf2c0212014-07-25 16:20:43 -07004484 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004485 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004486 profiles.removeAt(profile_index);
4487 profile_index--;
4488 } else {
4489 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004490 if (audio_device_is_digital(device)) {
4491 devDesc->importAudioPort(profile);
4492 }
Eric Laurentd4692962014-05-05 18:13:44 -07004493 ALOGV("checkInputsForDevice(): adding input %d", input);
4494 }
4495 } // end scan profiles
4496
4497 if (profiles.isEmpty()) {
4498 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4499 return BAD_VALUE;
4500 }
4501 } else {
4502 // Disconnect
4503 // check if one opened input is not needed any more after disconnecting one device
4504 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4505 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004506 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004507 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4508 mInputs.keyAt(input_index));
4509 inputs.add(mInputs.keyAt(input_index));
4510 }
4511 }
4512 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004513 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004514 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004515 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004516 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004517 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004518 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004519 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4520 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004521 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004522 }
4523 }
4524 }
4525 } // end disconnect
4526
4527 return NO_ERROR;
4528}
4529
4530
Eric Laurente0720872014-03-11 09:30:41 -07004531void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004532{
4533 ALOGV("closeOutput(%d)", output);
4534
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 if (outputDesc == NULL) {
4537 ALOGW("closeOutput() unknown output %d", output);
4538 return;
4539 }
François Gaffie036e1e92015-03-19 10:16:24 +01004540 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004541
Eric Laurente552edb2014-03-10 17:42:56 -07004542 // look for duplicated outputs connected to the output being removed.
4543 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004544 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004545 if (dupOutputDesc->isDuplicated() &&
4546 (dupOutputDesc->mOutput1 == outputDesc ||
4547 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004548 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004549 if (dupOutputDesc->mOutput1 == outputDesc) {
4550 outputDesc2 = dupOutputDesc->mOutput2;
4551 } else {
4552 outputDesc2 = dupOutputDesc->mOutput1;
4553 }
4554 // As all active tracks on duplicated output will be deleted,
4555 // and as they were also referenced on the other output, the reference
4556 // count for their stream type must be adjusted accordingly on
4557 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004558 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004559 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004560 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004561 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004562 }
Eric Laurent733ce942017-12-07 12:18:25 -08004563 // stop() will be a no op if the output is still active but is needed in case all
4564 // active streams refcounts where cleared above
4565 if (wasActive) {
4566 outputDesc2->stop();
4567 }
Eric Laurente552edb2014-03-10 17:42:56 -07004568 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4569 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4570
4571 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004572 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004573 }
4574 }
4575
Eric Laurent05b90f82014-08-27 15:32:29 -07004576 nextAudioPortGeneration();
4577
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004578 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004579 if (index >= 0) {
4580 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004581 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004582 mAudioPatches.removeItemsAt(index);
4583 mpClientInterface->onAudioPatchListUpdate();
4584 }
4585
Eric Laurentfe231122017-11-17 17:48:06 -08004586 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004587
François Gaffie53615e22015-03-19 09:24:12 +01004588 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004589 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004590}
4591
4592void AudioPolicyManager::closeInput(audio_io_handle_t input)
4593{
4594 ALOGV("closeInput(%d)", input);
4595
4596 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4597 if (inputDesc == NULL) {
4598 ALOGW("closeInput() unknown input %d", input);
4599 return;
4600 }
4601
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004603
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004604 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004605 if (index >= 0) {
4606 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004607 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004608 mAudioPatches.removeItemsAt(index);
4609 mpClientInterface->onAudioPatchListUpdate();
4610 }
4611
Eric Laurentfe231122017-11-17 17:48:06 -08004612 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004613 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004614}
4615
Eric Laurentc75307b2015-03-17 15:29:32 -07004616SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4617 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004618 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004619{
4620 SortedVector<audio_io_handle_t> outputs;
4621
4622 ALOGVV("getOutputsForDevice() device %04x", device);
4623 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004624 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004625 i, openOutputs.valueAt(i)->isDuplicated(),
4626 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4628 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4629 outputs.add(openOutputs.keyAt(i));
4630 }
4631 }
4632 return outputs;
4633}
4634
Eric Laurente0720872014-03-11 09:30:41 -07004635bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004636 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004637{
4638 if (outputs1.size() != outputs2.size()) {
4639 return false;
4640 }
4641 for (size_t i = 0; i < outputs1.size(); i++) {
4642 if (outputs1[i] != outputs2[i]) {
4643 return false;
4644 }
4645 }
4646 return true;
4647}
4648
Eric Laurente0720872014-03-11 09:30:41 -07004649void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004650{
4651 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4652 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4653 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4654 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4655
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004656 // also take into account external policy-related changes: add all outputs which are
4657 // associated with policies in the "before" and "after" output vectors
4658 ALOGVV("checkOutputForStrategy(): policy related outputs");
4659 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004661 if (desc != 0 && desc->mPolicyMix != NULL) {
4662 srcOutputs.add(desc->mIoHandle);
4663 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4664 }
4665 }
4666 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004667 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004668 if (desc != 0 && desc->mPolicyMix != NULL) {
4669 dstOutputs.add(desc->mIoHandle);
4670 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4671 }
4672 }
4673
Eric Laurente552edb2014-03-10 17:42:56 -07004674 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4675 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4676 strategy, srcOutputs[0], dstOutputs[0]);
4677 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004678 for (audio_io_handle_t srcOut : srcOutputs) {
4679 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOut);
François Gaffiead3183e2015-03-18 16:55:35 +01004680 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004681 setStrategyMute(strategy, true, desc);
4682 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004683 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004684 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004685 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004686 if (source != 0){
4687 connectAudioSource(source);
4688 }
Eric Laurente552edb2014-03-10 17:42:56 -07004689 }
4690
4691 // Move effects associated to this strategy from previous output to new output
4692 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004693 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004694 }
4695 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004696 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004697 if (getStrategy((audio_stream_type_t)i) == strategy) {
4698 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004699 }
4700 }
4701 }
4702}
4703
Eric Laurente0720872014-03-11 09:30:41 -07004704void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004705{
François Gaffie2110e042015-03-24 08:41:51 +01004706 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004707 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004708 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004709 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004710 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004711 checkOutputForStrategy(STRATEGY_SONIFICATION);
4712 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004713 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004714 checkOutputForStrategy(STRATEGY_MEDIA);
4715 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004716 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004717}
4718
Eric Laurente0720872014-03-11 09:30:41 -07004719void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004720{
François Gaffie53615e22015-03-19 09:24:12 +01004721 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004722 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004723 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004724 return;
4725 }
4726
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004728 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4729 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4730 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004731
4732 // if suspended, restore A2DP output if:
4733 // ((SCO device is NOT connected) ||
4734 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4735 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004736 //
Eric Laurentf732e072016-08-03 19:30:28 -07004737 // if not suspended, suspend A2DP output if:
4738 // (SCO device is connected) &&
4739 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4740 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004741 //
4742 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004743 if (!isScoConnected ||
4744 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4745 AUDIO_POLICY_FORCE_BT_SCO) &&
4746 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4747 AUDIO_POLICY_FORCE_BT_SCO) &&
4748 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004749 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004750
4751 mpClientInterface->restoreOutput(a2dpOutput);
4752 mA2dpSuspended = false;
4753 }
4754 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004755 if (isScoConnected &&
4756 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4757 AUDIO_POLICY_FORCE_BT_SCO) ||
4758 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4759 AUDIO_POLICY_FORCE_BT_SCO) ||
4760 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004761 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004762
4763 mpClientInterface->suspendOutput(a2dpOutput);
4764 mA2dpSuspended = true;
4765 }
4766 }
4767}
4768
Eric Laurentc75307b2015-03-17 15:29:32 -07004769audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4770 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004771{
4772 audio_devices_t device = AUDIO_DEVICE_NONE;
4773
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004774 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004775 if (index >= 0) {
4776 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4777 if (patchDesc->mUid != mUidCached) {
4778 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004779 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004780 return outputDesc->device();
4781 }
4782 }
4783
Eric Laurente552edb2014-03-10 17:42:56 -07004784 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004785 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004786 // use device for strategy enforced audible
4787 // 2: we are in call or the strategy phone is active on the output:
4788 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004789 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004790 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004791 // 4: the strategy for enforced audible is active but not enforced on the output:
4792 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004793 // 5: the strategy accessibility is active on the output:
4794 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004795 // 6: the strategy "respectful" sonification is active on the output:
4796 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004797 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004798 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004799 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004800 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004801 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004802 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004803 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004804 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004805 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4806 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004807 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004808 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004809 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004810 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004811 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4812 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004813 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4814 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004815 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004816 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004817 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004818 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004819 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004820 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004821 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004822 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004823 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004824 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004825 }
4826
Eric Laurent1c333e22014-05-20 10:48:17 -07004827 ALOGV("getNewOutputDevice() selected device %x", device);
4828 return device;
4829}
4830
Eric Laurentfb66dd92016-01-28 18:32:03 -08004831audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004832{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004833 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004834
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004835 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 if (index >= 0) {
4837 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4838 if (patchDesc->mUid != mUidCached) {
4839 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004840 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 return inputDesc->mDevice;
4842 }
4843 }
4844
Eric Laurentdc95a252018-04-12 12:46:56 -07004845 // If we are not in call and no client is active on this input, this methods returns
4846 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004847 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004848 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4849 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4850 }
4851 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004852 device = getDeviceAndMixForInputSource(source);
4853 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004854
Eric Laurente552edb2014-03-10 17:42:56 -07004855 return device;
4856}
4857
Eric Laurent794fde22016-03-11 09:50:45 -08004858bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4859 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004860 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004861}
4862
Eric Laurente0720872014-03-11 09:30:41 -07004863uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004864 return (uint32_t)getStrategy(stream);
4865}
4866
Eric Laurente0720872014-03-11 09:30:41 -07004867audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 // By checking the range of stream before calling getStrategy, we avoid
4869 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4870 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004871 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 return AUDIO_DEVICE_NONE;
4873 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004874 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004875 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4876 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004877 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004878 }
Eric Laurent794fde22016-03-11 09:50:45 -08004879 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004880 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004881 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004882 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4883 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004884 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004885 curDevices |= outputDesc->device();
4886 }
4887 }
4888 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004889 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004890
4891 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4892 and doesn't really need to.*/
4893 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4894 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4895 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4896 }
Eric Laurente552edb2014-03-10 17:42:56 -07004897 return devices;
4898}
4899
François Gaffie2110e042015-03-24 08:41:51 +01004900routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4901{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004902 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004903 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004904}
4905
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004906uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4907 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004908 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4909 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4910 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004911 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4912 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4913 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004914 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004915 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004916}
4917
Eric Laurente0720872014-03-11 09:30:41 -07004918void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004919 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004920 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004921 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4922 updateDevicesAndOutputs();
4923 break;
4924 default:
4925 break;
4926 }
4927}
4928
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004929uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004930
4931 // skip beacon mute management if a dedicated TTS output is available
4932 if (mTtsOutputAvailable) {
4933 return 0;
4934 }
4935
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004936 switch(event) {
4937 case STARTING_OUTPUT:
4938 mBeaconMuteRefCount++;
4939 break;
4940 case STOPPING_OUTPUT:
4941 if (mBeaconMuteRefCount > 0) {
4942 mBeaconMuteRefCount--;
4943 }
4944 break;
4945 case STARTING_BEACON:
4946 mBeaconPlayingRefCount++;
4947 break;
4948 case STOPPING_BEACON:
4949 if (mBeaconPlayingRefCount > 0) {
4950 mBeaconPlayingRefCount--;
4951 }
4952 break;
4953 }
4954
4955 if (mBeaconMuteRefCount > 0) {
4956 // any playback causes beacon to be muted
4957 return setBeaconMute(true);
4958 } else {
4959 // no other playback: unmute when beacon starts playing, mute when it stops
4960 return setBeaconMute(mBeaconPlayingRefCount == 0);
4961 }
4962}
4963
4964uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4965 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4966 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4967 // keep track of muted state to avoid repeating mute/unmute operations
4968 if (mBeaconMuted != mute) {
4969 // mute/unmute AUDIO_STREAM_TTS on all outputs
4970 ALOGV("\t muting %d", mute);
4971 uint32_t maxLatency = 0;
4972 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004973 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004974 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004975 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004976 0 /*delay*/, AUDIO_DEVICE_NONE);
4977 const uint32_t latency = desc->latency() * 2;
4978 if (latency > maxLatency) {
4979 maxLatency = latency;
4980 }
4981 }
4982 mBeaconMuted = mute;
4983 return maxLatency;
4984 }
4985 return 0;
4986}
4987
Eric Laurente0720872014-03-11 09:30:41 -07004988audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004989 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004990{
Paul McLeanaa981192015-03-21 09:55:15 -07004991 // Routing
4992 // see if we have an explicit route
4993 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4994 // (getStrategy(stream)).
4995 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07004996 // and activity count is non-zero and the device in the route descriptor is available
4997 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07004998 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4999 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08005000 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005001 if ((routeStrategy == strategy) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005002 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07005003 return route->mDeviceDescriptor->type();
5004 }
5005 }
5006
Eric Laurente552edb2014-03-10 17:42:56 -07005007 if (fromCache) {
5008 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5009 strategy, mDeviceForStrategy[strategy]);
5010 return mDeviceForStrategy[strategy];
5011 }
François Gaffie2110e042015-03-24 08:41:51 +01005012 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005013}
5014
Eric Laurente0720872014-03-11 09:30:41 -07005015void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005016{
5017 for (int i = 0; i < NUM_STRATEGIES; i++) {
5018 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5019 }
5020 mPreviousOutputs = mOutputs;
5021}
5022
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005023uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005024 audio_devices_t prevDevice,
5025 uint32_t delayMs)
5026{
5027 // mute/unmute strategies using an incompatible device combination
5028 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5029 // if unmuting, unmute only after the specified delay
5030 if (outputDesc->isDuplicated()) {
5031 return 0;
5032 }
5033
5034 uint32_t muteWaitMs = 0;
5035 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005036 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005037
5038 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5039 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005040 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005041 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5042 bool doMute = false;
5043
5044 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5045 doMute = true;
5046 outputDesc->mStrategyMutedByDevice[i] = true;
5047 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5048 doMute = true;
5049 outputDesc->mStrategyMutedByDevice[i] = false;
5050 }
Eric Laurent99401132014-05-07 19:48:15 -07005051 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005052 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005053 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005054 // skip output if it does not share any device with current output
5055 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5056 == AUDIO_DEVICE_NONE) {
5057 continue;
5058 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005059 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 mute ? "muting" : "unmuting", i, curDevice);
5061 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005062 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005063 if (mute) {
5064 // FIXME: should not need to double latency if volume could be applied
5065 // immediately by the audioflinger mixer. We must account for the delay
5066 // between now and the next time the audioflinger thread for this output
5067 // will process a buffer (which corresponds to one buffer size,
5068 // usually 1/2 or 1/4 of the latency).
5069 if (muteWaitMs < desc->latency() * 2) {
5070 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005071 }
5072 }
5073 }
5074 }
5075 }
5076 }
5077
Eric Laurent99401132014-05-07 19:48:15 -07005078 // temporary mute output if device selection changes to avoid volume bursts due to
5079 // different per device volumes
5080 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005081 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5082 // temporary mute duration is conservatively set to 4 times the reported latency
5083 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5084 if (muteWaitMs < tempMuteWaitMs) {
5085 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005086 }
Eric Laurentdc462862016-07-19 12:29:53 -07005087
Eric Laurent99401132014-05-07 19:48:15 -07005088 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005089 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005090 // make sure that we do not start the temporary mute period too early in case of
5091 // delayed device change
5092 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005093 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005094 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005095 }
5096 }
5097 }
5098
Eric Laurente552edb2014-03-10 17:42:56 -07005099 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5100 if (muteWaitMs > delayMs) {
5101 muteWaitMs -= delayMs;
5102 usleep(muteWaitMs * 1000);
5103 return muteWaitMs;
5104 }
5105 return 0;
5106}
5107
Eric Laurentc75307b2015-03-17 15:29:32 -07005108uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005109 audio_devices_t device,
5110 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005112 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005113 const char *address,
5114 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005115{
Eric Laurentc75307b2015-03-17 15:29:32 -07005116 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005117 AudioParameter param;
5118 uint32_t muteWaitMs;
5119
5120 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005121 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5122 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5123 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5124 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005125 return muteWaitMs;
5126 }
5127 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5128 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005129 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005130 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005131 return 0;
5132 }
5133
5134 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005135 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005136
5137 audio_devices_t prevDevice = outputDesc->mDevice;
5138
Paul McLeanaa981192015-03-21 09:55:15 -07005139 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005140
5141 if (device != AUDIO_DEVICE_NONE) {
5142 outputDesc->mDevice = device;
5143 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005144
5145 // if the outputs are not materially active, there is no need to mute.
5146 if (requiresMuteCheck) {
5147 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5148 } else {
5149 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5150 muteWaitMs = 0;
5151 }
Eric Laurente552edb2014-03-10 17:42:56 -07005152
5153 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005154 // the requested device is AUDIO_DEVICE_NONE
5155 // OR the requested device is the same as current device
5156 // AND force is not specified
5157 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005158 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005159 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5160 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005161 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005163 return muteWaitMs;
5164 }
5165
5166 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005167
Eric Laurente552edb2014-03-10 17:42:56 -07005168 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005169 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005170 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005171 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005172 DeviceVector deviceList;
5173 if ((address == NULL) || (strlen(address) == 0)) {
5174 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5175 } else {
5176 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5177 }
5178
Eric Laurent1c333e22014-05-20 10:48:17 -07005179 if (!deviceList.isEmpty()) {
5180 struct audio_patch patch;
5181 outputDesc->toAudioPortConfig(&patch.sources[0]);
5182 patch.num_sources = 1;
5183 patch.num_sinks = 0;
5184 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5185 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005186 patch.num_sinks++;
5187 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 ssize_t index;
5189 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5190 index = mAudioPatches.indexOfKey(*patchHandle);
5191 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005192 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 }
5194 sp< AudioPatch> patchDesc;
5195 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5196 if (index >= 0) {
5197 patchDesc = mAudioPatches.valueAt(index);
5198 afPatchHandle = patchDesc->mAfPatchHandle;
5199 }
5200
Eric Laurent1c333e22014-05-20 10:48:17 -07005201 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 &afPatchHandle,
5203 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5205 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005207 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005209 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 addAudioPatch(patchDesc->mHandle, patchDesc);
5211 } else {
5212 patchDesc->mPatch = patch;
5213 }
5214 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 if (patchHandle) {
5216 *patchHandle = patchDesc->mHandle;
5217 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005218 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005220 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005221 }
5222 }
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
5279 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5280 if (!deviceList.isEmpty()) {
5281 struct audio_patch patch;
5282 inputDesc->toAudioPortConfig(&patch.sinks[0]);
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
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005285 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005286 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005287 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5288 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005289 patch.num_sinks = 1;
5290 //only one input device for now
5291 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005292 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 ssize_t index;
5294 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5295 index = mAudioPatches.indexOfKey(*patchHandle);
5296 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005297 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005298 }
5299 sp< AudioPatch> patchDesc;
5300 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5301 if (index >= 0) {
5302 patchDesc = mAudioPatches.valueAt(index);
5303 afPatchHandle = patchDesc->mAfPatchHandle;
5304 }
5305
Eric Laurent1c333e22014-05-20 10:48:17 -07005306 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005308 0);
5309 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005311 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005313 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 addAudioPatch(patchDesc->mHandle, patchDesc);
5315 } else {
5316 patchDesc->mPatch = patch;
5317 }
5318 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 if (patchHandle) {
5320 *patchHandle = patchDesc->mHandle;
5321 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005322 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005324 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 }
5326 }
5327 }
5328 return status;
5329}
5330
Eric Laurent6a94d692014-05-20 11:18:06 -07005331status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5332 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005333{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005334 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 ssize_t index;
5336 if (patchHandle) {
5337 index = mAudioPatches.indexOfKey(*patchHandle);
5338 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005339 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 }
5341 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005342 return INVALID_OPERATION;
5343 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5345 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005346 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005347 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005348 removeAudioPatch(patchDesc->mHandle);
5349 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005350 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005351 return status;
5352}
5353
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005354sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005355 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005356 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005357 audio_format_t& format,
5358 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005359 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005360{
5361 // Choose an input profile based on the requested capture parameters: select the first available
5362 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005363 //
5364 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5365 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005366
Glenn Kasten730b9262018-03-29 15:01:26 -07005367 sp<IOProfile> firstInexact;
5368 uint32_t updatedSamplingRate = 0;
5369 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5370 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005371 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005372 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005373 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005374 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005375 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005376 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005377 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005378 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005379 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005380 &channelMask /*updatedChannelMask*/,
5381 // FIXME ugly cast
5382 (audio_output_flags_t) flags,
5383 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005384 return profile;
5385 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005386 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5387 samplingRate,
5388 &updatedSamplingRate,
5389 format,
5390 &updatedFormat,
5391 channelMask,
5392 &updatedChannelMask,
5393 // FIXME ugly cast
5394 (audio_output_flags_t) flags,
5395 false /*exactMatchRequiredForInputFlags*/)) {
5396 firstInexact = profile;
5397 }
5398
Eric Laurente552edb2014-03-10 17:42:56 -07005399 }
5400 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005401 if (firstInexact != nullptr) {
5402 samplingRate = updatedSamplingRate;
5403 format = updatedFormat;
5404 channelMask = updatedChannelMask;
5405 return firstInexact;
5406 }
Eric Laurente552edb2014-03-10 17:42:56 -07005407 return NULL;
5408}
5409
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005410
5411audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005412 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005413{
François Gaffie036e1e92015-03-19 10:16:24 +01005414 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5415 audio_devices_t selectedDeviceFromMix =
5416 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005417
François Gaffie036e1e92015-03-19 10:16:24 +01005418 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5419 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005420 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005421 return getDeviceForInputSource(inputSource);
5422}
5423
5424audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5425{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005426 // Routing
5427 // Scan the whole RouteMap to see if we have an explicit route:
5428 // if the input source in the RouteMap is the same as the argument above,
5429 // and activity count is non-zero and the device in the route descriptor is available
5430 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005431 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5432 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005433 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005434 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005435 return route->mDeviceDescriptor->type();
5436 }
5437 }
5438
5439 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005440}
5441
Eric Laurente0720872014-03-11 09:30:41 -07005442float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005443 int index,
5444 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005445{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005446 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005447
5448 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5449 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5450 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5451 // the ringtone volume
5452 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5453 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5454 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5455 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5456 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5457 }
5458
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005459 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005460 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5461 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005462 switch (stream) {
5463 case AUDIO_STREAM_SYSTEM:
5464 case AUDIO_STREAM_RING:
5465 case AUDIO_STREAM_MUSIC:
5466 case AUDIO_STREAM_ALARM:
5467 case AUDIO_STREAM_NOTIFICATION:
5468 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5469 case AUDIO_STREAM_DTMF:
5470 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005471 int voiceVolumeIndex =
5472 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5473 const float maxVoiceVolDb =
5474 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5475 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005476 if (volumeDB > maxVoiceVolDb) {
5477 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5478 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5479 volumeDB = maxVoiceVolDb;
5480 }
5481 } break;
5482 default:
5483 break;
5484 }
5485 }
5486
Eric Laurente552edb2014-03-10 17:42:56 -07005487 // if a headset is connected, apply the following rules to ring tones and notifications
5488 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005489 // - always attenuate notifications volume by 6dB
5490 // - attenuate ring tones volume by 6dB unless music is not playing and
5491 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005492 // - if music is playing, always limit the volume to current music volume,
5493 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005494 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005495 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5496 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5497 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005498 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005499 AUDIO_DEVICE_OUT_USB_HEADSET |
5500 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005501 ((stream_strategy == STRATEGY_SONIFICATION)
5502 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005503 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005504 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005505 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005506 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005507 // when the phone is ringing we must consider that music could have been paused just before
5508 // by the music application and behave as if music was active if the last music track was
5509 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005510 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005511 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005512 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005513 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005514 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005515 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5516 musicDevice),
5517 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005518 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5519 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005520 if (volumeDB > minVolDB) {
5521 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005522 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005523 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005524 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5525 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5526 // on A2DP, also ensure notification volume is not too low compared to media when
5527 // intended to be played
5528 if ((volumeDB > -96.0f) &&
5529 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5530 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5531 stream, device,
5532 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5533 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5534 }
5535 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005536 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5537 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005538 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005539 }
5540 }
5541
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005542 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005543}
5544
Eric Laurente0720872014-03-11 09:30:41 -07005545status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005546 int index,
5547 const sp<AudioOutputDescriptor>& outputDesc,
5548 audio_devices_t device,
5549 int delayMs,
5550 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005551{
Eric Laurente552edb2014-03-10 17:42:56 -07005552 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005553 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005554 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005555 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005556 return NO_ERROR;
5557 }
François Gaffie2110e042015-03-24 08:41:51 +01005558 audio_policy_forced_cfg_t forceUseForComm =
5559 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005560 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005561 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5562 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005563 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005564 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005565 return INVALID_OPERATION;
5566 }
5567
Eric Laurentc75307b2015-03-17 15:29:32 -07005568 if (device == AUDIO_DEVICE_NONE) {
5569 device = outputDesc->device();
5570 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005571
Eric Laurentffbc80f2015-03-18 18:30:19 -07005572 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005573 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005574 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005575 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005576
Eric Laurentffbc80f2015-03-18 18:30:19 -07005577 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005578
Eric Laurent3b73df72014-03-11 09:06:29 -07005579 if (stream == AUDIO_STREAM_VOICE_CALL ||
5580 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005581 float voiceVolume;
5582 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005583 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005584 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005585 } else {
5586 voiceVolume = 1.0;
5587 }
5588
Eric Laurent18fba842016-03-31 14:41:26 -07005589 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005590 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5591 mLastVoiceVolume = voiceVolume;
5592 }
5593 }
5594
5595 return NO_ERROR;
5596}
5597
Eric Laurentc75307b2015-03-17 15:29:32 -07005598void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5599 audio_devices_t device,
5600 int delayMs,
5601 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005602{
Eric Laurentc75307b2015-03-17 15:29:32 -07005603 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005604
Eric Laurent794fde22016-03-11 09:50:45 -08005605 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005606 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005607 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005608 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005609 device,
5610 delayMs,
5611 force);
5612 }
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 bool on,
5617 const sp<AudioOutputDescriptor>& outputDesc,
5618 int delayMs,
5619 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005620{
Eric Laurent72249d52015-06-08 11:12:15 -07005621 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5622 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005623 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005624 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005626 }
5627 }
5628}
5629
Eric Laurente0720872014-03-11 09:30:41 -07005630void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005631 bool on,
5632 const sp<AudioOutputDescriptor>& outputDesc,
5633 int delayMs,
5634 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005635{
Eric Laurente552edb2014-03-10 17:42:56 -07005636 if (device == AUDIO_DEVICE_NONE) {
5637 device = outputDesc->device();
5638 }
5639
Eric Laurentc75307b2015-03-17 15:29:32 -07005640 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5641 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005642
5643 if (on) {
5644 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005645 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005646 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005647 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005648 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005649 }
5650 }
5651 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5652 outputDesc->mMuteCount[stream]++;
5653 } else {
5654 if (outputDesc->mMuteCount[stream] == 0) {
5655 ALOGV("setStreamMute() unmuting non muted stream!");
5656 return;
5657 }
5658 if (--outputDesc->mMuteCount[stream] == 0) {
5659 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005660 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005661 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005662 device,
5663 delayMs);
5664 }
5665 }
5666}
5667
Eric Laurente0720872014-03-11 09:30:41 -07005668void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005669 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005670{
Eric Laurent87ffa392015-05-22 10:32:38 -07005671 if(!hasPrimaryOutput()) {
5672 return;
5673 }
5674
Eric Laurente552edb2014-03-10 17:42:56 -07005675 // if the stream pertains to sonification strategy and we are in call we must
5676 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5677 // in the device used for phone strategy and play the tone if the selected device does not
5678 // interfere with the device used for phone strategy
5679 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5680 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005681 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005682 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5683 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005684 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005685 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5686 stream, starting, outputDesc->mDevice, stateChange);
5687 if (outputDesc->mRefCount[stream]) {
5688 int muteCount = 1;
5689 if (stateChange) {
5690 muteCount = outputDesc->mRefCount[stream];
5691 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005692 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005693 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5694 for (int i = 0; i < muteCount; i++) {
5695 setStreamMute(stream, starting, mPrimaryOutput);
5696 }
5697 } else {
5698 ALOGV("handleIncallSonification() high visibility");
5699 if (outputDesc->device() &
5700 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5701 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5702 for (int i = 0; i < muteCount; i++) {
5703 setStreamMute(stream, starting, mPrimaryOutput);
5704 }
5705 }
5706 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005707 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5708 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005709 } else {
5710 mpClientInterface->stopTone();
5711 }
5712 }
5713 }
5714 }
5715}
5716
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005717audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5718{
5719 // flags to stream type mapping
5720 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5721 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5722 }
5723 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5724 return AUDIO_STREAM_BLUETOOTH_SCO;
5725 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005726 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5727 return AUDIO_STREAM_TTS;
5728 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005729
5730 // usage to stream type mapping
5731 switch (attr->usage) {
5732 case AUDIO_USAGE_MEDIA:
5733 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005734 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005735 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5736 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005737 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5738 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005739 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5740 return AUDIO_STREAM_SYSTEM;
5741 case AUDIO_USAGE_VOICE_COMMUNICATION:
5742 return AUDIO_STREAM_VOICE_CALL;
5743
5744 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5745 return AUDIO_STREAM_DTMF;
5746
5747 case AUDIO_USAGE_ALARM:
5748 return AUDIO_STREAM_ALARM;
5749 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5750 return AUDIO_STREAM_RING;
5751
5752 case AUDIO_USAGE_NOTIFICATION:
5753 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5754 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5755 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5756 case AUDIO_USAGE_NOTIFICATION_EVENT:
5757 return AUDIO_STREAM_NOTIFICATION;
5758
5759 case AUDIO_USAGE_UNKNOWN:
5760 default:
5761 return AUDIO_STREAM_MUSIC;
5762 }
5763}
Eric Laurente83b55d2014-11-14 10:06:21 -08005764
François Gaffie53615e22015-03-19 09:24:12 +01005765bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5766{
Eric Laurente83b55d2014-11-14 10:06:21 -08005767 // has flags that map to a strategy?
5768 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5769 return true;
5770 }
5771
5772 // has known usage?
5773 switch (paa->usage) {
5774 case AUDIO_USAGE_UNKNOWN:
5775 case AUDIO_USAGE_MEDIA:
5776 case AUDIO_USAGE_VOICE_COMMUNICATION:
5777 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5778 case AUDIO_USAGE_ALARM:
5779 case AUDIO_USAGE_NOTIFICATION:
5780 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5781 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5782 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5783 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5784 case AUDIO_USAGE_NOTIFICATION_EVENT:
5785 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5786 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5787 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5788 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005789 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005790 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005791 break;
5792 default:
5793 return false;
5794 }
5795 return true;
5796}
5797
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005798bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005799 routing_strategy strategy, uint32_t inPastMs,
5800 nsecs_t sysTime) const
5801{
5802 if ((sysTime == 0) && (inPastMs != 0)) {
5803 sysTime = systemTime();
5804 }
Eric Laurent794fde22016-03-11 09:50:45 -08005805 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005806 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5807 (NUM_STRATEGIES == strategy)) &&
5808 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5809 return true;
5810 }
5811 }
5812 return false;
5813}
5814
François Gaffie2110e042015-03-24 08:41:51 +01005815audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5816{
5817 return mEngine->getForceUse(usage);
5818}
5819
5820bool AudioPolicyManager::isInCall()
5821{
5822 return isStateInCall(mEngine->getPhoneState());
5823}
5824
5825bool AudioPolicyManager::isStateInCall(int state)
5826{
5827 return is_state_in_call(state);
5828}
5829
Eric Laurentd60560a2015-04-10 11:31:20 -07005830void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5831{
5832 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5833 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5834 if (sourceDesc->mDevice->equals(deviceDesc)) {
5835 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5836 stopAudioSource(sourceDesc->getHandle());
5837 }
5838 }
5839
5840 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5841 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5842 bool release = false;
5843 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5844 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5845 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5846 source->ext.device.type == deviceDesc->type()) {
5847 release = true;
5848 }
5849 }
5850 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5851 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5852 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5853 sink->ext.device.type == deviceDesc->type()) {
5854 release = true;
5855 }
5856 }
5857 if (release) {
5858 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5859 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5860 }
5861 }
5862}
5863
Phil Burk09bc4612016-02-24 15:58:15 -08005864// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005865void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5866 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005867 // TODO Set this based on Config properties.
5868 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005869
5870 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5871 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005872 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005873
jiabin81772902018-04-02 17:52:27 -07005874 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5875 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5876 formats.clear();
5877 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5878 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005879 }
jiabin81772902018-04-02 17:52:27 -07005880 // Always enable IEC61937 when in MANUAL mode.
5881 formats.add(AUDIO_FORMAT_IEC61937);
5882 } else { // NEVER, AUTO or ALWAYS
5883 // Analyze original support for various formats.
5884 bool supportsAC3 = false;
5885 bool supportsOtherSurround = false;
5886 bool supportsIEC61937 = false;
5887 mSurroundFormats.clear();
5888 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5889 audio_format_t format = formats[formatIndex];
5890 switch (format) {
5891 case AUDIO_FORMAT_AC3:
5892 supportsAC3 = true;
5893 break;
5894 case AUDIO_FORMAT_E_AC3:
5895 case AUDIO_FORMAT_DTS:
5896 case AUDIO_FORMAT_DTS_HD:
5897 // If ALWAYS, remove all other surround formats here
5898 // since we will add them later.
5899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5900 formats.removeAt(formatIndex);
5901 formatIndex--;
5902 }
5903 supportsOtherSurround = true;
5904 break;
5905 case AUDIO_FORMAT_IEC61937:
5906 supportsIEC61937 = true;
5907 break;
5908 default:
5909 break;
5910 }
5911 }
Phil Burk09bc4612016-02-24 15:58:15 -08005912
jiabin81772902018-04-02 17:52:27 -07005913 // Modify formats based on surround preferences.
5914 // If NEVER, remove support for surround formats.
5915 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5916 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5917 // Remove surround sound related formats.
5918 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5919 audio_format_t format = formats[formatIndex];
5920 switch(format) {
5921 case AUDIO_FORMAT_AC3:
5922 case AUDIO_FORMAT_E_AC3:
5923 case AUDIO_FORMAT_DTS:
5924 case AUDIO_FORMAT_DTS_HD:
5925 case AUDIO_FORMAT_IEC61937:
5926 formats.removeAt(formatIndex);
5927 break;
5928 default:
5929 formatIndex++; // keep it
5930 break;
5931 }
5932 }
5933 supportsAC3 = false;
5934 supportsOtherSurround = false;
5935 supportsIEC61937 = false;
5936 }
5937 } else { // AUTO or ALWAYS
5938 // Most TVs support AC3 even if they do not report it in the EDID.
5939 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5940 && !supportsAC3) {
5941 formats.add(AUDIO_FORMAT_AC3);
5942 supportsAC3 = true;
5943 }
5944
5945 // If ALWAYS, add support for raw surround formats if all are missing.
5946 // This assumes that if any of these formats are reported by the HAL
5947 // then the report is valid and should not be modified.
5948 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5949 formats.add(AUDIO_FORMAT_E_AC3);
5950 formats.add(AUDIO_FORMAT_DTS);
5951 formats.add(AUDIO_FORMAT_DTS_HD);
5952 supportsOtherSurround = true;
5953 }
5954
5955 // Add support for IEC61937 if any raw surround supported.
5956 // The HAL could do this but add it here, just in case.
5957 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5958 formats.add(AUDIO_FORMAT_IEC61937);
5959 supportsIEC61937 = true;
5960 }
5961
5962 // Add reported surround sound formats to enabled surround formats.
5963 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005964 audio_format_t format = formats[formatIndex];
5965 switch(format) {
5966 case AUDIO_FORMAT_AC3:
5967 case AUDIO_FORMAT_E_AC3:
5968 case AUDIO_FORMAT_DTS:
5969 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005970 case AUDIO_FORMAT_AAC_LC:
5971 case AUDIO_FORMAT_DOLBY_TRUEHD:
5972 case AUDIO_FORMAT_E_AC3_JOC:
5973 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005974 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005975 break;
5976 }
Phil Burk09bc4612016-02-24 15:58:15 -08005977 }
Phil Burk07ac1142016-03-25 13:39:29 -07005978 }
Phil Burk09bc4612016-02-24 15:58:15 -08005979 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005980}
5981
5982// Modify the list of channel masks supported.
5983void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5984 ChannelsVector &channelMasks = *channelMasksPtr;
5985 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5986 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5987
5988 // If NEVER, then remove support for channelMasks > stereo.
5989 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5990 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5991 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5992 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5993 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5994 channelMasks.removeAt(maskIndex);
5995 } else {
5996 maskIndex++;
5997 }
5998 }
jiabin81772902018-04-02 17:52:27 -07005999 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6000 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6001 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006002 bool supports5dot1 = false;
6003 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006004 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006005 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6006 supports5dot1 = true;
6007 break;
6008 }
6009 }
6010 // If not then add 5.1 support.
6011 if (!supports5dot1) {
6012 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6013 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6014 }
Phil Burk09bc4612016-02-24 15:58:15 -08006015 }
6016}
6017
Phil Burk00eeb322016-03-31 12:41:00 -07006018void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6019 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006020 AudioProfileVector &profiles)
6021{
6022 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006023
François Gaffie112b0af2015-11-19 16:13:25 +01006024 // Format MUST be checked first to update the list of AudioProfile
6025 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006026 reply = mpClientInterface->getParameters(
6027 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006028 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006029 AudioParameter repliedParameters(reply);
6030 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006031 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006032 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6033 return;
6034 }
Phil Burk09bc4612016-02-24 15:58:15 -08006035 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006036 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006037 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006038 }
Phil Burk09bc4612016-02-24 15:58:15 -08006039 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006040 }
François Gaffie112b0af2015-11-19 16:13:25 +01006041
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006042 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006043 ChannelsVector channelMasks;
6044 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006045 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006046 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006047
6048 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006049 reply = mpClientInterface->getParameters(
6050 ioHandle,
6051 requestedParameters.toString() + ";" +
6052 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006053 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006054 AudioParameter repliedParameters(reply);
6055 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006056 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006057 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006058 }
6059 }
6060 if (profiles.hasDynamicChannelsFor(format)) {
6061 reply = mpClientInterface->getParameters(ioHandle,
6062 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006063 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006064 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006065 AudioParameter repliedParameters(reply);
6066 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006067 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006068 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006069 if (device == AUDIO_DEVICE_OUT_HDMI) {
6070 filterSurroundChannelMasks(&channelMasks);
6071 }
François Gaffie112b0af2015-11-19 16:13:25 +01006072 }
6073 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006074 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006075 }
6076}
Eric Laurentd60560a2015-04-10 11:31:20 -07006077
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006078} // namespace android