blob: dcd1f3bfd94c8026668312948b323ac01589ed02 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
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;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431}
432
Eric Laurentdc462862016-07-19 12:29:53 -0700433uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434{
435 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700436 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437
Andy Hunga76c7de2016-12-13 19:14:31 -0800438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700439 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 createTxPatch = true;
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 return muteWaitMs;
475}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
479 struct audio_patch patch;
480 patch.num_sources = 1;
481 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700482
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800483 sp<DeviceDescriptor> txSourceDeviceDesc;
484 if (isRx) {
485 fillAudioPortConfigForDevice(mAvailableOutputDevices, device, &patch.sinks[0]);
486 fillAudioPortConfigForDevice(
487 mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX, &patch.sources[0]);
488 } else {
489 txSourceDeviceDesc = fillAudioPortConfigForDevice(
490 mAvailableInputDevices, device, &patch.sources[0]);
491 fillAudioPortConfigForDevice(
492 mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX, &patch.sinks[0]);
493 }
494
495 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
496 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
497 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
498 // request to reuse existing output stream if one is already opened to reach the target device
499 if (output != AUDIO_IO_HANDLE_NONE) {
500 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
501 ALOG_ASSERT(!outputDesc->isDuplicated(),
502 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
503 outputDesc->toAudioPortConfig(&patch.sources[1]);
504 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
505 patch.num_sources = 2;
506 }
507
508 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700509 // terminate active capture if on the same HW module as the call TX source device
510 // FIXME: would be better to refine to only inputs whose profile connects to the
511 // call TX device but this information is not in the audio patch and logic here must be
512 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800513 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800514 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
515 AudioSessionCollection activeSessions =
516 activeDesc->getAudioSessions(true /*activeOnly*/);
517 for (size_t j = 0; j < activeSessions.size(); j++) {
518 audio_session_t activeSession = activeSessions.keyAt(j);
519 stopInput(activeDesc->mIoHandle, activeSession);
520 releaseInput(activeDesc->mIoHandle, activeSession);
521 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700522 }
523 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700524 }
Eric Laurentdc462862016-07-19 12:29:53 -0700525
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800526 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
527 status_t status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
528 ALOGW_IF(status != NO_ERROR,
529 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
530 sp<AudioPatch> audioPatch;
531 if (status == NO_ERROR) {
532 audioPatch = new AudioPatch(&patch, mUidCached);
533 audioPatch->mAfPatchHandle = afPatchHandle;
534 audioPatch->mUid = mUidCached;
535 }
536 return audioPatch;
537}
538
539sp<DeviceDescriptor> AudioPolicyManager::fillAudioPortConfigForDevice(
540 const DeviceVector& devices, audio_devices_t device, audio_port_config *config) {
541 DeviceVector deviceList = devices.getDevicesFromType(device);
542 ALOG_ASSERT(!deviceList.isEmpty(),
543 "%s() selected device type %#x is not in devices list", __func__, device);
544 sp<DeviceDescriptor> deviceDesc = deviceList.itemAt(0);
545 deviceDesc->toAudioPortConfig(config);
546 return deviceDesc;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700547}
548
Eric Laurente0720872014-03-11 09:30:41 -0700549void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700550{
551 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100552 // store previous phone state for management of sonification strategy below
553 int oldState = mEngine->getPhoneState();
554
555 if (mEngine->setPhoneState(state) != NO_ERROR) {
556 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700557 return;
558 }
François Gaffie2110e042015-03-24 08:41:51 +0100559 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700560 // if leaving call state, handle special case of active streams
561 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700562 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700563 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800564 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700565 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700566 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800567
Eric Laurent63dea1d2015-07-02 17:10:28 -0700568 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800569 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700570 }
571
François Gaffie2110e042015-03-24 08:41:51 +0100572 /**
573 * Switching to or from incall state or switching between telephony and VoIP lead to force
574 * routing command.
575 */
576 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
577 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700578
579 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700580 checkA2dpSuspend();
581 checkOutputForAllStrategies();
582 updateDevicesAndOutputs();
583
Eric Laurente552edb2014-03-10 17:42:56 -0700584 int delayMs = 0;
585 if (isStateInCall(state)) {
586 nsecs_t sysTime = systemTime();
587 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700589 // mute media and sonification strategies and delay device switch by the largest
590 // latency of any output where either strategy is active.
591 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100592 if ((isStrategyActive(desc, STRATEGY_MEDIA,
593 SONIFICATION_HEADSET_MUSIC_DELAY,
594 sysTime) ||
595 isStrategyActive(desc, STRATEGY_SONIFICATION,
596 SONIFICATION_HEADSET_MUSIC_DELAY,
597 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700598 (delayMs < (int)desc->latency()*2)) {
599 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700600 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700601 setStrategyMute(STRATEGY_MEDIA, true, desc);
602 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700603 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700604 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
605 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700606 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
607 }
608 }
609
Eric Laurent87ffa392015-05-22 10:32:38 -0700610 if (hasPrimaryOutput()) {
611 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
612 // the device returned is not necessarily reachable via this output
613 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
614 // force routing command to audio hardware when ending call
615 // even if no device change is needed
616 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
617 rxDevice = mPrimaryOutput->device();
618 }
Eric Laurente552edb2014-03-10 17:42:56 -0700619
Eric Laurent87ffa392015-05-22 10:32:38 -0700620 if (state == AUDIO_MODE_IN_CALL) {
621 updateCallRouting(rxDevice, delayMs);
622 } else if (oldState == AUDIO_MODE_IN_CALL) {
623 if (mCallRxPatch != 0) {
624 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
625 mCallRxPatch.clear();
626 }
627 if (mCallTxPatch != 0) {
628 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
629 mCallTxPatch.clear();
630 }
631 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
632 } else {
633 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700634 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700635 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700636
637 // reevaluate routing on all outputs in case tracks have been started during the call
638 for (size_t i = 0; i < mOutputs.size(); i++) {
639 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
640 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
641 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800642 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700643 }
644 }
645
Eric Laurente552edb2014-03-10 17:42:56 -0700646 // if entering in call state, handle special case of active streams
647 // pertaining to sonification strategy see handleIncallSonification()
648 if (isStateInCall(state)) {
649 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800650 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700651 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700652 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700653
654 // force reevaluating accessibility routing when call starts
655 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700656 }
657
658 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700659 if (state == AUDIO_MODE_RINGTONE &&
660 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700661 mLimitRingtoneVolume = true;
662 } else {
663 mLimitRingtoneVolume = false;
664 }
665}
666
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700667audio_mode_t AudioPolicyManager::getPhoneState() {
668 return mEngine->getPhoneState();
669}
670
Eric Laurente0720872014-03-11 09:30:41 -0700671void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700672 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700673{
François Gaffie2110e042015-03-24 08:41:51 +0100674 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700675 if (config == mEngine->getForceUse(usage)) {
676 return;
677 }
Eric Laurente552edb2014-03-10 17:42:56 -0700678
François Gaffie2110e042015-03-24 08:41:51 +0100679 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
680 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
681 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700682 }
François Gaffie2110e042015-03-24 08:41:51 +0100683 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
684 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
685 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700686
687 // check for device and output changes triggered by new force usage
688 checkA2dpSuspend();
689 checkOutputForAllStrategies();
690 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800691
Eric Laurentdc462862016-07-19 12:29:53 -0700692 //FIXME: workaround for truncated touch sounds
693 // to be removed when the problem is handled by system UI
694 uint32_t delayMs = 0;
695 uint32_t waitMs = 0;
696 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
697 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
698 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700699 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700701 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700702 }
Eric Laurente552edb2014-03-10 17:42:56 -0700703 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700704 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
705 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
706 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700707 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
708 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 }
Eric Laurente552edb2014-03-10 17:42:56 -0700710 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700711 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700712 }
713 }
714
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800715 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800716 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700717 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800718 if (activeDesc->mProfile->getSupportedDevices().types() &
719 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
720 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700721 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800722 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700723 }
Eric Laurente552edb2014-03-10 17:42:56 -0700724 }
Eric Laurente552edb2014-03-10 17:42:56 -0700725}
726
Eric Laurente0720872014-03-11 09:30:41 -0700727void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700728{
729 ALOGV("setSystemProperty() property %s, value %s", property, value);
730}
731
732// Find a direct output profile compatible with the parameters passed, even if the input flags do
733// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800734sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700735 audio_devices_t device,
736 uint32_t samplingRate,
737 audio_format_t format,
738 audio_channel_mask_t channelMask,
739 audio_output_flags_t flags)
740{
Eric Laurent861a6282015-05-18 15:40:16 -0700741 // only retain flags that will drive the direct output profile selection
742 // if explicitly requested
743 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700744 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
745 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700746 flags =
747 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
748
749 sp<IOProfile> profile;
750
Mikhail Naganovd4120142017-12-06 15:49:22 -0800751 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800752 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700753 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700754 samplingRate, NULL /*updatedSamplingRate*/,
755 format, NULL /*updatedFormat*/,
756 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700757 flags)) {
758 continue;
759 }
760 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100761 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700762 continue;
763 }
764 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100765 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700766 continue;
767 }
768 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100769 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700770 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700771 }
Eric Laurente552edb2014-03-10 17:42:56 -0700772 }
773 }
Eric Laurent861a6282015-05-18 15:40:16 -0700774 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700775}
776
Eric Laurentf4e63452017-11-06 19:31:46 +0000777audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700778{
Eric Laurent3b73df72014-03-11 09:06:29 -0700779 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700780 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800781
782 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
783 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
784 // format, flags, etc. This may result in some discrepancy for functions that utilize
785 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
786 // and AudioSystem::getOutputSamplingRate().
787
Eric Laurentf4e63452017-11-06 19:31:46 +0000788 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
789 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700790
Eric Laurentf4e63452017-11-06 19:31:46 +0000791 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
792 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700793}
794
Eric Laurente83b55d2014-11-14 10:06:21 -0800795status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
796 audio_io_handle_t *output,
797 audio_session_t session,
798 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700799 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800800 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200801 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700802 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800803 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700804{
Eric Laurente83b55d2014-11-14 10:06:21 -0800805 audio_attributes_t attributes;
806 if (attr != NULL) {
807 if (!isValidAttributes(attr)) {
808 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
809 attr->usage, attr->content_type, attr->flags,
810 attr->tags);
811 return BAD_VALUE;
812 }
813 attributes = *attr;
814 } else {
815 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
816 ALOGE("getOutputForAttr(): invalid stream type");
817 return BAD_VALUE;
818 }
819 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700820 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800821
822 // TODO: check for existing client for this port ID
823 if (*portId == AUDIO_PORT_HANDLE_NONE) {
824 *portId = AudioPort::getNextUniqueId();
825 }
826
Eric Laurentc75307b2015-03-17 15:29:32 -0700827 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800828 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100829 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800830 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100831 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800832 }
François Gaffie036e1e92015-03-19 10:16:24 +0100833 *stream = streamTypefromAttributesInt(&attributes);
834 *output = desc->mIoHandle;
835 ALOGV("getOutputForAttr() returns output %d", *output);
836 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800837 }
838 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
839 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
840 return BAD_VALUE;
841 }
842
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700843 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
844 " session %d selectedDeviceId %d",
845 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700846 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700847
848 *stream = streamTypefromAttributesInt(&attributes);
849
850 // Explicit routing?
851 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700852 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800853 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700854 }
855 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700856
Eric Laurente83b55d2014-11-14 10:06:21 -0800857 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700858 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700859
Eric Laurente83b55d2014-11-14 10:06:21 -0800860 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200861 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700862 }
863
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800864 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
865 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200866 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700867
Andy Hungc88b0642018-04-27 15:42:35 -0700868 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800869 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700870 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800871 return INVALID_OPERATION;
872 }
Paul McLeanaa981192015-03-21 09:55:15 -0700873
Eric Laurent2ac76942017-06-22 17:17:09 -0700874 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
875 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
876 : AUDIO_PORT_HANDLE_NONE;
877
878 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
879
Eric Laurente83b55d2014-11-14 10:06:21 -0800880 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881}
882
883audio_io_handle_t AudioPolicyManager::getOutputForDevice(
884 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800885 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800887 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200888 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700889{
Andy Hungc88b0642018-04-27 15:42:35 -0700890 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700891 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700892
Eric Laurente552edb2014-03-10 17:42:56 -0700893 // open a direct output if required by specified parameters
894 //force direct flag if offload flag is set: offloading implies a direct output stream
895 // and all common behaviors are driven by checking only the direct flag
896 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200897 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
898 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700899 }
Nadav Bar766fb022018-01-07 12:18:03 +0200900 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
901 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700902 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800903 // only allow deep buffering for music stream type
904 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200905 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700906 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200907 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700908 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
909 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200910 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800911 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700912 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200913 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700914 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800915 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200916 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700917 AUDIO_OUTPUT_FLAG_DIRECT);
918 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200919 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
920 stream == AUDIO_STREAM_MUSIC &&
921 audio_is_linear_pcm(config->format) &&
922 isInCall()) {
923 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700924 }
Eric Laurente552edb2014-03-10 17:42:56 -0700925
Nadav Bar766fb022018-01-07 12:18:03 +0200926
Eric Laurentb732cf52014-09-24 19:08:21 -0700927 sp<IOProfile> profile;
928
929 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700930 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200931 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800932 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
933 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700934 goto non_direct_output;
935 }
936
Andy Hung2ddee192015-12-18 17:34:44 -0800937 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
938 // This prevents creating an offloaded track and tearing it down immediately after start
939 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // FIXME: We should check the audio session here but we do not have it in this context.
941 // This may prevent offloading in rare situations where effects are left active by apps
942 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700943
Nadav Bar766fb022018-01-07 12:18:03 +0200944 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800945 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700946 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800947 config->sample_rate,
948 config->format,
949 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200950 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700951 }
952
Eric Laurent1c333e22014-05-20 10:48:17 -0700953 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700954 // exclusive outputs for MMAP and Offload are enforced by different session ids.
955 for (size_t i = 0; i < mOutputs.size(); i++) {
956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
957 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
958 // reuse direct output if currently open by the same client
959 // and configured with same parameters
960 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700961 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700962 (config->channel_mask == desc->mChannelMask) &&
963 (session == desc->mDirectClientSession)) {
964 desc->mDirectOpenCount++;
965 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
966 mOutputs.keyAt(i), session);
967 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700968 }
969 }
970 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800971
972 if (!profile->canOpenNewIo()) {
973 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
Eric Laurent861a6282015-05-18 15:40:16 -0700975
Eric Laurent3974e3b2017-12-07 17:58:43 -0800976 sp<SwAudioOutputDescriptor> outputDesc =
977 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800978
979 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
980 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
981 : String8("");
982
Nadav Bar766fb022018-01-07 12:18:03 +0200983 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700984
985 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700986 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800987 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700988 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800989 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
990 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
991 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
992 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
993 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700994 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800995 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700996 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800997 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800998 if (audio_is_linear_pcm(config->format) &&
999 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001000 goto non_direct_output;
1001 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001002 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001003 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001004 outputDesc->mRefCount[stream] = 0;
1005 outputDesc->mStopTime[stream] = 0;
1006 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001007 outputDesc->mDirectClientSession = session;
1008
Eric Laurente552edb2014-03-10 17:42:56 -07001009 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001010 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001011 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001012 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001013 return output;
1014 }
1015
Eric Laurentb732cf52014-09-24 19:08:21 -07001016non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001017
1018 // A request for HW A/V sync cannot fallback to a mixed output because time
1019 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001020 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001021 return AUDIO_IO_HANDLE_NONE;
1022 }
1023
Eric Laurente552edb2014-03-10 17:42:56 -07001024 // ignoring channel mask due to downmix capability in mixer
1025
1026 // open a non direct output
1027
1028 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001029 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001030 // get which output is suitable for the specified stream. The actual
1031 // routing change will happen when startOutput() will be called
1032 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1033
Eric Laurent8838a382014-09-08 16:44:28 -07001034 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001035 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1036 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001037 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001038 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001039 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001040 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001041
Eric Laurente552edb2014-03-10 17:42:56 -07001042 return output;
1043}
1044
Eric Laurente0720872014-03-11 09:30:41 -07001045audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001046 audio_output_flags_t flags,
1047 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001048{
1049 // select one output among several that provide a path to a particular device or set of
1050 // devices (the list was previously build by getOutputsForDevice()).
1051 // The priority is as follows:
1052 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001053 // 2: the output with the bit depth the closest to the requested one
1054 // 3: the primary output
1055 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001056
1057 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001058 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001059 }
1060 if (outputs.size() == 1) {
1061 return outputs[0];
1062 }
1063
1064 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001065 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1066 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1067 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001068 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1069 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001070
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001071 for (audio_io_handle_t output : outputs) {
1072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001073 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001074 // if a valid format is specified, skip output if not compatible
1075 if (format != AUDIO_FORMAT_INVALID) {
1076 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001077 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001078 continue;
1079 }
1080 } else if (!audio_is_linear_pcm(format)) {
1081 continue;
1082 }
Eric Laurente6930022016-02-11 10:20:40 -08001083 if (AudioPort::isBetterFormatMatch(
1084 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001085 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001086 bestFormat = outputDesc->mFormat;
1087 }
Eric Laurent8838a382014-09-08 16:44:28 -07001088 }
1089
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001090 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001091 if (commonFlags >= maxCommonFlags) {
1092 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001093 if (format != AUDIO_FORMAT_INVALID
1094 && AudioPort::isBetterFormatMatch(
1095 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001096 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001097 bestFormatForFlags = outputDesc->mFormat;
1098 }
1099 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001100 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001101 maxCommonFlags = commonFlags;
1102 bestFormatForFlags = outputDesc->mFormat;
1103 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001104 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001105 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001106 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001107 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001108 }
1109 }
1110 }
1111
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001112 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001113 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001114 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001115 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001116 return outputForFormat;
1117 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001118 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001119 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001120 }
1121
1122 return outputs[0];
1123}
1124
Eric Laurente0720872014-03-11 09:30:41 -07001125status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001126 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001127 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001128{
Paul McLeanaa981192015-03-21 09:55:15 -07001129 ALOGV("startOutput() output %d, stream %d, session %d",
1130 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001131 ssize_t index = mOutputs.indexOfKey(output);
1132 if (index < 0) {
1133 ALOGW("startOutput() unknown output %d", output);
1134 return BAD_VALUE;
1135 }
1136
Eric Laurentc75307b2015-03-17 15:29:32 -07001137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1138
Eric Laurent733ce942017-12-07 12:18:25 -08001139 status_t status = outputDesc->start();
1140 if (status != NO_ERROR) {
1141 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001142 }
1143
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001144 // Routing?
1145 mOutputRoutes.incRouteActivity(session);
1146
Eric Laurentc75307b2015-03-17 15:29:32 -07001147 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001148 AudioMix *policyMix = NULL;
1149 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001150 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001151 policyMix = outputDesc->mPolicyMix;
1152 address = policyMix->mDeviceAddress.string();
1153 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1154 newDevice = policyMix->mDeviceType;
1155 } else {
1156 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1157 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001158 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001159 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001160 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001161 } else {
1162 newDevice = AUDIO_DEVICE_NONE;
1163 }
1164
1165 uint32_t delayMs = 0;
1166
Eric Laurent733ce942017-12-07 12:18:25 -08001167 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001168
1169 if (status != NO_ERROR) {
1170 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001171 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001172 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 }
1174 // Automatically enable the remote submix input when output is started on a re routing mix
1175 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001176 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1177 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001178 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1179 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001180 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001181 "remote-submix");
1182 }
1183
1184 if (delayMs != 0) {
1185 usleep(delayMs * 1000);
1186 }
1187
1188 return status;
1189}
1190
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001191status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001192 audio_stream_type_t stream,
1193 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001194 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 uint32_t *delayMs)
1196{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001197 // cannot start playback of STREAM_TTS if any other output is being used
1198 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001199
1200 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001201 if (stream == AUDIO_STREAM_TTS) {
1202 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001203 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001204 return INVALID_OPERATION;
1205 } else {
1206 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1207 }
1208 } else {
1209 // some playback other than beacon starts
1210 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1211 }
1212
Eric Laurent77305a62016-07-25 16:39:22 -07001213 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001214 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001215 bool force = !outputDesc->isActive() &&
1216 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001217
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001218 // requiresMuteCheck is false when we can bypass mute strategy.
1219 // It covers a common case when there is no materially active audio
1220 // and muting would result in unnecessary delay and dropped audio.
1221 const uint32_t outputLatencyMs = outputDesc->latency();
1222 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1223
Eric Laurente552edb2014-03-10 17:42:56 -07001224 // increment usage count for this stream on the requested output:
1225 // NOTE that the usage count is the same for duplicated output and hardware output which is
1226 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1227 outputDesc->changeRefCount(stream, 1);
1228
Eric Laurent36829f92017-04-07 19:04:42 -07001229 if (stream == AUDIO_STREAM_MUSIC) {
1230 selectOutputForMusicEffects();
1231 }
1232
Eric Laurent493404d2015-04-21 15:07:36 -07001233 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001234 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001235 if (device == AUDIO_DEVICE_NONE) {
1236 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001237 }
Eric Laurent36829f92017-04-07 19:04:42 -07001238
Eric Laurente552edb2014-03-10 17:42:56 -07001239 routing_strategy strategy = getStrategy(stream);
1240 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001241 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1242 (beaconMuteLatency > 0);
1243 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001244 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001245 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001246 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001247 // An output has a shared device if
1248 // - managed by the same hw module
1249 // - supports the currently selected device
1250 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1251 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1252
Eric Laurent77305a62016-07-25 16:39:22 -07001253 // force a device change if any other output is:
1254 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001255 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001256 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001257 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001258 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001259 // change the device currently selected by the other output.
1260 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001261 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001262 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001263 force = true;
1264 }
1265 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001266 // a notification so that audio focus effect can propagate, or that a mute/unmute
1267 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001268 const uint32_t latencyMs = desc->latency();
1269 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1270
1271 if (shouldWait && isActive && (waitMs < latencyMs)) {
1272 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001273 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001274
1275 // Require mute check if another output is on a shared device
1276 // and currently active to have proper drain and avoid pops.
1277 // Note restoring AudioTracks onto this output needs to invoke
1278 // a volume ramp if there is no mute.
1279 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001280 }
1281 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001282
1283 const uint32_t muteWaitMs =
1284 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001285
1286 // handle special case for sonification while in call
1287 if (isInCall()) {
1288 handleIncallSonification(stream, true, false);
1289 }
1290
1291 // apply volume rules for current stream and device if necessary
1292 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001293 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001294 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001295 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001296
1297 // update the outputs if starting an output with a stream that can affect notification
1298 // routing
1299 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001300
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001301 // force reevaluating accessibility routing when ringtone or alarm starts
1302 if (strategy == STRATEGY_SONIFICATION) {
1303 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1304 }
Eric Laurentdc462862016-07-19 12:29:53 -07001305
1306 if (waitMs > muteWaitMs) {
1307 *delayMs = waitMs - muteWaitMs;
1308 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001309
1310 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1311 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1312 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1313 // change occurs after the MixerThread starts and causes a stream volume
1314 // glitch.
1315 //
1316 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001317 }
Eric Laurentdc462862016-07-19 12:29:53 -07001318
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001319 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1320 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1321 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1322 }
1323
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001324 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1325 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1326 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1327 }
1328
Eric Laurente552edb2014-03-10 17:42:56 -07001329 return NO_ERROR;
1330}
1331
1332
Eric Laurente0720872014-03-11 09:30:41 -07001333status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001334 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001335 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001336{
1337 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1338 ssize_t index = mOutputs.indexOfKey(output);
1339 if (index < 0) {
1340 ALOGW("stopOutput() unknown output %d", output);
1341 return BAD_VALUE;
1342 }
1343
Eric Laurentc75307b2015-03-17 15:29:32 -07001344 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001345
Eric Laurentc75307b2015-03-17 15:29:32 -07001346 if (outputDesc->mRefCount[stream] == 1) {
1347 // Automatically disable the remote submix input when output is stopped on a
1348 // re routing mix of type MIX_TYPE_RECORDERS
1349 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1350 outputDesc->mPolicyMix != NULL &&
1351 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1352 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1353 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001354 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001355 "remote-submix");
1356 }
1357 }
1358
1359 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001360 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001361 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001362 int activityCount = mOutputRoutes.decRouteActivity(session);
1363 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1364
1365 if (forceDeviceUpdate) {
1366 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1367 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001368 }
1369
Eric Laurent3974e3b2017-12-07 17:58:43 -08001370 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1371
Eric Laurent733ce942017-12-07 12:18:25 -08001372 if (status == NO_ERROR ) {
1373 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001374 }
1375 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001376}
1377
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001378status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001379 audio_stream_type_t stream,
1380 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001381{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001382 // always handle stream stop, check which stream type is stopping
1383 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1384
Eric Laurente552edb2014-03-10 17:42:56 -07001385 // handle special case for sonification while in call
1386 if (isInCall()) {
1387 handleIncallSonification(stream, false, false);
1388 }
1389
1390 if (outputDesc->mRefCount[stream] > 0) {
1391 // decrement usage count of this stream on the output
1392 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001393
Eric Laurente552edb2014-03-10 17:42:56 -07001394 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001395 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001396 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001397 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001398 // delay the device switch by twice the latency because stopOutput() is executed when
1399 // the track stop() command is received and at that time the audio track buffer can
1400 // still contain data that needs to be drained. The latency only covers the audio HAL
1401 // and kernel buffers. Also the latency does not always include additional delay in the
1402 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001403 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001404
1405 // force restoring the device selection on other active outputs if it differs from the
1406 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001407 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001408 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001409 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001410 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001411 desc->isActive() &&
1412 outputDesc->sharesHwModuleWith(desc) &&
1413 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001414 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1415 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001416 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001417 newDevice2,
1418 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001419 delayMs);
1420 // re-apply device specific volume if not done by setOutputDevice()
1421 if (!force) {
1422 applyStreamVolumes(desc, newDevice2, delayMs);
1423 }
Eric Laurente552edb2014-03-10 17:42:56 -07001424 }
1425 }
1426 // update the outputs if stopping one with a stream that can affect notification routing
1427 handleNotificationRoutingForStream(stream);
1428 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001429
1430 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1431 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1432 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1433 }
1434
Eric Laurent36829f92017-04-07 19:04:42 -07001435 if (stream == AUDIO_STREAM_MUSIC) {
1436 selectOutputForMusicEffects();
1437 }
Eric Laurente552edb2014-03-10 17:42:56 -07001438 return NO_ERROR;
1439 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001440 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001441 return INVALID_OPERATION;
1442 }
1443}
1444
Eric Laurente83b55d2014-11-14 10:06:21 -08001445void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001446 audio_stream_type_t stream __unused,
1447 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001448{
1449 ALOGV("releaseOutput() %d", output);
1450 ssize_t index = mOutputs.indexOfKey(output);
1451 if (index < 0) {
1452 ALOGW("releaseOutput() releasing unknown output %d", output);
1453 return;
1454 }
1455
Paul McLeanaa981192015-03-21 09:55:15 -07001456 // Routing
1457 mOutputRoutes.removeRoute(session);
1458
Eric Laurentc75307b2015-03-17 15:29:32 -07001459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001460 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001461 if (desc->mDirectOpenCount <= 0) {
1462 ALOGW("releaseOutput() invalid open count %d for output %d",
1463 desc->mDirectOpenCount, output);
1464 return;
1465 }
1466 if (--desc->mDirectOpenCount == 0) {
1467 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001468 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001469 }
1470 }
1471}
1472
1473
Eric Laurentcaf7f482014-11-25 17:50:47 -08001474status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1475 audio_io_handle_t *input,
1476 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001477 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001478 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001479 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001480 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001481 input_type_t *inputType,
1482 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001483{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001484 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001485 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001486 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001487
Eric Laurentad2e7b92017-09-14 20:06:42 -07001488 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001489 // handle legacy remote submix case where the address was not always specified
1490 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001491 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001492 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001493 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001494 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495
Eric Laurentfe231122017-11-17 17:48:06 -08001496 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1497 inputSource = AUDIO_SOURCE_MIC;
1498 }
1499
Paul McLean466dc8e2015-04-17 13:15:36 -06001500 // Explicit routing?
1501 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001502 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001503 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001504 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001505 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001506
Eric Laurentad2e7b92017-09-14 20:06:42 -07001507 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1508 // possible
1509 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1510 *input != AUDIO_IO_HANDLE_NONE) {
1511 ssize_t index = mInputs.indexOfKey(*input);
1512 if (index < 0) {
1513 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1514 status = BAD_VALUE;
1515 goto error;
1516 }
1517 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1518 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1519 if (audioSession == 0) {
1520 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1521 status = BAD_VALUE;
1522 goto error;
1523 }
1524 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1525 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001526 // corresponds to a new client and is only permitted from the same UID.
1527 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001528 if (audioSession->openCount() == 1) {
1529 audioSession->setUid(uid);
1530 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001531 if (!audioSession->isSilenced()) {
1532 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1533 uid, session, audioSession->uid());
1534 status = INVALID_OPERATION;
1535 goto error;
1536 }
1537 audioSession->setUid(uid);
1538 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001539 }
1540 audioSession->changeOpenCount(1);
1541 *inputType = API_INPUT_LEGACY;
1542 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1543 *portId = AudioPort::getNextUniqueId();
1544 }
1545 inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1546 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1547 : AUDIO_PORT_HANDLE_NONE;
1548 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1549
1550 return NO_ERROR;
1551 }
1552
1553 *input = AUDIO_IO_HANDLE_NONE;
1554 *inputType = API_INPUT_INVALID;
1555
Eric Laurentad2e7b92017-09-14 20:06:42 -07001556 halInputSource = inputSource;
1557
1558 // TODO: check for existing client for this port ID
1559 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1560 *portId = AudioPort::getNextUniqueId();
1561 }
1562
1563 audio_devices_t device;
1564
Eric Laurentc447ded2015-01-06 08:47:05 -08001565 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001566 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001567 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1568 if (status != NO_ERROR) {
1569 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001570 }
1571 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001572 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1573 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001574 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001575 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001576 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001577 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001578 status = BAD_VALUE;
1579 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001580 }
Eric Laurentc722f302014-12-10 11:21:49 -08001581 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001582 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001583 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1584 // there is an external policy, but this input is attached to a mix of recorders,
1585 // meaning it receives audio injected into the framework, so the recorder doesn't
1586 // know about it and is therefore considered "legacy"
1587 *inputType = API_INPUT_LEGACY;
1588 } else {
1589 // recording a mix of players defined by an external policy, we're rerouting for
1590 // an external policy
1591 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1592 }
Eric Laurentc722f302014-12-10 11:21:49 -08001593 } else if (audio_is_remote_submix_device(device)) {
1594 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001595 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001596 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1597 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001598 } else {
1599 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001600 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001601
Eric Laurent599c7582015-12-07 18:05:55 -08001602 }
1603
1604 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001605 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001606 policyMix);
1607 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001608 status = INVALID_OPERATION;
1609 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001610 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001611
Eric Laurentad2e7b92017-09-14 20:06:42 -07001612 inputDevices = mAvailableInputDevices.getDevicesFromType(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001613 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1614 : AUDIO_PORT_HANDLE_NONE;
1615
1616 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1617 *input, *inputType, *selectedDeviceId);
1618
Eric Laurent599c7582015-12-07 18:05:55 -08001619 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001620
1621error:
1622 mInputRoutes.removeRoute(session);
1623 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001624}
1625
1626
1627audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1628 String8 address,
1629 audio_session_t session,
1630 uid_t uid,
1631 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001632 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001633 audio_input_flags_t flags,
1634 AudioMix *policyMix)
1635{
1636 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1637 audio_source_t halInputSource = inputSource;
1638 bool isSoundTrigger = false;
1639
1640 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1641 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1642 if (index >= 0) {
1643 input = mSoundTriggerSessions.valueFor(session);
1644 isSoundTrigger = true;
1645 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1646 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1647 } else {
1648 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001649 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001650 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001651 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001652 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001653 }
1654
Andy Hungf129b032015-04-07 13:45:50 -07001655 // find a compatible input profile (not necessarily identical in parameters)
1656 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001657 // sampling rate and flags may be updated by getInputProfile
1658 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1659 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001660 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001661 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001662 audio_input_flags_t profileFlags = flags;
1663 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001664 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001665 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001666 profileSamplingRate, profileFormat, profileChannelMask,
1667 profileFlags);
1668 if (profile != 0) {
1669 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001670 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1671 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001672 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1673 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1674 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001675 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001676 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1677 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001678 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001679 }
Eric Laurente552edb2014-03-10 17:42:56 -07001680 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001681 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001682 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001683 if (samplingRate == 0) {
1684 samplingRate = profileSamplingRate;
1685 }
Eric Laurente552edb2014-03-10 17:42:56 -07001686
Eric Laurent322b4d22015-04-03 15:57:54 -07001687 if (profile->getModuleHandle() == 0) {
1688 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001689 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001690 }
1691
Eric Laurent599c7582015-12-07 18:05:55 -08001692 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001693 inputSource,
1694 config->format,
1695 samplingRate,
1696 config->channel_mask,
1697 flags,
1698 uid,
1699 isSoundTrigger,
1700 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001701
Eric Laurent74708e72017-04-07 17:13:42 -07001702// FIXME: disable concurrent capture until UI is ready
1703#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001704 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001705 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001706 for (size_t i = 0; i < mInputs.size(); i++) {
1707 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001708 // reuse input if:
1709 // - it shares the same profile
1710 // AND
1711 // - it is not a reroute submix input
1712 // AND
1713 // - it is: not used for sound trigger
1714 // OR
1715 // used for sound trigger and all clients use the same session ID
1716 //
1717 if ((profile == desc->mProfile) &&
1718 (isSoundTrigger == desc->isSoundTrigger()) &&
1719 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001720
1721 sp<AudioSession> as = desc->getAudioSession(session);
1722 if (as != 0) {
1723 // do not allow unmatching properties on same session
1724 if (as->matches(audioSession)) {
1725 as->changeOpenCount(1);
1726 } else {
1727 ALOGW("getInputForDevice() record with different attributes"
1728 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001729 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001730 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001731 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001732 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001733 }
Eric Laurentbb948092017-01-23 18:33:30 -08001734
Eric Laurent555530a2017-02-07 18:17:24 -08001735 // Reuse the already opened input stream on this profile if:
1736 // - the new capture source is background OR
1737 // - the path requested configurations match OR
1738 // - the new source priority is less than the highest source priority on this input
1739 // If the input stream cannot be reused, close it before opening a new stream
1740 // on the same profile for the new client so that the requested path configuration
1741 // can be selected.
1742 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001743 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001744 desc->mChannelMask != config->channel_mask ||
1745 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001746 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001747 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001748 reusedInputDesc = desc;
1749 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001750 } else {
1751 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001752 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1753 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001754 }
Eric Laurent599c7582015-12-07 18:05:55 -08001755 }
1756 }
Eric Laurent599c7582015-12-07 18:05:55 -08001757
Eric Laurent555530a2017-02-07 18:17:24 -08001758 if (reusedInputDesc != 0) {
1759 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1760 for (size_t j = 0; j < sessions.size(); j++) {
1761 audio_session_t currentSession = sessions.keyAt(j);
1762 stopInput(reusedInputDesc->mIoHandle, currentSession);
1763 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1764 }
1765 }
Eric Laurent74708e72017-04-07 17:13:42 -07001766#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001767
Eric Laurent3974e3b2017-12-07 17:58:43 -08001768 if (!profile->canOpenNewIo()) {
1769 return AUDIO_IO_HANDLE_NONE;
1770 }
1771
Eric Laurentfe231122017-11-17 17:48:06 -08001772 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001773
Eric Laurentfe231122017-11-17 17:48:06 -08001774 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1775 lConfig.sample_rate = profileSamplingRate;
1776 lConfig.channel_mask = profileChannelMask;
1777 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001778
Eric Laurent53b810e2017-12-10 17:25:10 -08001779 if (address == "") {
1780 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1781 // the inputs vector must be of size >= 1, but we don't want to crash here
1782 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1783 }
1784
Eric Laurentfe231122017-11-17 17:48:06 -08001785 status_t status = inputDesc->open(&lConfig, device, address,
1786 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001787
1788 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001789 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001790 (profileSamplingRate != lConfig.sample_rate) ||
1791 !audio_formats_match(profileFormat, lConfig.format) ||
1792 (profileChannelMask != lConfig.channel_mask)) {
1793 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001794 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001795 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001796 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001797 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001798 }
Eric Laurent599c7582015-12-07 18:05:55 -08001799 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001800 }
1801
Eric Laurentc722f302014-12-10 11:21:49 -08001802 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001803 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001804
Eric Laurent599c7582015-12-07 18:05:55 -08001805 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001806 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001807
Eric Laurent599c7582015-12-07 18:05:55 -08001808 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001809}
1810
Eric Laurentbb948092017-01-23 18:33:30 -08001811//static
1812bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1813{
1814 return (source == AUDIO_SOURCE_HOTWORD) ||
1815 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1816 (source == AUDIO_SOURCE_FM_TUNER);
1817}
1818
Eric Laurentfb66dd92016-01-28 18:32:03 -08001819bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1820 const sp<AudioSession>& audioSession)
1821{
1822 // Do not allow capture if an active voice call is using a software patch and
1823 // the call TX source device is on the same HW module.
1824 // FIXME: would be better to refine to only inputs whose profile connects to the
1825 // call TX device but this information is not in the audio patch
1826 if (mCallTxPatch != 0 &&
1827 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1828 return false;
1829 }
1830
1831 // starting concurrent capture is enabled if:
1832 // 1) capturing for re-routing
1833 // 2) capturing for HOTWORD source
1834 // 3) capturing for FM TUNER source
1835 // 3) All other active captures are either for re-routing or HOTWORD
1836
1837 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001838 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001839 return true;
1840 }
1841
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001842 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001843 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001844 !is_virtual_input_device(activeInput->mDevice)) {
1845 return false;
1846 }
1847 }
1848
1849 return true;
1850}
1851
Chris Thornton2b864642017-06-27 21:26:07 -07001852// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1853bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1854 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1855 bool soundTriggerSupportsConcurrentCapture = false;
1856 unsigned int numModules = 0;
1857 struct sound_trigger_module_descriptor* nModules = NULL;
1858
1859 status_t status = SoundTrigger::listModules(nModules, &numModules);
1860 if (status == NO_ERROR && numModules != 0) {
1861 nModules = (struct sound_trigger_module_descriptor*) calloc(
1862 numModules, sizeof(struct sound_trigger_module_descriptor));
1863 if (nModules == NULL) {
1864 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1865 // ram the next time this function is called.
1866 ALOGE("Failed to allocate buffer for module descriptors");
1867 return false;
1868 }
1869
1870 status = SoundTrigger::listModules(nModules, &numModules);
1871 if (status == NO_ERROR) {
1872 soundTriggerSupportsConcurrentCapture = true;
1873 for (size_t i = 0; i < numModules; ++i) {
1874 soundTriggerSupportsConcurrentCapture &=
1875 nModules[i].properties.concurrent_capture;
1876 }
1877 }
1878 free(nModules);
1879 }
1880 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1881 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1882 }
1883 return mSoundTriggerSupportsConcurrentCapture;
1884}
1885
Eric Laurentfb66dd92016-01-28 18:32:03 -08001886
Eric Laurent4dc68062014-07-28 17:26:49 -07001887status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001888 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001889 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001890 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001891{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001892
1893 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1894 input, session, silenced, *concurrency);
1895
Eric Laurentfb66dd92016-01-28 18:32:03 -08001896 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001897
Eric Laurente552edb2014-03-10 17:42:56 -07001898 ssize_t index = mInputs.indexOfKey(input);
1899 if (index < 0) {
1900 ALOGW("startInput() unknown input %d", input);
1901 return BAD_VALUE;
1902 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001903 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001904
Eric Laurent599c7582015-12-07 18:05:55 -08001905 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1906 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001907 ALOGW("startInput() unknown session %d on input %d", session, input);
1908 return BAD_VALUE;
1909 }
1910
Eric Laurent74708e72017-04-07 17:13:42 -07001911// FIXME: disable concurrent capture until UI is ready
1912#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001913 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1914 ALOGW("startInput(%d) failed: other input already started", input);
1915 return INVALID_OPERATION;
1916 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001917
Eric Laurentfb66dd92016-01-28 18:32:03 -08001918 if (isInCall()) {
1919 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1920 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001921 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001922 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001923 }
Eric Laurent74708e72017-04-07 17:13:42 -07001924#else
1925 if (!is_virtual_input_device(inputDesc->mDevice)) {
1926 if (mCallTxPatch != 0 &&
1927 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1928 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001929 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001930 return INVALID_OPERATION;
1931 }
1932
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001933 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001934
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001935 // If a UID is idle and records silence and another not silenced recording starts
1936 // from another UID (idle or active) we stop the current idle UID recording in
1937 // favor of the new one - "There can be only one" TM
1938 if (!silenced) {
1939 for (const auto& activeDesc : activeInputs) {
1940 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1941 activeDesc->getId() == inputDesc->getId()) {
1942 continue;
1943 }
1944
1945 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1946 true /*activeOnly*/);
1947 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1948 if (activeSession->isSilenced()) {
1949 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1950 audio_session_t activeSessionId = activeSession->session();
1951 stopInput(activeInput, activeSessionId);
1952 releaseInput(activeInput, activeSessionId);
1953 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1954 activeInputs = mInputs.getActiveInputs();
1955 }
1956 }
1957 }
1958
1959 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001960 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1961 activeDesc->getId() == inputDesc->getId()) {
1962 continue;
1963 }
1964
Eric Laurent74708e72017-04-07 17:13:42 -07001965 audio_source_t activeSource = activeDesc->inputSource(true);
1966 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1967 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1968 if (activeDesc->hasPreemptedSession(session)) {
1969 ALOGW("startInput(%d) failed for HOTWORD: "
1970 "other input %d already started for HOTWORD",
1971 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001972 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001973 return INVALID_OPERATION;
1974 }
1975 } else {
1976 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1977 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001978 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001979 return INVALID_OPERATION;
1980 }
1981 } else {
1982 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1983 ALOGW("startInput(%d) failed: other input %d already started",
1984 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001985 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001986 return INVALID_OPERATION;
1987 }
1988 }
1989 }
1990
Chris Thornton2b864642017-06-27 21:26:07 -07001991 // We only need to check if the sound trigger session supports concurrent capture if the
1992 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1993 // that's running.
1994 const bool allowConcurrentWithSoundTrigger =
1995 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1996
Eric Laurent74708e72017-04-07 17:13:42 -07001997 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001998 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001999 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
2000 continue;
2001 }
2002
Eric Laurent74708e72017-04-07 17:13:42 -07002003 audio_source_t activeSource = activeDesc->inputSource(true);
2004 if (activeSource == AUDIO_SOURCE_HOTWORD) {
2005 AudioSessionCollection activeSessions =
2006 activeDesc->getAudioSessions(true /*activeOnly*/);
2007 audio_session_t activeSession = activeSessions.keyAt(0);
2008 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
2009 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07002010 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07002011 sessions.add(activeSession);
2012 inputDesc->setPreemptedSessions(sessions);
2013 stopInput(activeHandle, activeSession);
2014 releaseInput(activeHandle, activeSession);
2015 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
2016 input, activeDesc->mIoHandle);
2017 }
2018 }
2019 }
2020#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002022 // Make sure we start with the correct silence state
2023 audioSession->setSilenced(silenced);
2024
Eric Laurent313d1e72016-01-29 09:56:57 -08002025 // increment activity count before calling getNewInputDevice() below as only active sessions
2026 // are considered for device selection
2027 audioSession->changeActiveCount(1);
2028
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002029 // Routing?
2030 mInputRoutes.incRouteActivity(session);
2031
Eric Laurent2157f5b2018-04-25 18:33:02 -07002032 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002033 // indicate active capture to sound trigger service if starting capture from a mic on
2034 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002035 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002036 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002037
Eric Laurent733ce942017-12-07 12:18:25 -08002038 status_t status = inputDesc->start();
2039 if (status != NO_ERROR) {
2040 mInputRoutes.decRouteActivity(session);
2041 audioSession->changeActiveCount(-1);
2042 return status;
2043 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002044
Eric Laurent733ce942017-12-07 12:18:25 -08002045 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002046 // if input maps to a dynamic policy with an activity listener, notify of state change
2047 if ((inputDesc->mPolicyMix != NULL)
2048 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2049 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2050 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002051 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002052
Eric Laurentf7c50102016-09-30 15:19:43 -07002053 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2054 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002055 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002056 SoundTrigger::setCaptureState(true);
2057 }
2058
2059 // automatically enable the remote submix output when input is started if not
2060 // used by a policy mix of type MIX_TYPE_RECORDERS
2061 // For remote submix (a virtual device), we open only one input per capture request.
2062 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2063 String8 address = String8("");
2064 if (inputDesc->mPolicyMix == NULL) {
2065 address = String8("0");
2066 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2067 address = inputDesc->mPolicyMix->mDeviceAddress;
2068 }
2069 if (address != "") {
2070 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2071 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2072 address, "remote-submix");
2073 }
Eric Laurentc722f302014-12-10 11:21:49 -08002074 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002075 }
Eric Laurente552edb2014-03-10 17:42:56 -07002076 }
2077
Eric Laurent599c7582015-12-07 18:05:55 -08002078 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002079
Eric Laurente552edb2014-03-10 17:42:56 -07002080 return NO_ERROR;
2081}
2082
Eric Laurent4dc68062014-07-28 17:26:49 -07002083status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2084 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002085{
2086 ALOGV("stopInput() input %d", input);
2087 ssize_t index = mInputs.indexOfKey(input);
2088 if (index < 0) {
2089 ALOGW("stopInput() unknown input %d", input);
2090 return BAD_VALUE;
2091 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002092 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002093
Eric Laurent599c7582015-12-07 18:05:55 -08002094 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002095 if (index < 0) {
2096 ALOGW("stopInput() unknown session %d on input %d", session, input);
2097 return BAD_VALUE;
2098 }
2099
Eric Laurent599c7582015-12-07 18:05:55 -08002100 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002101 ALOGW("stopInput() input %d already stopped", input);
2102 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002103 }
2104
Eric Laurent599c7582015-12-07 18:05:55 -08002105 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002106
2107 // Routing?
2108 mInputRoutes.decRouteActivity(session);
2109
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002110 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002111 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002112 if (inputDesc->isActive()) {
2113 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2114 } else {
2115 // if input maps to a dynamic policy with an activity listener, notify of state change
2116 if ((inputDesc->mPolicyMix != NULL)
2117 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2118 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2119 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002120 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002121
2122 // automatically disable the remote submix output when input is stopped if not
2123 // used by a policy mix of type MIX_TYPE_RECORDERS
2124 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2125 String8 address = String8("");
2126 if (inputDesc->mPolicyMix == NULL) {
2127 address = String8("0");
2128 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2129 address = inputDesc->mPolicyMix->mDeviceAddress;
2130 }
2131 if (address != "") {
2132 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2133 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2134 address, "remote-submix");
2135 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002136 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002137
Eric Laurentf7c50102016-09-30 15:19:43 -07002138 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002139 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002140
Eric Laurentf7c50102016-09-30 15:19:43 -07002141 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2142 // primary HW module
2143 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2144 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2145 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002146 SoundTrigger::setCaptureState(false);
2147 }
2148 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002149 }
Eric Laurente552edb2014-03-10 17:42:56 -07002150 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002151 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002152}
2153
Eric Laurent4dc68062014-07-28 17:26:49 -07002154void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2155 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002156{
2157 ALOGV("releaseInput() %d", input);
2158 ssize_t index = mInputs.indexOfKey(input);
2159 if (index < 0) {
2160 ALOGW("releaseInput() releasing unknown input %d", input);
2161 return;
2162 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002163
2164 // Routing
2165 mInputRoutes.removeRoute(session);
2166
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002167 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2168 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002169
Eric Laurent599c7582015-12-07 18:05:55 -08002170 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002171 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002172 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2173 return;
2174 }
Eric Laurent599c7582015-12-07 18:05:55 -08002175
2176 if (audioSession->openCount() == 0) {
2177 ALOGW("releaseInput() invalid open count %d on session %d",
2178 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002179 return;
2180 }
Eric Laurent599c7582015-12-07 18:05:55 -08002181
2182 if (audioSession->changeOpenCount(-1) == 0) {
2183 inputDesc->removeAudioSession(session);
2184 }
2185
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002186 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002187 ALOGV("releaseInput() exit > 0");
2188 return;
2189 }
2190
Eric Laurent05b90f82014-08-27 15:32:29 -07002191 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002192 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002193 ALOGV("releaseInput() exit");
2194}
2195
Eric Laurentd4692962014-05-05 18:13:44 -07002196void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002197 bool patchRemoved = false;
2198
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002199 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002200 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002201 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002202 if (patch_index >= 0) {
2203 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002204 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002205 mAudioPatches.removeItemsAt(patch_index);
2206 patchRemoved = true;
2207 }
Eric Laurentfe231122017-11-17 17:48:06 -08002208 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002209 }
jiabin829a00b2018-04-04 16:28:32 -07002210 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002211 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002212 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002213 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002214
2215 if (patchRemoved) {
2216 mpClientInterface->onAudioPatchListUpdate();
2217 }
Eric Laurentd4692962014-05-05 18:13:44 -07002218}
2219
Eric Laurente0720872014-03-11 09:30:41 -07002220void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002221 int indexMin,
2222 int indexMax)
2223{
2224 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002225 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002226
2227 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002228 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2229 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002230 continue;
2231 }
2232 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002233 }
Eric Laurente552edb2014-03-10 17:42:56 -07002234}
2235
Eric Laurente0720872014-03-11 09:30:41 -07002236status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002237 int index,
2238 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002239{
2240
Nadav Bar7c605f62017-12-25 00:01:52 +02002241 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2242 // app that has MODIFY_PHONE_STATE permission.
2243 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2244 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002245 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002246 return BAD_VALUE;
2247 }
2248 if (!audio_is_output_device(device)) {
2249 return BAD_VALUE;
2250 }
2251
2252 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002253 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002254
Eric Laurent1fd372e2016-04-06 14:23:53 -07002255 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002256 stream, device, index);
2257
Eric Laurent28d09f02016-03-08 10:43:05 -08002258 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002259 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2260 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002261 continue;
2262 }
2263 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2264 }
Eric Laurente552edb2014-03-10 17:42:56 -07002265
Eric Laurent1fd372e2016-04-06 14:23:53 -07002266 // update volume on all outputs and streams matching the following:
2267 // - The requested stream (or a stream matching for volume control) is active on the output
2268 // - The device (or devices) selected by the strategy corresponding to this stream includes
2269 // the requested device
2270 // - For non default requested device, currently selected device on the output is either the
2271 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002272 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2273 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002274 status_t status = NO_ERROR;
2275 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002276 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2277 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002278 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2279 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002280 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002281 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002282 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2283 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002284 continue;
2285 }
Eric Laurent794fde22016-03-11 09:50:45 -08002286 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002287 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2288 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002289 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2290 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002291 continue;
2292 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002293 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002294 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002295 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002296 applyVolume = (curDevice & curStreamDevice) != 0;
2297 } else {
2298 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002299 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002300 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002301
Eric Laurente76f29c2016-09-14 17:17:53 -07002302 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002303 //FIXME: workaround for truncated touch sounds
2304 // delayed volume change for system stream to be removed when the problem is
2305 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002306 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002307 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2308 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002309 if (volStatus != NO_ERROR) {
2310 status = volStatus;
2311 }
2312 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002313 }
Eric Laurente552edb2014-03-10 17:42:56 -07002314 }
2315 return status;
2316}
2317
Eric Laurente0720872014-03-11 09:30:41 -07002318status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002319 int *index,
2320 audio_devices_t device)
2321{
2322 if (index == NULL) {
2323 return BAD_VALUE;
2324 }
2325 if (!audio_is_output_device(device)) {
2326 return BAD_VALUE;
2327 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002328 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002329 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002330 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002331 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2332 }
François Gaffiedfd74092015-03-19 12:10:59 +01002333 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002334
François Gaffied1ab2bd2015-12-02 18:20:06 +01002335 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002336 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2337 return NO_ERROR;
2338}
2339
Eric Laurent36829f92017-04-07 19:04:42 -07002340audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002341{
2342 // select one output among several suitable for global effects.
2343 // The priority is as follows:
2344 // 1: An offloaded output. If the effect ends up not being offloadable,
2345 // AudioFlinger will invalidate the track and the offloaded output
2346 // will be closed causing the effect to be moved to a PCM output.
2347 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002348 // 3: The primary output
2349 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002350
Eric Laurent3b73df72014-03-11 09:06:29 -07002351 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002352 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002353 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002354
Eric Laurent36829f92017-04-07 19:04:42 -07002355 if (outputs.size() == 0) {
2356 return AUDIO_IO_HANDLE_NONE;
2357 }
Eric Laurente552edb2014-03-10 17:42:56 -07002358
Eric Laurent36829f92017-04-07 19:04:42 -07002359 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2360 bool activeOnly = true;
2361
2362 while (output == AUDIO_IO_HANDLE_NONE) {
2363 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2364 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2365 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2366
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002367 for (audio_io_handle_t output : outputs) {
2368 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002369 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2370 continue;
2371 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002372 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2373 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002374 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002375 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002376 }
2377 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002378 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002379 }
2380 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002381 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002382 }
2383 }
2384 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2385 output = outputOffloaded;
2386 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2387 output = outputDeepBuffer;
2388 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2389 output = outputPrimary;
2390 } else {
2391 output = outputs[0];
2392 }
2393 activeOnly = false;
2394 }
2395
2396 if (output != mMusicEffectOutput) {
2397 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2398 mMusicEffectOutput = output;
2399 }
2400
2401 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002402 return output;
2403}
2404
Eric Laurent36829f92017-04-07 19:04:42 -07002405audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2406{
2407 return selectOutputForMusicEffects();
2408}
2409
Eric Laurente0720872014-03-11 09:30:41 -07002410status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002411 audio_io_handle_t io,
2412 uint32_t strategy,
2413 int session,
2414 int id)
2415{
2416 ssize_t index = mOutputs.indexOfKey(io);
2417 if (index < 0) {
2418 index = mInputs.indexOfKey(io);
2419 if (index < 0) {
2420 ALOGW("registerEffect() unknown io %d", io);
2421 return INVALID_OPERATION;
2422 }
2423 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002424 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002425}
2426
Eric Laurentc75307b2015-03-17 15:29:32 -07002427bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2428{
Eric Laurent28d09f02016-03-08 10:43:05 -08002429 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002430 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2431 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002432 continue;
2433 }
2434 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2435 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002436 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002437}
2438
2439bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2440{
2441 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2442}
2443
Eric Laurente0720872014-03-11 09:30:41 -07002444bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002445{
2446 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002447 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002448 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002449 return true;
2450 }
2451 }
2452 return false;
2453}
2454
Eric Laurent275e8e92014-11-30 15:14:47 -08002455// Register a list of custom mixes with their attributes and format.
2456// When a mix is registered, corresponding input and output profiles are
2457// added to the remote submix hw module. The profile contains only the
2458// parameters (sampling rate, format...) specified by the mix.
2459// The corresponding input remote submix device is also connected.
2460//
2461// When a remote submix device is connected, the address is checked to select the
2462// appropriate profile and the corresponding input or output stream is opened.
2463//
2464// When capture starts, getInputForAttr() will:
2465// - 1 look for a mix matching the address passed in attribtutes tags if any
2466// - 2 if none found, getDeviceForInputSource() will:
2467// - 2.1 look for a mix matching the attributes source
2468// - 2.2 if none found, default to device selection by policy rules
2469// At this time, the corresponding output remote submix device is also connected
2470// and active playback use cases can be transferred to this mix if needed when reconnecting
2471// after AudioTracks are invalidated
2472//
2473// When playback starts, getOutputForAttr() will:
2474// - 1 look for a mix matching the address passed in attribtutes tags if any
2475// - 2 if none found, look for a mix matching the attributes usage
2476// - 3 if none found, default to device and output selection by policy rules.
2477
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002478status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002479{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2481 status_t res = NO_ERROR;
2482
2483 sp<HwModule> rSubmixModule;
2484 // examine each mix's route type
2485 for (size_t i = 0; i < mixes.size(); i++) {
2486 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2487 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2488 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002489 break;
2490 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002491 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002492 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002493 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002494 rSubmixModule = mHwModules.getModuleFromName(
2495 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2496 if (rSubmixModule == 0) {
2497 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2498 i);
2499 res = INVALID_OPERATION;
2500 break;
2501 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002502 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002503
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002504 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002505
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002507 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508 res = INVALID_OPERATION;
2509 break;
2510 }
2511 audio_config_t outputConfig = mixes[i].mFormat;
2512 audio_config_t inputConfig = mixes[i].mFormat;
2513 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2514 // stereo and let audio flinger do the channel conversion if needed.
2515 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2516 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2517 rSubmixModule->addOutputProfile(address, &outputConfig,
2518 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2519 rSubmixModule->addInputProfile(address, &inputConfig,
2520 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002521
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2523 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2524 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2525 address.string(), "remote-submix");
2526 } else {
2527 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2528 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2529 address.string(), "remote-submix");
2530 }
2531 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002532 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002534 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2535 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002536
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002537 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002538 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2539 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2540 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2541 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2542 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2543 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002544 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2545 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2547 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002548 } else {
2549 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002550 }
2551 break;
2552 }
2553 }
2554
2555 if (res != NO_ERROR) {
2556 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002557 i, device, address.string());
2558 res = INVALID_OPERATION;
2559 break;
2560 } else if (!foundOutput) {
2561 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2562 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002563 res = INVALID_OPERATION;
2564 break;
2565 }
Eric Laurentc722f302014-12-10 11:21:49 -08002566 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002567 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002568 if (res != NO_ERROR) {
2569 unregisterPolicyMixes(mixes);
2570 }
2571 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002572}
2573
2574status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2575{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002576 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002577 status_t res = NO_ERROR;
2578 sp<HwModule> rSubmixModule;
2579 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002580 for (const auto& mix : mixes) {
2581 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002582
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002583 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002584 rSubmixModule = mHwModules.getModuleFromName(
2585 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2586 if (rSubmixModule == 0) {
2587 res = INVALID_OPERATION;
2588 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 }
2590 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002591
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002592 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002593
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2595 res = INVALID_OPERATION;
2596 continue;
2597 }
2598
2599 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2600 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2601 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2602 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2603 address.string(), "remote-submix");
2604 }
2605 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2606 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2607 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2608 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2609 address.string(), "remote-submix");
2610 }
2611 rSubmixModule->removeOutputProfile(address);
2612 rSubmixModule->removeInputProfile(address);
2613
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002614 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2615 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002616 res = INVALID_OPERATION;
2617 continue;
2618 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002619 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002620 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002621 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002622}
2623
Eric Laurente552edb2014-03-10 17:42:56 -07002624
Eric Laurente0720872014-03-11 09:30:41 -07002625status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002626{
2627 const size_t SIZE = 256;
2628 char buffer[SIZE];
2629 String8 result;
2630
2631 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2632 result.append(buffer);
2633
Eric Laurent87ffa392015-05-22 10:32:38 -07002634 snprintf(buffer, SIZE, " Primary Output: %d\n",
2635 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002636 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002637 std::string stateLiteral;
2638 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2639 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002640 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002641 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002642 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002643 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002644 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002645 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002646 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002647 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002648 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002649 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002650 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002651 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002652 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002653 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002654 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002655 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2656 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2657 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002658 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2659 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002660 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2661 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002662
François Gaffie2110e042015-03-24 08:41:51 +01002663 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002664
François Gaffie112b0af2015-11-19 16:13:25 +01002665 mAvailableOutputDevices.dump(fd, String8("Available output"));
2666 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002667 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002668 mOutputs.dump(fd);
2669 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002670 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002671 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002672 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002673 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002674
2675 return NO_ERROR;
2676}
2677
2678// This function checks for the parameters which can be offloaded.
2679// This can be enhanced depending on the capability of the DSP and policy
2680// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002681bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002682{
2683 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002684 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002685 offloadInfo.sample_rate, offloadInfo.channel_mask,
2686 offloadInfo.format,
2687 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2688 offloadInfo.has_video);
2689
Andy Hung2ddee192015-12-18 17:34:44 -08002690 if (mMasterMono) {
2691 return false; // no offloading if mono is set.
2692 }
2693
Eric Laurente552edb2014-03-10 17:42:56 -07002694 // Check if offload has been disabled
2695 char propValue[PROPERTY_VALUE_MAX];
2696 if (property_get("audio.offload.disable", propValue, "0")) {
2697 if (atoi(propValue) != 0) {
2698 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2699 return false;
2700 }
2701 }
2702
2703 // Check if stream type is music, then only allow offload as of now.
2704 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2705 {
2706 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2707 return false;
2708 }
2709
2710 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002711 const bool allowOffloadWithVideo =
2712 property_get_bool("audio.offload.video", false /* default_value */);
2713 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002714 ALOGV("isOffloadSupported: has_video == true, returning false");
2715 return false;
2716 }
2717
2718 //If duration is less than minimum value defined in property, return false
2719 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2720 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2721 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2722 return false;
2723 }
2724 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2725 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2726 return false;
2727 }
2728
2729 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2730 // creating an offloaded track and tearing it down immediately after start when audioflinger
2731 // detects there is an active non offloadable effect.
2732 // FIXME: We should check the audio session here but we do not have it in this context.
2733 // This may prevent offloading in rare situations where effects are left active by apps
2734 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002735 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002736 return false;
2737 }
2738
2739 // See if there is a profile to support this.
2740 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002741 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002742 offloadInfo.sample_rate,
2743 offloadInfo.format,
2744 offloadInfo.channel_mask,
2745 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002746 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2747 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002748}
2749
Eric Laurent6a94d692014-05-20 11:18:06 -07002750status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2751 audio_port_type_t type,
2752 unsigned int *num_ports,
2753 struct audio_port *ports,
2754 unsigned int *generation)
2755{
2756 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2757 generation == NULL) {
2758 return BAD_VALUE;
2759 }
2760 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2761 if (ports == NULL) {
2762 *num_ports = 0;
2763 }
2764
2765 size_t portsWritten = 0;
2766 size_t portsMax = *num_ports;
2767 *num_ports = 0;
2768 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002769 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2770 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002771 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002772 for (const auto& dev : mAvailableOutputDevices) {
2773 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002774 continue;
2775 }
2776 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002777 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002778 }
2779 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002780 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002781 }
2782 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002783 for (const auto& dev : mAvailableInputDevices) {
2784 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002785 continue;
2786 }
2787 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002788 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002789 }
2790 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002791 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002792 }
2793 }
2794 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2795 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2796 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2797 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2798 }
2799 *num_ports += mInputs.size();
2800 }
2801 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002802 size_t numOutputs = 0;
2803 for (size_t i = 0; i < mOutputs.size(); i++) {
2804 if (!mOutputs[i]->isDuplicated()) {
2805 numOutputs++;
2806 if (portsWritten < portsMax) {
2807 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2808 }
2809 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 }
Eric Laurent84c70242014-06-23 08:46:27 -07002811 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002812 }
2813 }
2814 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002815 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002816 return NO_ERROR;
2817}
2818
Eric Laurent99fcae42018-05-17 16:59:18 -07002819status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002820{
Eric Laurent99fcae42018-05-17 16:59:18 -07002821 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2822 return BAD_VALUE;
2823 }
2824 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2825 if (dev != 0) {
2826 dev->toAudioPort(port);
2827 return NO_ERROR;
2828 }
2829 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2830 if (dev != 0) {
2831 dev->toAudioPort(port);
2832 return NO_ERROR;
2833 }
2834 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2835 if (out != 0) {
2836 out->toAudioPort(port);
2837 return NO_ERROR;
2838 }
2839 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2840 if (in != 0) {
2841 in->toAudioPort(port);
2842 return NO_ERROR;
2843 }
2844 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002845}
2846
Eric Laurent6a94d692014-05-20 11:18:06 -07002847status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2848 audio_patch_handle_t *handle,
2849 uid_t uid)
2850{
2851 ALOGV("createAudioPatch()");
2852
2853 if (handle == NULL || patch == NULL) {
2854 return BAD_VALUE;
2855 }
2856 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2857
Eric Laurent874c42872014-08-08 15:13:39 -07002858 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2859 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2860 return BAD_VALUE;
2861 }
2862 // only one source per audio patch supported for now
2863 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002864 return INVALID_OPERATION;
2865 }
Eric Laurent874c42872014-08-08 15:13:39 -07002866
2867 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002868 return INVALID_OPERATION;
2869 }
Eric Laurent874c42872014-08-08 15:13:39 -07002870 for (size_t i = 0; i < patch->num_sinks; i++) {
2871 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2872 return INVALID_OPERATION;
2873 }
2874 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002875
2876 sp<AudioPatch> patchDesc;
2877 ssize_t index = mAudioPatches.indexOfKey(*handle);
2878
Eric Laurent6a94d692014-05-20 11:18:06 -07002879 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2880 patch->sources[0].role,
2881 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002882#if LOG_NDEBUG == 0
2883 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002884 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002885 patch->sinks[i].role,
2886 patch->sinks[i].type);
2887 }
2888#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002889
2890 if (index >= 0) {
2891 patchDesc = mAudioPatches.valueAt(index);
2892 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2893 mUidCached, patchDesc->mUid, uid);
2894 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2895 return INVALID_OPERATION;
2896 }
2897 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002898 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 }
2900
2901 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002902 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002903 if (outputDesc == NULL) {
2904 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2905 return BAD_VALUE;
2906 }
Eric Laurent84c70242014-06-23 08:46:27 -07002907 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2908 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002909 if (patchDesc != 0) {
2910 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2911 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2912 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2913 return BAD_VALUE;
2914 }
2915 }
Eric Laurent874c42872014-08-08 15:13:39 -07002916 DeviceVector devices;
2917 for (size_t i = 0; i < patch->num_sinks; i++) {
2918 // Only support mix to devices connection
2919 // TODO add support for mix to mix connection
2920 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2921 ALOGV("createAudioPatch() source mix but sink is not a device");
2922 return INVALID_OPERATION;
2923 }
2924 sp<DeviceDescriptor> devDesc =
2925 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2926 if (devDesc == 0) {
2927 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2928 return BAD_VALUE;
2929 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002930
François Gaffie53615e22015-03-19 09:24:12 +01002931 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002932 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002933 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002934 NULL, // updatedSamplingRate
2935 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002936 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002937 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002938 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002939 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002940 ALOGV("createAudioPatch() profile not supported for device %08x",
2941 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002942 return INVALID_OPERATION;
2943 }
2944 devices.add(devDesc);
2945 }
2946 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002947 return INVALID_OPERATION;
2948 }
Eric Laurent874c42872014-08-08 15:13:39 -07002949
Eric Laurent6a94d692014-05-20 11:18:06 -07002950 // TODO: reconfigure output format and channels here
2951 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002952 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002953 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 index = mAudioPatches.indexOfKey(*handle);
2955 if (index >= 0) {
2956 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2957 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2958 }
2959 patchDesc = mAudioPatches.valueAt(index);
2960 patchDesc->mUid = uid;
2961 ALOGV("createAudioPatch() success");
2962 } else {
2963 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2964 return INVALID_OPERATION;
2965 }
2966 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2967 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2968 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002969 // only one sink supported when connecting an input device to a mix
2970 if (patch->num_sinks > 1) {
2971 return INVALID_OPERATION;
2972 }
François Gaffie53615e22015-03-19 09:24:12 +01002973 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002974 if (inputDesc == NULL) {
2975 return BAD_VALUE;
2976 }
2977 if (patchDesc != 0) {
2978 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2979 return BAD_VALUE;
2980 }
2981 }
2982 sp<DeviceDescriptor> devDesc =
2983 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2984 if (devDesc == 0) {
2985 return BAD_VALUE;
2986 }
2987
François Gaffie53615e22015-03-19 09:24:12 +01002988 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002989 devDesc->mAddress,
2990 patch->sinks[0].sample_rate,
2991 NULL, /*updatedSampleRate*/
2992 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002993 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002994 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002995 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002996 // FIXME for the parameter type,
2997 // and the NONE
2998 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002999 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003000 return INVALID_OPERATION;
3001 }
3002 // TODO: reconfigure output format and channels here
3003 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01003004 devDesc->type(), inputDesc->mIoHandle);
3005 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003006 index = mAudioPatches.indexOfKey(*handle);
3007 if (index >= 0) {
3008 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3009 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3010 }
3011 patchDesc = mAudioPatches.valueAt(index);
3012 patchDesc->mUid = uid;
3013 ALOGV("createAudioPatch() success");
3014 } else {
3015 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3016 return INVALID_OPERATION;
3017 }
3018 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3019 // device to device connection
3020 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003021 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003022 return BAD_VALUE;
3023 }
3024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003025 sp<DeviceDescriptor> srcDeviceDesc =
3026 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07003027 if (srcDeviceDesc == 0) {
3028 return BAD_VALUE;
3029 }
Eric Laurent874c42872014-08-08 15:13:39 -07003030
Eric Laurent6a94d692014-05-20 11:18:06 -07003031 //update source and sink with our own data as the data passed in the patch may
3032 // be incomplete.
3033 struct audio_patch newPatch = *patch;
3034 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003035
Eric Laurent874c42872014-08-08 15:13:39 -07003036 for (size_t i = 0; i < patch->num_sinks; i++) {
3037 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3038 ALOGV("createAudioPatch() source device but one sink is not a device");
3039 return INVALID_OPERATION;
3040 }
3041
3042 sp<DeviceDescriptor> sinkDeviceDesc =
3043 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3044 if (sinkDeviceDesc == 0) {
3045 return BAD_VALUE;
3046 }
3047 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3048
Eric Laurent3bcf8592015-04-03 12:13:24 -07003049 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003050 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003051 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003052 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003053 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003054 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003055 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003056 return INVALID_OPERATION;
3057 }
Eric Laurent874c42872014-08-08 15:13:39 -07003058 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003059 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003060 // if the sink device is reachable via an opened output stream, request to go via
3061 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003062 audio_io_handle_t output = selectOutput(outputs,
3063 AUDIO_OUTPUT_FLAG_NONE,
3064 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003065 if (output != AUDIO_IO_HANDLE_NONE) {
3066 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3067 if (outputDesc->isDuplicated()) {
3068 return INVALID_OPERATION;
3069 }
3070 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003071 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003072 newPatch.num_sources = 2;
3073 }
Eric Laurent83b88082014-06-20 18:31:16 -07003074 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003075 }
3076 // TODO: check from routing capabilities in config file and other conflicting patches
3077
3078 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3079 if (index >= 0) {
3080 afPatchHandle = patchDesc->mAfPatchHandle;
3081 }
3082
3083 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3084 &afPatchHandle,
3085 0);
3086 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3087 status, afPatchHandle);
3088 if (status == NO_ERROR) {
3089 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003090 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 addAudioPatch(patchDesc->mHandle, patchDesc);
3092 } else {
3093 patchDesc->mPatch = newPatch;
3094 }
3095 patchDesc->mAfPatchHandle = afPatchHandle;
3096 *handle = patchDesc->mHandle;
3097 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003098 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003099 } else {
3100 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3101 status);
3102 return INVALID_OPERATION;
3103 }
3104 } else {
3105 return BAD_VALUE;
3106 }
3107 } else {
3108 return BAD_VALUE;
3109 }
3110 return NO_ERROR;
3111}
3112
3113status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3114 uid_t uid)
3115{
3116 ALOGV("releaseAudioPatch() patch %d", handle);
3117
3118 ssize_t index = mAudioPatches.indexOfKey(handle);
3119
3120 if (index < 0) {
3121 return BAD_VALUE;
3122 }
3123 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3124 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3125 mUidCached, patchDesc->mUid, uid);
3126 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3127 return INVALID_OPERATION;
3128 }
3129
3130 struct audio_patch *patch = &patchDesc->mPatch;
3131 patchDesc->mUid = mUidCached;
3132 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003133 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003134 if (outputDesc == NULL) {
3135 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3136 return BAD_VALUE;
3137 }
3138
Eric Laurentc75307b2015-03-17 15:29:32 -07003139 setOutputDevice(outputDesc,
3140 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003141 true,
3142 0,
3143 NULL);
3144 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3145 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003146 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003147 if (inputDesc == NULL) {
3148 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3149 return BAD_VALUE;
3150 }
3151 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003152 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003153 true,
3154 NULL);
3155 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003156 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3157 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3158 status, patchDesc->mAfPatchHandle);
3159 removeAudioPatch(patchDesc->mHandle);
3160 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003161 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003162 } else {
3163 return BAD_VALUE;
3164 }
3165 } else {
3166 return BAD_VALUE;
3167 }
3168 return NO_ERROR;
3169}
3170
3171status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3172 struct audio_patch *patches,
3173 unsigned int *generation)
3174{
François Gaffie53615e22015-03-19 09:24:12 +01003175 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003176 return BAD_VALUE;
3177 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003179 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003180}
3181
Eric Laurente1715a42014-05-20 11:30:42 -07003182status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003183{
Eric Laurente1715a42014-05-20 11:30:42 -07003184 ALOGV("setAudioPortConfig()");
3185
3186 if (config == NULL) {
3187 return BAD_VALUE;
3188 }
3189 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3190 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003191 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3192 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003193 }
3194
Eric Laurenta121f902014-06-03 13:32:54 -07003195 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003196 if (config->type == AUDIO_PORT_TYPE_MIX) {
3197 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003198 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003199 if (outputDesc == NULL) {
3200 return BAD_VALUE;
3201 }
Eric Laurent84c70242014-06-23 08:46:27 -07003202 ALOG_ASSERT(!outputDesc->isDuplicated(),
3203 "setAudioPortConfig() called on duplicated output %d",
3204 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003205 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003206 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003207 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003208 if (inputDesc == NULL) {
3209 return BAD_VALUE;
3210 }
Eric Laurenta121f902014-06-03 13:32:54 -07003211 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003212 } else {
3213 return BAD_VALUE;
3214 }
3215 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3216 sp<DeviceDescriptor> deviceDesc;
3217 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3218 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3219 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3220 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3221 } else {
3222 return BAD_VALUE;
3223 }
3224 if (deviceDesc == NULL) {
3225 return BAD_VALUE;
3226 }
Eric Laurenta121f902014-06-03 13:32:54 -07003227 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003228 } else {
3229 return BAD_VALUE;
3230 }
3231
Eric Laurenta121f902014-06-03 13:32:54 -07003232 struct audio_port_config backupConfig;
3233 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3234 if (status == NO_ERROR) {
3235 struct audio_port_config newConfig;
3236 audioPortConfig->toAudioPortConfig(&newConfig, config);
3237 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003238 }
Eric Laurenta121f902014-06-03 13:32:54 -07003239 if (status != NO_ERROR) {
3240 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003241 }
Eric Laurente1715a42014-05-20 11:30:42 -07003242
3243 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003244}
3245
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003246void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3247{
Eric Laurentd60560a2015-04-10 11:31:20 -07003248 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003249 clearAudioPatches(uid);
3250 clearSessionRoutes(uid);
3251}
3252
Eric Laurent6a94d692014-05-20 11:18:06 -07003253void AudioPolicyManager::clearAudioPatches(uid_t uid)
3254{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003255 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003256 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3257 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003258 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003259 }
3260 }
3261}
3262
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003263void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3264 audio_io_handle_t ouptutToSkip)
3265{
3266 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3267 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3268 for (size_t j = 0; j < mOutputs.size(); j++) {
3269 if (mOutputs.keyAt(j) == ouptutToSkip) {
3270 continue;
3271 }
3272 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3273 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3274 continue;
3275 }
3276 // If the default device for this strategy is on another output mix,
3277 // invalidate all tracks in this strategy to force re connection.
3278 // Otherwise select new device on the output mix.
3279 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003280 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003281 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3282 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3283 }
3284 }
3285 } else {
3286 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3287 setOutputDevice(outputDesc, newDevice, false);
3288 }
3289 }
3290}
3291
3292void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3293{
3294 // remove output routes associated with this uid
3295 SortedVector<routing_strategy> affectedStrategies;
3296 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3297 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3298 if (route->mUid == uid) {
3299 mOutputRoutes.removeItemsAt(i);
3300 if (route->mDeviceDescriptor != 0) {
3301 affectedStrategies.add(getStrategy(route->mStreamType));
3302 }
3303 }
3304 }
3305 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003306 for (const auto& strategy : affectedStrategies) {
3307 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003308 }
3309
3310 // remove input routes associated with this uid
3311 SortedVector<audio_source_t> affectedSources;
3312 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3313 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3314 if (route->mUid == uid) {
3315 mInputRoutes.removeItemsAt(i);
3316 if (route->mDeviceDescriptor != 0) {
3317 affectedSources.add(route->mSource);
3318 }
3319 }
3320 }
3321 // reroute inputs if necessary
3322 SortedVector<audio_io_handle_t> inputsToClose;
3323 for (size_t i = 0; i < mInputs.size(); i++) {
3324 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003325 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003326 inputsToClose.add(inputDesc->mIoHandle);
3327 }
3328 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003329 for (const auto& input : inputsToClose) {
3330 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003331 }
3332}
3333
Eric Laurentd60560a2015-04-10 11:31:20 -07003334void AudioPolicyManager::clearAudioSources(uid_t uid)
3335{
3336 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3337 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3338 if (sourceDesc->mUid == uid) {
3339 stopAudioSource(mAudioSources.keyAt(i));
3340 }
3341 }
3342}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003343
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003344status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3345 audio_io_handle_t *ioHandle,
3346 audio_devices_t *device)
3347{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003348 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3349 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003350 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003351
François Gaffiedf372692015-03-19 10:43:27 +01003352 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003353}
3354
Eric Laurentd60560a2015-04-10 11:31:20 -07003355status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3356 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003357 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003358 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003359{
Eric Laurentd60560a2015-04-10 11:31:20 -07003360 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3361 if (source == NULL || attributes == NULL || handle == NULL) {
3362 return BAD_VALUE;
3363 }
3364
Glenn Kasten559d4392016-03-29 13:42:57 -07003365 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003366
3367 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3368 source->type != AUDIO_PORT_TYPE_DEVICE) {
3369 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3370 return INVALID_OPERATION;
3371 }
3372
3373 sp<DeviceDescriptor> srcDeviceDesc =
3374 mAvailableInputDevices.getDevice(source->ext.device.type,
3375 String8(source->ext.device.address));
3376 if (srcDeviceDesc == 0) {
3377 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3378 return BAD_VALUE;
3379 }
3380 sp<AudioSourceDescriptor> sourceDesc =
3381 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3382
3383 struct audio_patch dummyPatch;
3384 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3385 sourceDesc->mPatchDesc = patchDesc;
3386
3387 status_t status = connectAudioSource(sourceDesc);
3388 if (status == NO_ERROR) {
3389 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3390 *handle = sourceDesc->getHandle();
3391 }
3392 return status;
3393}
3394
3395status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3396{
3397 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3398
3399 // make sure we only have one patch per source.
3400 disconnectAudioSource(sourceDesc);
3401
3402 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003403 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003404 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3405
3406 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3407 sp<DeviceDescriptor> sinkDeviceDesc =
3408 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3409
3410 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3411 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3412
3413 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3414 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003415 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003416 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3417 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3418 // create patch between src device and output device
3419 // create Hwoutput and add to mHwOutputs
3420 } else {
3421 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3422 audio_io_handle_t output =
3423 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3424 if (output == AUDIO_IO_HANDLE_NONE) {
3425 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3426 return INVALID_OPERATION;
3427 }
3428 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3429 if (outputDesc->isDuplicated()) {
3430 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3431 return INVALID_OPERATION;
3432 }
Eric Laurent733ce942017-12-07 12:18:25 -08003433 status_t status = outputDesc->start();
3434 if (status != NO_ERROR) {
3435 return status;
3436 }
3437
Eric Laurentd60560a2015-04-10 11:31:20 -07003438 // create a special patch with no sink and two sources:
3439 // - the second source indicates to PatchPanel through which output mix this patch should
3440 // be connected as well as the stream type for volume control
3441 // - the sink is defined by whatever output device is currently selected for the output
3442 // though which this patch is routed.
3443 patch->num_sinks = 0;
3444 patch->num_sources = 2;
3445 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3446 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3447 patch->sources[1].ext.mix.usecase.stream = stream;
Eric Laurent733ce942017-12-07 12:18:25 -08003448 status = mpClientInterface->createAudioPatch(patch,
Eric Laurentd60560a2015-04-10 11:31:20 -07003449 &afPatchHandle,
3450 0);
3451 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3452 status, afPatchHandle);
3453 if (status != NO_ERROR) {
3454 ALOGW("%s patch panel could not connect device patch, error %d",
3455 __FUNCTION__, status);
3456 return INVALID_OPERATION;
3457 }
3458 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003459 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003460
3461 if (status != NO_ERROR) {
3462 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3463 return status;
3464 }
3465 sourceDesc->mSwOutput = outputDesc;
3466 if (delayMs != 0) {
3467 usleep(delayMs * 1000);
3468 }
3469 }
3470
3471 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3472 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3473
3474 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003475}
3476
Glenn Kasten559d4392016-03-29 13:42:57 -07003477status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003478{
Eric Laurentd60560a2015-04-10 11:31:20 -07003479 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3480 ALOGV("%s handle %d", __FUNCTION__, handle);
3481 if (sourceDesc == 0) {
3482 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3483 return BAD_VALUE;
3484 }
3485 status_t status = disconnectAudioSource(sourceDesc);
3486
3487 mAudioSources.removeItem(handle);
3488 return status;
3489}
3490
Andy Hung2ddee192015-12-18 17:34:44 -08003491status_t AudioPolicyManager::setMasterMono(bool mono)
3492{
3493 if (mMasterMono == mono) {
3494 return NO_ERROR;
3495 }
3496 mMasterMono = mono;
3497 // if enabling mono we close all offloaded devices, which will invalidate the
3498 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3499 // for recreating the new AudioTrack as non-offloaded PCM.
3500 //
3501 // If disabling mono, we leave all tracks as is: we don't know which clients
3502 // and tracks are able to be recreated as offloaded. The next "song" should
3503 // play back offloaded.
3504 if (mMasterMono) {
3505 Vector<audio_io_handle_t> offloaded;
3506 for (size_t i = 0; i < mOutputs.size(); ++i) {
3507 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3508 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3509 offloaded.push(desc->mIoHandle);
3510 }
3511 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003512 for (const auto& handle : offloaded) {
3513 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003514 }
3515 }
3516 // update master mono for all remaining outputs
3517 for (size_t i = 0; i < mOutputs.size(); ++i) {
3518 updateMono(mOutputs.keyAt(i));
3519 }
3520 return NO_ERROR;
3521}
3522
3523status_t AudioPolicyManager::getMasterMono(bool *mono)
3524{
3525 *mono = mMasterMono;
3526 return NO_ERROR;
3527}
3528
Eric Laurentac9cef52017-06-09 15:46:26 -07003529float AudioPolicyManager::getStreamVolumeDB(
3530 audio_stream_type_t stream, int index, audio_devices_t device)
3531{
3532 return computeVolume(stream, index, device);
3533}
3534
jiabin81772902018-04-02 17:52:27 -07003535status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3536 FormatVector& formats) {
3537 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3538 return BAD_VALUE;
3539 }
3540 String8 reply;
3541 reply = mpClientInterface->getParameters(
3542 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3543 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3544 AudioParameter repliedParameters(reply);
3545 if (repliedParameters.get(
3546 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3547 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3548 return BAD_VALUE;
3549 }
3550 for (auto format : formatsFromString(reply.string())) {
3551 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3552 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3553 if (format == AAC_FORMATS[i]) {
3554 format = AUDIO_FORMAT_AAC_LC;
3555 break;
3556 }
3557 }
3558 bool exist = false;
3559 for (size_t i = 0; i < formats.size(); i++) {
3560 if (format == formats[i]) {
3561 exist = true;
3562 break;
3563 }
3564 }
3565 bool isSurroundFormat = false;
3566 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3567 if (SURROUND_FORMATS[i] == format) {
3568 isSurroundFormat = true;
3569 break;
3570 }
3571 }
3572 if (!exist && isSurroundFormat) {
3573 formats.add(format);
3574 }
3575 }
3576 return NO_ERROR;
3577}
3578
3579status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3580 audio_format_t *surroundFormats,
3581 bool *surroundFormatsEnabled,
3582 bool reported)
3583{
3584 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3585 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3586 return BAD_VALUE;
3587 }
3588 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3589 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3590
3591 // Only return value if there is HDMI output.
3592 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3593 return INVALID_OPERATION;
3594 }
3595
3596 size_t formatsWritten = 0;
3597 size_t formatsMax = *numSurroundFormats;
3598 *numSurroundFormats = 0;
3599 FormatVector formats;
3600 if (reported) {
3601 // Only get surround formats which are reported by device.
3602 // First list already open outputs that can be routed to this device
3603 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3604 SortedVector<audio_io_handle_t> outputs;
3605 bool reportedFormatFound = false;
3606 status_t status;
3607 sp<SwAudioOutputDescriptor> desc;
3608 for (size_t i = 0; i < mOutputs.size(); i++) {
3609 desc = mOutputs.valueAt(i);
3610 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3611 outputs.add(mOutputs.keyAt(i));
3612 }
3613 }
3614 // Open an output to query dynamic parameters.
3615 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3616 AUDIO_DEVICE_OUT_HDMI);
3617 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3618 String8 address = hdmiOutputDevices[i]->mAddress;
3619 for (const auto& hwModule : mHwModules) {
3620 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3621 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3622 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3623 profile->supportDeviceAddress(address)) {
3624 size_t j;
3625 for (j = 0; j < outputs.size(); j++) {
3626 desc = mOutputs.valueFor(outputs.itemAt(j));
3627 if (!desc->isDuplicated() && desc->mProfile == profile) {
3628 break;
3629 }
3630 }
3631 if (j != outputs.size()) {
3632 status = getSupportedFormats(outputs.itemAt(j), formats);
3633 reportedFormatFound |= (status == NO_ERROR);
3634 continue;
3635 }
3636
3637 if (!profile->canOpenNewIo()) {
3638 ALOGW("Max Output number %u already opened for this profile %s",
3639 profile->maxOpenCount, profile->getTagName().c_str());
3640 continue;
3641 }
3642
3643 ALOGV("opening output for device %08x with params %s profile %p name %s",
3644 device, address.string(), profile.get(), profile->getName().string());
3645 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3646 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3647 status_t status = desc->open(nullptr, device, address,
3648 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3649 &output);
3650
3651 if (status == NO_ERROR) {
3652 status = getSupportedFormats(output, formats);
3653 reportedFormatFound |= (status == NO_ERROR);
3654 desc->close();
3655 output = AUDIO_IO_HANDLE_NONE;
3656 }
3657 }
3658 }
3659 }
3660 }
3661
3662 if (!reportedFormatFound) {
3663 return UNKNOWN_ERROR;
3664 }
3665 } else {
3666 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3667 formats.add(SURROUND_FORMATS[i]);
3668 }
3669 }
3670 for (size_t i = 0; i < formats.size(); i++) {
3671 if (formatsWritten < formatsMax) {
3672 surroundFormats[formatsWritten] = formats[i];
3673 bool formatEnabled = false;
3674 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3675 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3676 formatEnabled =
3677 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3678 break;
3679 }
3680 } else {
3681 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3682 }
3683 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3684 }
3685 (*numSurroundFormats)++;
3686 }
3687 return NO_ERROR;
3688}
3689
3690status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3691{
3692 // Check if audio format is a surround formats.
3693 bool isSurroundFormat = false;
3694 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3695 if (audioFormat == SURROUND_FORMATS[i]) {
3696 isSurroundFormat = true;
3697 break;
3698 }
3699 }
3700 if (!isSurroundFormat) {
3701 return BAD_VALUE;
3702 }
3703
3704 // Should only be called when MANUAL.
3705 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3706 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3707 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3708 return INVALID_OPERATION;
3709 }
3710
3711 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3712 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3713 return NO_ERROR;
3714 }
3715
3716 // The operation is valid only when there is HDMI output available.
3717 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3718 return INVALID_OPERATION;
3719 }
3720
3721 if (enabled) {
3722 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3723 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3724 mSurroundFormats.insert(AAC_FORMATS[i]);
3725 }
3726 } else {
3727 mSurroundFormats.insert(audioFormat);
3728 }
3729 } else {
3730 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3731 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3732 mSurroundFormats.erase(AAC_FORMATS[i]);
3733 }
3734 } else {
3735 mSurroundFormats.erase(audioFormat);
3736 }
3737 }
3738
3739 sp<SwAudioOutputDescriptor> outputDesc;
3740 bool profileUpdated = false;
3741 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
3742 AUDIO_DEVICE_OUT_HDMI);
3743 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3744 // Simulate reconnection to update enabled surround sound formats.
3745 String8 address = hdmiOutputDevices[i]->mAddress;
3746 String8 name = hdmiOutputDevices[i]->getName();
3747 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3748 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3749 address.c_str(),
3750 name.c_str());
3751 if (status != NO_ERROR) {
3752 continue;
3753 }
3754 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3755 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3756 address.c_str(),
3757 name.c_str());
3758 profileUpdated |= (status == NO_ERROR);
3759 }
3760 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
3761 AUDIO_DEVICE_IN_HDMI);
3762 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3763 // Simulate reconnection to update enabled surround sound formats.
3764 String8 address = hdmiInputDevices[i]->mAddress;
3765 String8 name = hdmiInputDevices[i]->getName();
3766 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3767 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3768 address.c_str(),
3769 name.c_str());
3770 if (status != NO_ERROR) {
3771 continue;
3772 }
3773 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3774 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3775 address.c_str(),
3776 name.c_str());
3777 profileUpdated |= (status == NO_ERROR);
3778 }
3779
3780 // Undo the surround formats change due to no audio profiles updated.
3781 if (!profileUpdated) {
3782 if (enabled) {
3783 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3784 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3785 mSurroundFormats.erase(AAC_FORMATS[i]);
3786 }
3787 } else {
3788 mSurroundFormats.erase(audioFormat);
3789 }
3790 } else {
3791 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3792 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3793 mSurroundFormats.insert(AAC_FORMATS[i]);
3794 }
3795 } else {
3796 mSurroundFormats.insert(audioFormat);
3797 }
3798 }
3799 }
3800
3801 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3802}
3803
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003804void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3805{
3806 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3807
3808 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3809 for (size_t i = 0; i < activeInputs.size(); i++) {
3810 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3811 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3812 for (size_t j = 0; j < activeSessions.size(); j++) {
3813 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3814 if (activeSession->uid() == uid) {
3815 activeSession->setSilenced(silenced);
3816 }
3817 }
3818 }
3819}
3820
Eric Laurentd60560a2015-04-10 11:31:20 -07003821status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3822{
3823 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3824
3825 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3826 if (patchDesc == 0) {
3827 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3828 sourceDesc->mPatchDesc->mHandle);
3829 return BAD_VALUE;
3830 }
3831 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3832
Eric Laurent28d09f02016-03-08 10:43:05 -08003833 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003834 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3835 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003836 status_t status = stopSource(swOutputDesc, stream, false);
3837 if (status == NO_ERROR) {
3838 swOutputDesc->stop();
3839 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003840 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3841 } else {
3842 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3843 if (hwOutputDesc != 0) {
3844 // release patch between src device and output device
3845 // close Hwoutput and remove from mHwOutputs
3846 } else {
3847 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3848 }
3849 }
3850 return NO_ERROR;
3851}
3852
3853sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3854 audio_io_handle_t output, routing_strategy strategy)
3855{
3856 sp<AudioSourceDescriptor> source;
3857 for (size_t i = 0; i < mAudioSources.size(); i++) {
3858 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3859 routing_strategy sourceStrategy =
3860 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3861 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3862 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3863 source = sourceDesc;
3864 break;
3865 }
3866 }
3867 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003868}
3869
Eric Laurente552edb2014-03-10 17:42:56 -07003870// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003871// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003872// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003873uint32_t AudioPolicyManager::nextAudioPortGeneration()
3874{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003875 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003876}
3877
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003878#ifdef USE_XML_AUDIO_POLICY_CONF
3879// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3880static const char *kConfigLocationList[] =
3881 {"/odm/etc", "/vendor/etc", "/system/etc"};
3882static const int kConfigLocationListSize =
3883 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3884
3885static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3886 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003887 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003888 status_t ret;
3889
Petri Gyntherf497f292018-04-17 18:46:10 -07003890 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3891 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3892 // A2DP offload supported but disabled: try to use special XML file
3893 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3894 }
3895 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3896
3897 for (const char* fileName : fileNames) {
3898 for (int i = 0; i < kConfigLocationListSize; i++) {
3899 PolicySerializer serializer;
3900 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3901 "%s/%s", kConfigLocationList[i], fileName);
3902 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3903 if (ret == NO_ERROR) {
3904 return ret;
3905 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003906 }
3907 }
3908 return ret;
3909}
3910#endif
3911
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003912AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3913 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003914 :
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003915 mUidCached(getuid()),
3916 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003917 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003918 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003919#ifdef USE_XML_AUDIO_POLICY_CONF
3920 mVolumeCurves(new VolumeCurvesCollection()),
3921 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003922 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003923#else
3924 mVolumeCurves(new StreamDescriptorCollection()),
3925 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3926 mDefaultOutputDevice),
3927#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003928 mAudioPortGeneration(1),
3929 mBeaconMuteRefCount(0),
3930 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003931 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003932 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003933 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003934 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3935 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003936{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003937}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003938
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003939AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3940 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3941{
3942 loadConfig();
3943 initialize();
3944}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003945
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003946void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003947#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003948 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003949#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003950 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3951 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003952#endif
3953 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003954 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003955 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003956}
3957
3958status_t AudioPolicyManager::initialize() {
3959 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003960
3961 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003962 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3963 if (!engineInstance) {
3964 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003965 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003966 }
3967 // Retrieve the Policy Manager Interface
3968 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3969 if (mEngine == NULL) {
3970 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003971 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003972 }
3973 mEngine->setObserver(this);
3974 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003975 if (status != NO_ERROR) {
3976 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3977 return status;
3978 }
François Gaffie2110e042015-03-24 08:41:51 +01003979
Eric Laurent3a4311c2014-03-17 12:00:47 -07003980 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003981 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003982 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3983 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003984 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003985 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003986 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3987 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003988 continue;
3989 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003990 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003991 // open all output streams needed to access attached devices
3992 // except for direct output streams that are only opened when they are actually
3993 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003994 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003995 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003996 if (!outProfile->canOpenNewIo()) {
3997 ALOGE("Invalid Output profile max open count %u for profile %s",
3998 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3999 continue;
4000 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004001 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004002 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004003 continue;
4004 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004005 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004006 mTtsOutputAvailable = true;
4007 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004009 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004010 continue;
4011 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004012 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01004013 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
4014 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07004015 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004016 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004017 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004018 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07004019 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004020 if ((profileType & outputDeviceTypes) == 0) {
4021 continue;
4022 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004023 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4024 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07004025 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4026 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
4027 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
4028 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07004029 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004030 status_t status = outputDesc->open(nullptr, profileType, address,
4031 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004032
4033 if (status != NO_ERROR) {
4034 ALOGW("Cannot open output stream for device %08x on hw module %s",
4035 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004036 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004037 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004038 for (const auto& dev : supportedDevices) {
4039 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004040 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08004041 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004042 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07004043 }
4044 }
4045 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004046 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004047 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07004048 }
4049 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004050 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08004051 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07004052 true,
4053 0,
4054 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08004055 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07004056 }
Eric Laurente552edb2014-03-10 17:42:56 -07004057 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004058 // open input streams needed to access attached devices to validate
4059 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004060 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004061 if (!inProfile->canOpenNewIo()) {
4062 ALOGE("Invalid Input profile max open count %u for profile %s",
4063 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4064 continue;
4065 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004066 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004067 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 continue;
4069 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004070 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004071 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004072 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4073
Eric Laurentd78f1532014-09-16 16:38:20 -07004074 if ((profileType & inputDeviceTypes) == 0) {
4075 continue;
4076 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004077 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004078 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004079
Eric Laurent53b810e2017-12-10 17:25:10 -08004080 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
4081 // the inputs vector must be of size >= 1, but we don't want to crash here
4082 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4083 : String8("");
4084 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4085 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4086
Eric Laurentd78f1532014-09-16 16:38:20 -07004087 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004088 status_t status = inputDesc->open(nullptr,
4089 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004090 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004091 AUDIO_SOURCE_MIC,
4092 AUDIO_INPUT_FLAG_NONE,
4093 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004094
4095 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004096 for (const auto& dev : inProfile->getSupportedDevices()) {
4097 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004098 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004099 if (index >= 0) {
4100 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4101 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004102 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004103 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004104 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004105 }
4106 }
Eric Laurentfe231122017-11-17 17:48:06 -08004107 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004108 } else {
4109 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004110 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004111 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004112 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 }
4114 }
4115 // make sure all attached devices have been allocated a unique ID
4116 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004117 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004118 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004119 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4120 continue;
4121 }
François Gaffie2110e042015-03-24 08:41:51 +01004122 // The device is now validated and can be appended to the available devices of the engine
4123 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4124 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004125 i++;
4126 }
4127 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004128 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004129 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004130 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4131 continue;
4132 }
François Gaffie2110e042015-03-24 08:41:51 +01004133 // The device is now validated and can be appended to the available devices of the engine
4134 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4135 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004136 i++;
4137 }
4138 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004139 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004140 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004141 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004142 }
jiabin9ff780e2018-03-19 18:19:52 -07004143 // If microphones address is empty, set it according to device type
4144 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4145 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4146 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4147 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4148 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4149 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4150 }
4151 }
4152 }
Eric Laurente552edb2014-03-10 17:42:56 -07004153
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004154 if (mPrimaryOutput == 0) {
4155 ALOGE("Failed to open primary output");
4156 status = NO_INIT;
4157 }
Eric Laurente552edb2014-03-10 17:42:56 -07004158
4159 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004160 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004161}
4162
Eric Laurente0720872014-03-11 09:30:41 -07004163AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004164{
Eric Laurente552edb2014-03-10 17:42:56 -07004165 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004166 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004167 }
4168 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004169 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004170 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004171 mAvailableOutputDevices.clear();
4172 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004173 mOutputs.clear();
4174 mInputs.clear();
4175 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004176 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004177 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004178}
4179
Eric Laurente0720872014-03-11 09:30:41 -07004180status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004181{
Eric Laurent87ffa392015-05-22 10:32:38 -07004182 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004183}
4184
Eric Laurente552edb2014-03-10 17:42:56 -07004185// ---
4186
Eric Laurent98e38192018-02-15 18:31:53 -08004187void AudioPolicyManager::addOutput(audio_io_handle_t output,
4188 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004189{
Eric Laurent1c333e22014-05-20 10:48:17 -07004190 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004191 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004192 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004193 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004194 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004195}
4196
François Gaffie53615e22015-03-19 09:24:12 +01004197void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4198{
4199 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004200 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004201}
4202
Eric Laurent98e38192018-02-15 18:31:53 -08004203void AudioPolicyManager::addInput(audio_io_handle_t input,
4204 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004205{
Eric Laurent1c333e22014-05-20 10:48:17 -07004206 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004208}
Eric Laurente552edb2014-03-10 17:42:56 -07004209
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004210void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004211 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004212 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004213 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004214 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004215 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004216 if (devDesc != 0) {
4217 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4218 desc->mIoHandle, address.string());
4219 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004220 }
4221}
4222
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004223status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004224 audio_policy_dev_state_t state,
4225 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004226 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004227{
François Gaffie53615e22015-03-19 09:24:12 +01004228 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004229 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004230
4231 if (audio_device_is_digital(device)) {
4232 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004233 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004234 }
Eric Laurente552edb2014-03-10 17:42:56 -07004235
Eric Laurent3b73df72014-03-11 09:06:29 -07004236 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004237 // first list already open outputs that can be routed to this device
4238 for (size_t i = 0; i < mOutputs.size(); i++) {
4239 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004240 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004241 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004242 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4243 outputs.add(mOutputs.keyAt(i));
4244 } else {
4245 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004246 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004247 }
Eric Laurente552edb2014-03-10 17:42:56 -07004248 }
4249 }
4250 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004251 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004252 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004253 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4254 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004255 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004256 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004257 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004258 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004259 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4260 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004261 }
Eric Laurente552edb2014-03-10 17:42:56 -07004262 }
4263 }
4264 }
4265
Eric Laurent7b279bb2015-12-14 10:18:23 -08004266 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004267
Eric Laurente552edb2014-03-10 17:42:56 -07004268 if (profiles.isEmpty() && outputs.isEmpty()) {
4269 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4270 return BAD_VALUE;
4271 }
4272
4273 // open outputs for matching profiles if needed. Direct outputs are also opened to
4274 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4275 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004276 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004277
4278 // nothing to do if one output is already opened for this profile
4279 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004280 for (j = 0; j < outputs.size(); j++) {
4281 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004282 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004283 // matching profile: save the sample rates, format and channel masks supported
4284 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004285 if (audio_device_is_digital(device)) {
4286 devDesc->importAudioPort(profile);
4287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 break;
4289 }
4290 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004291 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004292 continue;
4293 }
4294
Eric Laurent3974e3b2017-12-07 17:58:43 -08004295 if (!profile->canOpenNewIo()) {
4296 ALOGW("Max Output number %u already opened for this profile %s",
4297 profile->maxOpenCount, profile->getTagName().c_str());
4298 continue;
4299 }
4300
Eric Laurent83efe1c2017-07-09 16:51:08 -07004301 ALOGV("opening output for device %08x with params %s profile %p name %s",
4302 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004303 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004304 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004305 status_t status = desc->open(nullptr, device, address,
4306 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004307
Eric Laurentfe231122017-11-17 17:48:06 -08004308 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004309 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004310 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004311 char *param = audio_device_address_to_parameter(device, address);
4312 mpClientInterface->setParameters(output, String8(param));
4313 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004314 }
Phil Burk00eeb322016-03-31 12:41:00 -07004315 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004316 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004317 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004318 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004320 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004321 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004322 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004323 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4324 profile->pickAudioProfile(
4325 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004326 config.offload_info.sample_rate = config.sample_rate;
4327 config.offload_info.channel_mask = config.channel_mask;
4328 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004329
4330 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4331 AUDIO_OUTPUT_FLAG_NONE, &output);
4332 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004333 output = AUDIO_IO_HANDLE_NONE;
4334 }
Eric Laurentd4692962014-05-05 18:13:44 -07004335 }
4336
Eric Laurentcf2c0212014-07-25 16:20:43 -07004337 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004338 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004339 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004340 sp<AudioPolicyMix> policyMix;
4341 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004342 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4343 address.string());
4344 }
François Gaffie036e1e92015-03-19 10:16:24 +01004345 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004346 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004347
Eric Laurent87ffa392015-05-22 10:32:38 -07004348 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4349 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004350 // no duplicated output for direct outputs and
4351 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004352 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004353
Eric Laurentd4692962014-05-05 18:13:44 -07004354 //TODO: configure audio effect output stage here
4355
4356 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004357 sp<SwAudioOutputDescriptor> dupOutputDesc =
4358 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4359 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4360 &duplicatedOutput);
4361 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004362 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004363 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004364 } else {
4365 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004366 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004367 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004368 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004369 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004370 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004371 }
Eric Laurente552edb2014-03-10 17:42:56 -07004372 }
4373 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004374 } else {
4375 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004376 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004377 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004378 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004379 profiles.removeAt(profile_index);
4380 profile_index--;
4381 } else {
4382 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004383 // Load digital format info only for digital devices
4384 if (audio_device_is_digital(device)) {
4385 devDesc->importAudioPort(profile);
4386 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004387
François Gaffie53615e22015-03-19 09:24:12 +01004388 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004389 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4390 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004391 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004392 NULL/*patch handle*/, address.string());
4393 }
Eric Laurente552edb2014-03-10 17:42:56 -07004394 ALOGV("checkOutputsForDevice(): adding output %d", output);
4395 }
4396 }
4397
4398 if (profiles.isEmpty()) {
4399 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4400 return BAD_VALUE;
4401 }
Eric Laurentd4692962014-05-05 18:13:44 -07004402 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004403 // check if one opened output is not needed any more after disconnecting one device
4404 for (size_t i = 0; i < mOutputs.size(); i++) {
4405 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004406 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004407 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004408 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004409 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004410 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004411 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004412 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4413 mOutputs.keyAt(i));
4414 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004415 }
Eric Laurente552edb2014-03-10 17:42:56 -07004416 }
4417 }
Eric Laurentd4692962014-05-05 18:13:44 -07004418 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004419 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004420 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4421 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004422 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004423 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004424 "clearing direct output profile %zu on module %s",
4425 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004426 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004427 }
4428 }
4429 }
4430 }
4431 return NO_ERROR;
4432}
4433
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004434status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004435 audio_policy_dev_state_t state,
4436 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004437 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004438{
Paul McLean9080a4c2015-06-18 08:24:02 -07004439 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004440 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004441
4442 if (audio_device_is_digital(device)) {
4443 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004444 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004445 }
4446
Eric Laurentd4692962014-05-05 18:13:44 -07004447 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4448 // first list already open inputs that can be routed to this device
4449 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4450 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004451 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004452 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4453 inputs.add(mInputs.keyAt(input_index));
4454 }
4455 }
4456
4457 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004458 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004459 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004460 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004461 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004462 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004463 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004464
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004465 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004466 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004467 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004468 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004469 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4470 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004471 }
Eric Laurentd4692962014-05-05 18:13:44 -07004472 }
4473 }
4474 }
4475
4476 if (profiles.isEmpty() && inputs.isEmpty()) {
4477 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4478 return BAD_VALUE;
4479 }
4480
4481 // open inputs for matching profiles if needed. Direct inputs are also opened to
4482 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4483 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4484
Eric Laurent1c333e22014-05-20 10:48:17 -07004485 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004486
Eric Laurentd4692962014-05-05 18:13:44 -07004487 // nothing to do if one input is already opened for this profile
4488 size_t input_index;
4489 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4490 desc = mInputs.valueAt(input_index);
4491 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004492 if (audio_device_is_digital(device)) {
4493 devDesc->importAudioPort(profile);
4494 }
Eric Laurentd4692962014-05-05 18:13:44 -07004495 break;
4496 }
4497 }
4498 if (input_index != mInputs.size()) {
4499 continue;
4500 }
4501
Eric Laurent3974e3b2017-12-07 17:58:43 -08004502 if (!profile->canOpenNewIo()) {
4503 ALOGW("Max Input number %u already opened for this profile %s",
4504 profile->maxOpenCount, profile->getTagName().c_str());
4505 continue;
4506 }
4507
Eric Laurentfe231122017-11-17 17:48:06 -08004508 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004509 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004510 status_t status = desc->open(nullptr,
4511 device,
4512 address,
4513 AUDIO_SOURCE_MIC,
4514 AUDIO_INPUT_FLAG_NONE,
4515 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004516
Eric Laurentcf2c0212014-07-25 16:20:43 -07004517 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004518 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004519 char *param = audio_device_address_to_parameter(device, address);
4520 mpClientInterface->setParameters(input, String8(param));
4521 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004522 }
Phil Burk00eeb322016-03-31 12:41:00 -07004523 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004524 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004525 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004526 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004527 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004528 }
4529
4530 if (input != 0) {
4531 addInput(input, desc);
4532 }
4533 } // endif input != 0
4534
Eric Laurentcf2c0212014-07-25 16:20:43 -07004535 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004536 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004537 profiles.removeAt(profile_index);
4538 profile_index--;
4539 } else {
4540 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004541 if (audio_device_is_digital(device)) {
4542 devDesc->importAudioPort(profile);
4543 }
Eric Laurentd4692962014-05-05 18:13:44 -07004544 ALOGV("checkInputsForDevice(): adding input %d", input);
4545 }
4546 } // end scan profiles
4547
4548 if (profiles.isEmpty()) {
4549 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4550 return BAD_VALUE;
4551 }
4552 } else {
4553 // Disconnect
4554 // check if one opened input is not needed any more after disconnecting one device
4555 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4556 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004557 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004558 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4559 mInputs.keyAt(input_index));
4560 inputs.add(mInputs.keyAt(input_index));
4561 }
4562 }
4563 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004564 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004565 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004566 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004567 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004568 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004569 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004570 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4571 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004572 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004573 }
4574 }
4575 }
4576 } // end disconnect
4577
4578 return NO_ERROR;
4579}
4580
4581
Eric Laurente0720872014-03-11 09:30:41 -07004582void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004583{
4584 ALOGV("closeOutput(%d)", output);
4585
Eric Laurentc75307b2015-03-17 15:29:32 -07004586 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004587 if (outputDesc == NULL) {
4588 ALOGW("closeOutput() unknown output %d", output);
4589 return;
4590 }
François Gaffie036e1e92015-03-19 10:16:24 +01004591 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004592
Eric Laurente552edb2014-03-10 17:42:56 -07004593 // look for duplicated outputs connected to the output being removed.
4594 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004595 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004596 if (dupOutputDesc->isDuplicated() &&
4597 (dupOutputDesc->mOutput1 == outputDesc ||
4598 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004599 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004600 if (dupOutputDesc->mOutput1 == outputDesc) {
4601 outputDesc2 = dupOutputDesc->mOutput2;
4602 } else {
4603 outputDesc2 = dupOutputDesc->mOutput1;
4604 }
4605 // As all active tracks on duplicated output will be deleted,
4606 // and as they were also referenced on the other output, the reference
4607 // count for their stream type must be adjusted accordingly on
4608 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004609 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004610 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004611 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004612 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004613 }
Eric Laurent733ce942017-12-07 12:18:25 -08004614 // stop() will be a no op if the output is still active but is needed in case all
4615 // active streams refcounts where cleared above
4616 if (wasActive) {
4617 outputDesc2->stop();
4618 }
Eric Laurente552edb2014-03-10 17:42:56 -07004619 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4620 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4621
4622 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004623 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004624 }
4625 }
4626
Eric Laurent05b90f82014-08-27 15:32:29 -07004627 nextAudioPortGeneration();
4628
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004629 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004630 if (index >= 0) {
4631 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004632 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004633 mAudioPatches.removeItemsAt(index);
4634 mpClientInterface->onAudioPatchListUpdate();
4635 }
4636
Eric Laurentfe231122017-11-17 17:48:06 -08004637 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004638
François Gaffie53615e22015-03-19 09:24:12 +01004639 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004640 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004641}
4642
4643void AudioPolicyManager::closeInput(audio_io_handle_t input)
4644{
4645 ALOGV("closeInput(%d)", input);
4646
4647 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4648 if (inputDesc == NULL) {
4649 ALOGW("closeInput() unknown input %d", input);
4650 return;
4651 }
4652
Eric Laurent6a94d692014-05-20 11:18:06 -07004653 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004654
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004655 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004656 if (index >= 0) {
4657 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004658 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004659 mAudioPatches.removeItemsAt(index);
4660 mpClientInterface->onAudioPatchListUpdate();
4661 }
4662
Eric Laurentfe231122017-11-17 17:48:06 -08004663 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004664 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004665}
4666
Eric Laurentc75307b2015-03-17 15:29:32 -07004667SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4668 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004669 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004670{
4671 SortedVector<audio_io_handle_t> outputs;
4672
4673 ALOGVV("getOutputsForDevice() device %04x", device);
4674 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004675 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004676 i, openOutputs.valueAt(i)->isDuplicated(),
4677 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004678 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4679 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4680 outputs.add(openOutputs.keyAt(i));
4681 }
4682 }
4683 return outputs;
4684}
4685
Eric Laurente0720872014-03-11 09:30:41 -07004686bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004687 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004688{
4689 if (outputs1.size() != outputs2.size()) {
4690 return false;
4691 }
4692 for (size_t i = 0; i < outputs1.size(); i++) {
4693 if (outputs1[i] != outputs2[i]) {
4694 return false;
4695 }
4696 }
4697 return true;
4698}
4699
Eric Laurente0720872014-03-11 09:30:41 -07004700void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004701{
4702 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4703 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4704 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4705 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4706
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004707 // also take into account external policy-related changes: add all outputs which are
4708 // associated with policies in the "before" and "after" output vectors
4709 ALOGVV("checkOutputForStrategy(): policy related outputs");
4710 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004711 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004712 if (desc != 0 && desc->mPolicyMix != NULL) {
4713 srcOutputs.add(desc->mIoHandle);
4714 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4715 }
4716 }
4717 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004718 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004719 if (desc != 0 && desc->mPolicyMix != NULL) {
4720 dstOutputs.add(desc->mIoHandle);
4721 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4722 }
4723 }
4724
Eric Laurente552edb2014-03-10 17:42:56 -07004725 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004726 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4727 // audio from invalidated tracks will be rendered when unmuting
4728 uint32_t maxLatency = 0;
4729 for (audio_io_handle_t srcOut : srcOutputs) {
4730 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4731 if (desc != 0 && maxLatency < desc->latency()) {
4732 maxLatency = desc->latency();
4733 }
4734 }
Eric Laurente552edb2014-03-10 17:42:56 -07004735 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4736 strategy, srcOutputs[0], dstOutputs[0]);
4737 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004738 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004739 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4740 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004741 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004742 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004743 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004744 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004745 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004746 if (source != 0){
4747 connectAudioSource(source);
4748 }
Eric Laurente552edb2014-03-10 17:42:56 -07004749 }
4750
4751 // Move effects associated to this strategy from previous output to new output
4752 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004753 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004754 }
4755 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004756 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004757 if (getStrategy((audio_stream_type_t)i) == strategy) {
4758 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004759 }
4760 }
4761 }
4762}
4763
Eric Laurente0720872014-03-11 09:30:41 -07004764void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004765{
François Gaffie2110e042015-03-24 08:41:51 +01004766 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004767 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004768 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004769 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004770 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004771 checkOutputForStrategy(STRATEGY_SONIFICATION);
4772 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004773 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004774 checkOutputForStrategy(STRATEGY_MEDIA);
4775 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004776 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004777}
4778
Eric Laurente0720872014-03-11 09:30:41 -07004779void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004780{
François Gaffie53615e22015-03-19 09:24:12 +01004781 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004782 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004783 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004784 return;
4785 }
4786
Eric Laurent3a4311c2014-03-17 12:00:47 -07004787 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004788 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4789 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4790 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004791
4792 // if suspended, restore A2DP output if:
4793 // ((SCO device is NOT connected) ||
4794 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4795 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004796 //
Eric Laurentf732e072016-08-03 19:30:28 -07004797 // if not suspended, suspend A2DP output if:
4798 // (SCO device is connected) &&
4799 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4800 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004801 //
4802 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004803 if (!isScoConnected ||
4804 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4805 AUDIO_POLICY_FORCE_BT_SCO) &&
4806 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4807 AUDIO_POLICY_FORCE_BT_SCO) &&
4808 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004809 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004810
4811 mpClientInterface->restoreOutput(a2dpOutput);
4812 mA2dpSuspended = false;
4813 }
4814 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004815 if (isScoConnected &&
4816 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4817 AUDIO_POLICY_FORCE_BT_SCO) ||
4818 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4819 AUDIO_POLICY_FORCE_BT_SCO) ||
4820 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004821 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004822
4823 mpClientInterface->suspendOutput(a2dpOutput);
4824 mA2dpSuspended = true;
4825 }
4826 }
4827}
4828
Eric Laurentc75307b2015-03-17 15:29:32 -07004829audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4830 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004831{
4832 audio_devices_t device = AUDIO_DEVICE_NONE;
4833
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004834 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004835 if (index >= 0) {
4836 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4837 if (patchDesc->mUid != mUidCached) {
4838 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004839 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 return outputDesc->device();
4841 }
4842 }
4843
Eric Laurente552edb2014-03-10 17:42:56 -07004844 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004845 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004846 // use device for strategy enforced audible
4847 // 2: we are in call or the strategy phone is active on the output:
4848 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004849 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004850 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004851 // 4: the strategy for enforced audible is active but not enforced on the output:
4852 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004853 // 5: the strategy accessibility is active on the output:
4854 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004855 // 6: the strategy "respectful" sonification is active on the output:
4856 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004857 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004858 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004859 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004860 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004861 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004862 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004863 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004864 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004865 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4866 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004867 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004868 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004869 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004871 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4872 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004873 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4874 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004875 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004876 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004877 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004878 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004879 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004880 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004881 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004882 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004883 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004884 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004885 }
4886
Eric Laurent1c333e22014-05-20 10:48:17 -07004887 ALOGV("getNewOutputDevice() selected device %x", device);
4888 return device;
4889}
4890
Eric Laurentfb66dd92016-01-28 18:32:03 -08004891audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004892{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004893 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004894
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004895 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 if (index >= 0) {
4897 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4898 if (patchDesc->mUid != mUidCached) {
4899 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004900 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004901 return inputDesc->mDevice;
4902 }
4903 }
4904
Eric Laurentdc95a252018-04-12 12:46:56 -07004905 // If we are not in call and no client is active on this input, this methods returns
4906 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004907 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004908 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4909 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4910 }
4911 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004912 device = getDeviceAndMixForInputSource(source);
4913 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004914
Eric Laurente552edb2014-03-10 17:42:56 -07004915 return device;
4916}
4917
Eric Laurent794fde22016-03-11 09:50:45 -08004918bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4919 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004920 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004921}
4922
Eric Laurente0720872014-03-11 09:30:41 -07004923uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004924 return (uint32_t)getStrategy(stream);
4925}
4926
Eric Laurente0720872014-03-11 09:30:41 -07004927audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004928 // By checking the range of stream before calling getStrategy, we avoid
4929 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4930 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004931 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 return AUDIO_DEVICE_NONE;
4933 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004934 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004935 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4936 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004937 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 }
Eric Laurent794fde22016-03-11 09:50:45 -08004939 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004940 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004941 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004942 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4943 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004944 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004945 curDevices |= outputDesc->device();
4946 }
4947 }
4948 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004949 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004950
4951 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4952 and doesn't really need to.*/
4953 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4954 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4955 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4956 }
Eric Laurente552edb2014-03-10 17:42:56 -07004957 return devices;
4958}
4959
François Gaffie2110e042015-03-24 08:41:51 +01004960routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4961{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004962 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004963 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004964}
4965
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004966uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4967 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004968 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4969 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4970 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004971 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4972 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4973 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004974 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004975 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004976}
4977
Eric Laurente0720872014-03-11 09:30:41 -07004978void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004979 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004980 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004981 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4982 updateDevicesAndOutputs();
4983 break;
4984 default:
4985 break;
4986 }
4987}
4988
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004989uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004990
4991 // skip beacon mute management if a dedicated TTS output is available
4992 if (mTtsOutputAvailable) {
4993 return 0;
4994 }
4995
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004996 switch(event) {
4997 case STARTING_OUTPUT:
4998 mBeaconMuteRefCount++;
4999 break;
5000 case STOPPING_OUTPUT:
5001 if (mBeaconMuteRefCount > 0) {
5002 mBeaconMuteRefCount--;
5003 }
5004 break;
5005 case STARTING_BEACON:
5006 mBeaconPlayingRefCount++;
5007 break;
5008 case STOPPING_BEACON:
5009 if (mBeaconPlayingRefCount > 0) {
5010 mBeaconPlayingRefCount--;
5011 }
5012 break;
5013 }
5014
5015 if (mBeaconMuteRefCount > 0) {
5016 // any playback causes beacon to be muted
5017 return setBeaconMute(true);
5018 } else {
5019 // no other playback: unmute when beacon starts playing, mute when it stops
5020 return setBeaconMute(mBeaconPlayingRefCount == 0);
5021 }
5022}
5023
5024uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5025 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5026 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5027 // keep track of muted state to avoid repeating mute/unmute operations
5028 if (mBeaconMuted != mute) {
5029 // mute/unmute AUDIO_STREAM_TTS on all outputs
5030 ALOGV("\t muting %d", mute);
5031 uint32_t maxLatency = 0;
5032 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005033 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005034 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005035 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005036 0 /*delay*/, AUDIO_DEVICE_NONE);
5037 const uint32_t latency = desc->latency() * 2;
5038 if (latency > maxLatency) {
5039 maxLatency = latency;
5040 }
5041 }
5042 mBeaconMuted = mute;
5043 return maxLatency;
5044 }
5045 return 0;
5046}
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005049 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005050{
Paul McLeanaa981192015-03-21 09:55:15 -07005051 // Routing
5052 // see if we have an explicit route
5053 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
5054 // (getStrategy(stream)).
5055 // if the strategy from the stream type in the RouteMap is the same as the argument above,
Eric Laurentad2e7b92017-09-14 20:06:42 -07005056 // and activity count is non-zero and the device in the route descriptor is available
5057 // then select this device.
Paul McLeanaa981192015-03-21 09:55:15 -07005058 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
5059 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08005060 routing_strategy routeStrategy = getStrategy(route->mStreamType);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005061 if ((routeStrategy == strategy) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005062 (mAvailableOutputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLeanaa981192015-03-21 09:55:15 -07005063 return route->mDeviceDescriptor->type();
5064 }
5065 }
5066
Eric Laurente552edb2014-03-10 17:42:56 -07005067 if (fromCache) {
5068 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5069 strategy, mDeviceForStrategy[strategy]);
5070 return mDeviceForStrategy[strategy];
5071 }
François Gaffie2110e042015-03-24 08:41:51 +01005072 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005073}
5074
Eric Laurente0720872014-03-11 09:30:41 -07005075void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005076{
5077 for (int i = 0; i < NUM_STRATEGIES; i++) {
5078 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5079 }
5080 mPreviousOutputs = mOutputs;
5081}
5082
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005083uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005084 audio_devices_t prevDevice,
5085 uint32_t delayMs)
5086{
5087 // mute/unmute strategies using an incompatible device combination
5088 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5089 // if unmuting, unmute only after the specified delay
5090 if (outputDesc->isDuplicated()) {
5091 return 0;
5092 }
5093
5094 uint32_t muteWaitMs = 0;
5095 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005096 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005097
5098 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5099 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005100 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005101 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5102 bool doMute = false;
5103
5104 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5105 doMute = true;
5106 outputDesc->mStrategyMutedByDevice[i] = true;
5107 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5108 doMute = true;
5109 outputDesc->mStrategyMutedByDevice[i] = false;
5110 }
Eric Laurent99401132014-05-07 19:48:15 -07005111 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005112 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005113 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005114 // skip output if it does not share any device with current output
5115 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5116 == AUDIO_DEVICE_NONE) {
5117 continue;
5118 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005119 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005120 mute ? "muting" : "unmuting", i, curDevice);
5121 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005122 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005123 if (mute) {
5124 // FIXME: should not need to double latency if volume could be applied
5125 // immediately by the audioflinger mixer. We must account for the delay
5126 // between now and the next time the audioflinger thread for this output
5127 // will process a buffer (which corresponds to one buffer size,
5128 // usually 1/2 or 1/4 of the latency).
5129 if (muteWaitMs < desc->latency() * 2) {
5130 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005131 }
5132 }
5133 }
5134 }
5135 }
5136 }
5137
Eric Laurent99401132014-05-07 19:48:15 -07005138 // temporary mute output if device selection changes to avoid volume bursts due to
5139 // different per device volumes
5140 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005141 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5142 // temporary mute duration is conservatively set to 4 times the reported latency
5143 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5144 if (muteWaitMs < tempMuteWaitMs) {
5145 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005146 }
Eric Laurentdc462862016-07-19 12:29:53 -07005147
Eric Laurent99401132014-05-07 19:48:15 -07005148 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005149 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005150 // make sure that we do not start the temporary mute period too early in case of
5151 // delayed device change
5152 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005153 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005154 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005155 }
5156 }
5157 }
5158
Eric Laurente552edb2014-03-10 17:42:56 -07005159 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5160 if (muteWaitMs > delayMs) {
5161 muteWaitMs -= delayMs;
5162 usleep(muteWaitMs * 1000);
5163 return muteWaitMs;
5164 }
5165 return 0;
5166}
5167
Eric Laurentc75307b2015-03-17 15:29:32 -07005168uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005169 audio_devices_t device,
5170 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005172 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005173 const char *address,
5174 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005175{
Eric Laurentc75307b2015-03-17 15:29:32 -07005176 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005177 AudioParameter param;
5178 uint32_t muteWaitMs;
5179
5180 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005181 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5182 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5183 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5184 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 return muteWaitMs;
5186 }
5187 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5188 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005189 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005190 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005191 return 0;
5192 }
5193
5194 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005196
5197 audio_devices_t prevDevice = outputDesc->mDevice;
5198
Paul McLeanaa981192015-03-21 09:55:15 -07005199 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005200
5201 if (device != AUDIO_DEVICE_NONE) {
5202 outputDesc->mDevice = device;
5203 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005204
5205 // if the outputs are not materially active, there is no need to mute.
5206 if (requiresMuteCheck) {
5207 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5208 } else {
5209 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5210 muteWaitMs = 0;
5211 }
Eric Laurente552edb2014-03-10 17:42:56 -07005212
5213 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005214 // the requested device is AUDIO_DEVICE_NONE
5215 // OR the requested device is the same as current device
5216 // AND force is not specified
5217 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005218 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005219 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5220 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005221 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005222 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005223 return muteWaitMs;
5224 }
5225
5226 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005227
Eric Laurente552edb2014-03-10 17:42:56 -07005228 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005229 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005231 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005232 DeviceVector deviceList;
5233 if ((address == NULL) || (strlen(address) == 0)) {
5234 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5235 } else {
5236 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5237 }
5238
Eric Laurent1c333e22014-05-20 10:48:17 -07005239 if (!deviceList.isEmpty()) {
5240 struct audio_patch patch;
5241 outputDesc->toAudioPortConfig(&patch.sources[0]);
5242 patch.num_sources = 1;
5243 patch.num_sinks = 0;
5244 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5245 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005246 patch.num_sinks++;
5247 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 ssize_t index;
5249 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5250 index = mAudioPatches.indexOfKey(*patchHandle);
5251 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005252 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 }
5254 sp< AudioPatch> patchDesc;
5255 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5256 if (index >= 0) {
5257 patchDesc = mAudioPatches.valueAt(index);
5258 afPatchHandle = patchDesc->mAfPatchHandle;
5259 }
5260
Eric Laurent1c333e22014-05-20 10:48:17 -07005261 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 &afPatchHandle,
5263 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5265 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005267 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005269 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 addAudioPatch(patchDesc->mHandle, patchDesc);
5271 } else {
5272 patchDesc->mPatch = patch;
5273 }
5274 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 if (patchHandle) {
5276 *patchHandle = patchDesc->mHandle;
5277 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005278 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005280 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005281 }
5282 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005283
5284 // inform all input as well
5285 for (size_t i = 0; i < mInputs.size(); i++) {
5286 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005287 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005288 AudioParameter inputCmd = AudioParameter();
5289 ALOGV("%s: inform input %d of device:%d", __func__,
5290 inputDescriptor->mIoHandle, device);
5291 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5292 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5293 inputCmd.toString(),
5294 delayMs);
5295 }
5296 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005297 }
Eric Laurente552edb2014-03-10 17:42:56 -07005298
5299 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005300 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005301
5302 return muteWaitMs;
5303}
5304
Eric Laurentc75307b2015-03-17 15:29:32 -07005305status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 int delayMs,
5307 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005308{
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 ssize_t index;
5310 if (patchHandle) {
5311 index = mAudioPatches.indexOfKey(*patchHandle);
5312 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005313 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 }
5315 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005316 return INVALID_OPERATION;
5317 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5319 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005320 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005321 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 removeAudioPatch(patchDesc->mHandle);
5323 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005324 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005325 return status;
5326}
5327
5328status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5329 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 bool force,
5331 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005332{
5333 status_t status = NO_ERROR;
5334
Eric Laurent1f2f2232014-06-02 12:01:23 -07005335 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005336 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5337 inputDesc->mDevice = device;
5338
5339 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5340 if (!deviceList.isEmpty()) {
5341 struct audio_patch patch;
5342 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005343 // AUDIO_SOURCE_HOTWORD is for internal use only:
5344 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005345 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005346 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005347 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5348 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005349 patch.num_sinks = 1;
5350 //only one input device for now
5351 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005353 ssize_t index;
5354 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5355 index = mAudioPatches.indexOfKey(*patchHandle);
5356 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005357 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 }
5359 sp< AudioPatch> patchDesc;
5360 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5361 if (index >= 0) {
5362 patchDesc = mAudioPatches.valueAt(index);
5363 afPatchHandle = patchDesc->mAfPatchHandle;
5364 }
5365
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005368 0);
5369 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005371 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005373 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 addAudioPatch(patchDesc->mHandle, patchDesc);
5375 } else {
5376 patchDesc->mPatch = patch;
5377 }
5378 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005379 if (patchHandle) {
5380 *patchHandle = patchDesc->mHandle;
5381 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005382 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005384 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005385 }
5386 }
5387 }
5388 return status;
5389}
5390
Eric Laurent6a94d692014-05-20 11:18:06 -07005391status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5392 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005393{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005394 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 ssize_t index;
5396 if (patchHandle) {
5397 index = mAudioPatches.indexOfKey(*patchHandle);
5398 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005399 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005400 }
5401 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005402 return INVALID_OPERATION;
5403 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5405 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005406 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005407 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 removeAudioPatch(patchDesc->mHandle);
5409 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005410 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005411 return status;
5412}
5413
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005414sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005415 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005416 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005417 audio_format_t& format,
5418 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005419 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005420{
5421 // Choose an input profile based on the requested capture parameters: select the first available
5422 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005423 //
5424 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5425 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005426
Glenn Kasten730b9262018-03-29 15:01:26 -07005427 sp<IOProfile> firstInexact;
5428 uint32_t updatedSamplingRate = 0;
5429 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5430 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005431 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005432 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005433 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005434 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005435 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005436 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005437 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005438 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005439 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005440 &channelMask /*updatedChannelMask*/,
5441 // FIXME ugly cast
5442 (audio_output_flags_t) flags,
5443 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005444 return profile;
5445 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005446 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5447 samplingRate,
5448 &updatedSamplingRate,
5449 format,
5450 &updatedFormat,
5451 channelMask,
5452 &updatedChannelMask,
5453 // FIXME ugly cast
5454 (audio_output_flags_t) flags,
5455 false /*exactMatchRequiredForInputFlags*/)) {
5456 firstInexact = profile;
5457 }
5458
Eric Laurente552edb2014-03-10 17:42:56 -07005459 }
5460 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005461 if (firstInexact != nullptr) {
5462 samplingRate = updatedSamplingRate;
5463 format = updatedFormat;
5464 channelMask = updatedChannelMask;
5465 return firstInexact;
5466 }
Eric Laurente552edb2014-03-10 17:42:56 -07005467 return NULL;
5468}
5469
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005470
5471audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005472 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005473{
François Gaffie036e1e92015-03-19 10:16:24 +01005474 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5475 audio_devices_t selectedDeviceFromMix =
5476 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005477
François Gaffie036e1e92015-03-19 10:16:24 +01005478 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5479 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005480 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005481 return getDeviceForInputSource(inputSource);
5482}
5483
5484audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5485{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005486 // Routing
5487 // Scan the whole RouteMap to see if we have an explicit route:
5488 // if the input source in the RouteMap is the same as the argument above,
5489 // and activity count is non-zero and the device in the route descriptor is available
5490 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005491 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5492 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005493 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005494 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005495 return route->mDeviceDescriptor->type();
5496 }
5497 }
5498
5499 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005500}
5501
Eric Laurente0720872014-03-11 09:30:41 -07005502float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005503 int index,
5504 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005505{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005506 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005507
5508 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5509 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5510 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5511 // the ringtone volume
5512 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5513 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5514 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5515 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5516 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5517 }
5518
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005519 // in-call: always cap earpiece volume by voice volume + some low headroom
Eric Laurent7731b5a2018-04-06 15:47:22 -07005520 if ((stream != AUDIO_STREAM_VOICE_CALL) && (device & AUDIO_DEVICE_OUT_EARPIECE) &&
5521 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005522 switch (stream) {
5523 case AUDIO_STREAM_SYSTEM:
5524 case AUDIO_STREAM_RING:
5525 case AUDIO_STREAM_MUSIC:
5526 case AUDIO_STREAM_ALARM:
5527 case AUDIO_STREAM_NOTIFICATION:
5528 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5529 case AUDIO_STREAM_DTMF:
5530 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005531 int voiceVolumeIndex =
5532 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, AUDIO_DEVICE_OUT_EARPIECE);
5533 const float maxVoiceVolDb =
5534 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, AUDIO_DEVICE_OUT_EARPIECE)
5535 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005536 if (volumeDB > maxVoiceVolDb) {
5537 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5538 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5539 volumeDB = maxVoiceVolDb;
5540 }
5541 } break;
5542 default:
5543 break;
5544 }
5545 }
5546
Eric Laurente552edb2014-03-10 17:42:56 -07005547 // if a headset is connected, apply the following rules to ring tones and notifications
5548 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005549 // - always attenuate notifications volume by 6dB
5550 // - attenuate ring tones volume by 6dB unless music is not playing and
5551 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005552 // - if music is playing, always limit the volume to current music volume,
5553 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005554 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005555 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5556 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5557 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005558 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005559 AUDIO_DEVICE_OUT_USB_HEADSET |
5560 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005561 ((stream_strategy == STRATEGY_SONIFICATION)
5562 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005563 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005564 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005565 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005566 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005567 // when the phone is ringing we must consider that music could have been paused just before
5568 // by the music application and behave as if music was active if the last music track was
5569 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005570 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005571 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005572 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005573 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005574 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005575 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5576 musicDevice),
5577 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005578 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5579 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005580 if (volumeDB > minVolDB) {
5581 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005582 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005583 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005584 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5585 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5586 // on A2DP, also ensure notification volume is not too low compared to media when
5587 // intended to be played
5588 if ((volumeDB > -96.0f) &&
5589 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5590 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5591 stream, device,
5592 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5593 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5594 }
5595 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005596 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5597 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005598 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005599 }
5600 }
5601
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005602 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005603}
5604
Eric Laurente0720872014-03-11 09:30:41 -07005605status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005606 int index,
5607 const sp<AudioOutputDescriptor>& outputDesc,
5608 audio_devices_t device,
5609 int delayMs,
5610 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005611{
Eric Laurente552edb2014-03-10 17:42:56 -07005612 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005613 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005614 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005615 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005616 return NO_ERROR;
5617 }
François Gaffie2110e042015-03-24 08:41:51 +01005618 audio_policy_forced_cfg_t forceUseForComm =
5619 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005620 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005621 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5622 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005623 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005624 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005625 return INVALID_OPERATION;
5626 }
5627
Eric Laurentc75307b2015-03-17 15:29:32 -07005628 if (device == AUDIO_DEVICE_NONE) {
5629 device = outputDesc->device();
5630 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005631
Eric Laurentffbc80f2015-03-18 18:30:19 -07005632 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005634 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005635 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005636
Eric Laurentffbc80f2015-03-18 18:30:19 -07005637 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005638
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 if (stream == AUDIO_STREAM_VOICE_CALL ||
5640 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005641 float voiceVolume;
5642 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005643 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005644 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005645 } else {
5646 voiceVolume = 1.0;
5647 }
5648
Eric Laurent18fba842016-03-31 14:41:26 -07005649 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005650 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5651 mLastVoiceVolume = voiceVolume;
5652 }
5653 }
5654
5655 return NO_ERROR;
5656}
5657
Eric Laurentc75307b2015-03-17 15:29:32 -07005658void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5659 audio_devices_t device,
5660 int delayMs,
5661 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005662{
Eric Laurentc75307b2015-03-17 15:29:32 -07005663 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005664
Eric Laurent794fde22016-03-11 09:50:45 -08005665 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005666 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005667 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005668 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005669 device,
5670 delayMs,
5671 force);
5672 }
5673}
5674
Eric Laurente0720872014-03-11 09:30:41 -07005675void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005676 bool on,
5677 const sp<AudioOutputDescriptor>& outputDesc,
5678 int delayMs,
5679 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005680{
Eric Laurent72249d52015-06-08 11:12:15 -07005681 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5682 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005683 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005684 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005685 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005686 }
5687 }
5688}
5689
Eric Laurente0720872014-03-11 09:30:41 -07005690void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005691 bool on,
5692 const sp<AudioOutputDescriptor>& outputDesc,
5693 int delayMs,
5694 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005695{
Eric Laurente552edb2014-03-10 17:42:56 -07005696 if (device == AUDIO_DEVICE_NONE) {
5697 device = outputDesc->device();
5698 }
5699
Eric Laurentc75307b2015-03-17 15:29:32 -07005700 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5701 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005702
5703 if (on) {
5704 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005705 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005706 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005707 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005708 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005709 }
5710 }
5711 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5712 outputDesc->mMuteCount[stream]++;
5713 } else {
5714 if (outputDesc->mMuteCount[stream] == 0) {
5715 ALOGV("setStreamMute() unmuting non muted stream!");
5716 return;
5717 }
5718 if (--outputDesc->mMuteCount[stream] == 0) {
5719 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005720 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005721 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005722 device,
5723 delayMs);
5724 }
5725 }
5726}
5727
Eric Laurente0720872014-03-11 09:30:41 -07005728void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005729 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005730{
Eric Laurent87ffa392015-05-22 10:32:38 -07005731 if(!hasPrimaryOutput()) {
5732 return;
5733 }
5734
Eric Laurente552edb2014-03-10 17:42:56 -07005735 // if the stream pertains to sonification strategy and we are in call we must
5736 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5737 // in the device used for phone strategy and play the tone if the selected device does not
5738 // interfere with the device used for phone strategy
5739 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5740 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005741 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005742 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5743 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005744 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005745 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5746 stream, starting, outputDesc->mDevice, stateChange);
5747 if (outputDesc->mRefCount[stream]) {
5748 int muteCount = 1;
5749 if (stateChange) {
5750 muteCount = outputDesc->mRefCount[stream];
5751 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005752 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005753 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5754 for (int i = 0; i < muteCount; i++) {
5755 setStreamMute(stream, starting, mPrimaryOutput);
5756 }
5757 } else {
5758 ALOGV("handleIncallSonification() high visibility");
5759 if (outputDesc->device() &
5760 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5761 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5762 for (int i = 0; i < muteCount; i++) {
5763 setStreamMute(stream, starting, mPrimaryOutput);
5764 }
5765 }
5766 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005767 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5768 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005769 } else {
5770 mpClientInterface->stopTone();
5771 }
5772 }
5773 }
5774 }
5775}
5776
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005777audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5778{
5779 // flags to stream type mapping
5780 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5781 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5782 }
5783 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5784 return AUDIO_STREAM_BLUETOOTH_SCO;
5785 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005786 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5787 return AUDIO_STREAM_TTS;
5788 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005789
5790 // usage to stream type mapping
5791 switch (attr->usage) {
5792 case AUDIO_USAGE_MEDIA:
5793 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005794 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005795 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5796 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005797 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5798 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005799 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5800 return AUDIO_STREAM_SYSTEM;
5801 case AUDIO_USAGE_VOICE_COMMUNICATION:
5802 return AUDIO_STREAM_VOICE_CALL;
5803
5804 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5805 return AUDIO_STREAM_DTMF;
5806
5807 case AUDIO_USAGE_ALARM:
5808 return AUDIO_STREAM_ALARM;
5809 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5810 return AUDIO_STREAM_RING;
5811
5812 case AUDIO_USAGE_NOTIFICATION:
5813 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5814 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5815 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5816 case AUDIO_USAGE_NOTIFICATION_EVENT:
5817 return AUDIO_STREAM_NOTIFICATION;
5818
5819 case AUDIO_USAGE_UNKNOWN:
5820 default:
5821 return AUDIO_STREAM_MUSIC;
5822 }
5823}
Eric Laurente83b55d2014-11-14 10:06:21 -08005824
François Gaffie53615e22015-03-19 09:24:12 +01005825bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5826{
Eric Laurente83b55d2014-11-14 10:06:21 -08005827 // has flags that map to a strategy?
5828 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5829 return true;
5830 }
5831
5832 // has known usage?
5833 switch (paa->usage) {
5834 case AUDIO_USAGE_UNKNOWN:
5835 case AUDIO_USAGE_MEDIA:
5836 case AUDIO_USAGE_VOICE_COMMUNICATION:
5837 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5838 case AUDIO_USAGE_ALARM:
5839 case AUDIO_USAGE_NOTIFICATION:
5840 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5841 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5842 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5843 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5844 case AUDIO_USAGE_NOTIFICATION_EVENT:
5845 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5846 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5847 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5848 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005849 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005850 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005851 break;
5852 default:
5853 return false;
5854 }
5855 return true;
5856}
5857
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005858bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005859 routing_strategy strategy, uint32_t inPastMs,
5860 nsecs_t sysTime) const
5861{
5862 if ((sysTime == 0) && (inPastMs != 0)) {
5863 sysTime = systemTime();
5864 }
Eric Laurent794fde22016-03-11 09:50:45 -08005865 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005866 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5867 (NUM_STRATEGIES == strategy)) &&
5868 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5869 return true;
5870 }
5871 }
5872 return false;
5873}
5874
François Gaffie2110e042015-03-24 08:41:51 +01005875audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5876{
5877 return mEngine->getForceUse(usage);
5878}
5879
5880bool AudioPolicyManager::isInCall()
5881{
5882 return isStateInCall(mEngine->getPhoneState());
5883}
5884
5885bool AudioPolicyManager::isStateInCall(int state)
5886{
5887 return is_state_in_call(state);
5888}
5889
Eric Laurentd60560a2015-04-10 11:31:20 -07005890void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5891{
5892 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5893 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5894 if (sourceDesc->mDevice->equals(deviceDesc)) {
5895 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5896 stopAudioSource(sourceDesc->getHandle());
5897 }
5898 }
5899
5900 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5901 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5902 bool release = false;
5903 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5904 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5905 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5906 source->ext.device.type == deviceDesc->type()) {
5907 release = true;
5908 }
5909 }
5910 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5911 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5912 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5913 sink->ext.device.type == deviceDesc->type()) {
5914 release = true;
5915 }
5916 }
5917 if (release) {
5918 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5919 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5920 }
5921 }
5922}
5923
Phil Burk09bc4612016-02-24 15:58:15 -08005924// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005925void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5926 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005927 // TODO Set this based on Config properties.
5928 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005929
5930 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5931 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005932 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005933
jiabin81772902018-04-02 17:52:27 -07005934 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5935 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5936 formats.clear();
5937 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5938 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005939 }
jiabin81772902018-04-02 17:52:27 -07005940 // Always enable IEC61937 when in MANUAL mode.
5941 formats.add(AUDIO_FORMAT_IEC61937);
5942 } else { // NEVER, AUTO or ALWAYS
5943 // Analyze original support for various formats.
5944 bool supportsAC3 = false;
5945 bool supportsOtherSurround = false;
5946 bool supportsIEC61937 = false;
5947 mSurroundFormats.clear();
5948 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5949 audio_format_t format = formats[formatIndex];
5950 switch (format) {
5951 case AUDIO_FORMAT_AC3:
5952 supportsAC3 = true;
5953 break;
5954 case AUDIO_FORMAT_E_AC3:
5955 case AUDIO_FORMAT_DTS:
5956 case AUDIO_FORMAT_DTS_HD:
5957 // If ALWAYS, remove all other surround formats here
5958 // since we will add them later.
5959 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5960 formats.removeAt(formatIndex);
5961 formatIndex--;
5962 }
5963 supportsOtherSurround = true;
5964 break;
5965 case AUDIO_FORMAT_IEC61937:
5966 supportsIEC61937 = true;
5967 break;
5968 default:
5969 break;
5970 }
5971 }
Phil Burk09bc4612016-02-24 15:58:15 -08005972
jiabin81772902018-04-02 17:52:27 -07005973 // Modify formats based on surround preferences.
5974 // If NEVER, remove support for surround formats.
5975 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5976 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5977 // Remove surround sound related formats.
5978 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5979 audio_format_t format = formats[formatIndex];
5980 switch(format) {
5981 case AUDIO_FORMAT_AC3:
5982 case AUDIO_FORMAT_E_AC3:
5983 case AUDIO_FORMAT_DTS:
5984 case AUDIO_FORMAT_DTS_HD:
5985 case AUDIO_FORMAT_IEC61937:
5986 formats.removeAt(formatIndex);
5987 break;
5988 default:
5989 formatIndex++; // keep it
5990 break;
5991 }
5992 }
5993 supportsAC3 = false;
5994 supportsOtherSurround = false;
5995 supportsIEC61937 = false;
5996 }
5997 } else { // AUTO or ALWAYS
5998 // Most TVs support AC3 even if they do not report it in the EDID.
5999 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
6000 && !supportsAC3) {
6001 formats.add(AUDIO_FORMAT_AC3);
6002 supportsAC3 = true;
6003 }
6004
6005 // If ALWAYS, add support for raw surround formats if all are missing.
6006 // This assumes that if any of these formats are reported by the HAL
6007 // then the report is valid and should not be modified.
6008 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6009 formats.add(AUDIO_FORMAT_E_AC3);
6010 formats.add(AUDIO_FORMAT_DTS);
6011 formats.add(AUDIO_FORMAT_DTS_HD);
6012 supportsOtherSurround = true;
6013 }
6014
6015 // Add support for IEC61937 if any raw surround supported.
6016 // The HAL could do this but add it here, just in case.
6017 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
6018 formats.add(AUDIO_FORMAT_IEC61937);
6019 supportsIEC61937 = true;
6020 }
6021
6022 // Add reported surround sound formats to enabled surround formats.
6023 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07006024 audio_format_t format = formats[formatIndex];
6025 switch(format) {
6026 case AUDIO_FORMAT_AC3:
6027 case AUDIO_FORMAT_E_AC3:
6028 case AUDIO_FORMAT_DTS:
6029 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07006030 case AUDIO_FORMAT_AAC_LC:
6031 case AUDIO_FORMAT_DOLBY_TRUEHD:
6032 case AUDIO_FORMAT_E_AC3_JOC:
6033 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07006034 default:
Phil Burk07ac1142016-03-25 13:39:29 -07006035 break;
6036 }
Phil Burk09bc4612016-02-24 15:58:15 -08006037 }
Phil Burk07ac1142016-03-25 13:39:29 -07006038 }
Phil Burk09bc4612016-02-24 15:58:15 -08006039 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006040}
6041
6042// Modify the list of channel masks supported.
6043void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6044 ChannelsVector &channelMasks = *channelMasksPtr;
6045 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6046 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6047
6048 // If NEVER, then remove support for channelMasks > stereo.
6049 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6050 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6051 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6052 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6053 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6054 channelMasks.removeAt(maskIndex);
6055 } else {
6056 maskIndex++;
6057 }
6058 }
jiabin81772902018-04-02 17:52:27 -07006059 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6060 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6061 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006062 bool supports5dot1 = false;
6063 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006064 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006065 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6066 supports5dot1 = true;
6067 break;
6068 }
6069 }
6070 // If not then add 5.1 support.
6071 if (!supports5dot1) {
6072 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6073 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
6074 }
Phil Burk09bc4612016-02-24 15:58:15 -08006075 }
6076}
6077
Phil Burk00eeb322016-03-31 12:41:00 -07006078void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
6079 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006080 AudioProfileVector &profiles)
6081{
6082 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07006083
François Gaffie112b0af2015-11-19 16:13:25 +01006084 // Format MUST be checked first to update the list of AudioProfile
6085 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006086 reply = mpClientInterface->getParameters(
6087 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006088 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006089 AudioParameter repliedParameters(reply);
6090 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006091 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006092 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6093 return;
6094 }
Phil Burk09bc4612016-02-24 15:58:15 -08006095 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07006096 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006097 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006098 }
Phil Burk09bc4612016-02-24 15:58:15 -08006099 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006100 }
François Gaffie112b0af2015-11-19 16:13:25 +01006101
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006102 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08006103 ChannelsVector channelMasks;
6104 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006105 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006106 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006107
6108 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006109 reply = mpClientInterface->getParameters(
6110 ioHandle,
6111 requestedParameters.toString() + ";" +
6112 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006113 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006114 AudioParameter repliedParameters(reply);
6115 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006116 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006117 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006118 }
6119 }
6120 if (profiles.hasDynamicChannelsFor(format)) {
6121 reply = mpClientInterface->getParameters(ioHandle,
6122 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006123 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006124 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006125 AudioParameter repliedParameters(reply);
6126 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006127 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006128 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006129 if (device == AUDIO_DEVICE_OUT_HDMI) {
6130 filterSurroundChannelMasks(&channelMasks);
6131 }
François Gaffie112b0af2015-11-19 16:13:25 +01006132 }
6133 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006134 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006135 }
6136}
Eric Laurentd60560a2015-04-10 11:31:20 -07006137
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006138} // namespace android