blob: 856bcb35bc230035b605c75c3604d3cca8138ffb [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070041#include <media/PatchBuilder.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Eric Laurente552edb2014-03-10 17:42:56 -070085// ----------------------------------------------------------------------------
86// AudioPolicyInterface implementation
87// ----------------------------------------------------------------------------
88
Eric Laurente0720872014-03-11 09:30:41 -070089status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080090 audio_policy_dev_state_t state,
91 const char *device_address,
92 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070093{
jiabina7b43792018-02-15 16:04:46 -080094 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
95 nextAudioPortGeneration();
96 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080097}
98
François Gaffie44481e72016-04-20 07:49:57 +020099void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
100 audio_policy_dev_state_t state,
101 const String8 &device_address)
102{
103 AudioParameter param(device_address);
104 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700105 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200106 param.addInt(key, device);
107 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
108}
109
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800111 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800112 const char *device_address,
113 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114{
Paul McLeane743a472015-01-28 11:07:31 -0800115 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800116 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700117
118 // connect/disconnect only 1 device at a time
119 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
120
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<DeviceDescriptor> devDesc =
122 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
125 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700138 ALOGW("setDeviceConnectionState() device already connected: %x", device);
139 return INVALID_OPERATION;
140 }
141 ALOGV("setDeviceConnectionState() connecting device %x", device);
142
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 index = mAvailableOutputDevices.add(devDesc);
145 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100146 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700147 if (module == 0) {
148 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
149 device);
150 mAvailableOutputDevices.remove(devDesc);
151 return INVALID_OPERATION;
152 }
Paul McLeane743a472015-01-28 11:07:31 -0800153 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 } else {
155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
160 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200164
165 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
166 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 return INVALID_OPERATION;
168 }
François Gaffie2110e042015-03-24 08:41:51 +0100169 // Propagate device availability to Engine
170 mEngine->setDeviceConnectionState(devDesc, state);
171
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 // outputs should never be empty here
173 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
174 "checkOutputsForDevice() returned no outputs but status OK");
175 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
176 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700182 ALOGW("setDeviceConnectionState() device not connected: %x", device);
183 return INVALID_OPERATION;
184 }
185
Paul McLean5c477aa2014-08-20 16:47:57 -0700186 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200189 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Eric Laurenta1d525f2015-01-29 13:36:45 -0800194 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100195
196 // Propagate device availability to Engine
197 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700198 } break;
199
200 default:
201 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 return BAD_VALUE;
203 }
204
Mikhail Naganov37977152018-07-11 15:54:44 -0700205 checkForDeviceAndOutputChanges([&]() {
206 // outputs must be closed after checkOutputForAllStrategies() is executed
207 if (!outputs.isEmpty()) {
208 for (audio_io_handle_t output : outputs) {
209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
210 // close unused outputs after device disconnection or direct outputs that have been
211 // opened by checkOutputsForDevice() to query dynamic parameters
212 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
213 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
214 (desc->mDirectOpenCount == 0))) {
215 closeOutput(output);
216 }
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700218 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
219 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 return false;
222 });
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent87ffa392015-05-22 10:32:38 -0700224 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
226 updateCallRouting(newDevice);
227 }
Eric Laurente552edb2014-03-10 17:42:56 -0700228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
230 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
231 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // do not force device change on duplicated output because if device is 0, it will
233 // also force a device 0 for the two outputs it is duplicated to which may override
234 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700235 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100236 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 // always force when disconnecting (a non-duplicated device)
238 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700239 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700240 }
Eric Laurente552edb2014-03-10 17:42:56 -0700241 }
242
Eric Laurentd60560a2015-04-10 11:31:20 -0700243 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
244 cleanUpForDevice(devDesc);
245 }
246
Eric Laurent72aa32f2014-05-30 18:51:48 -0700247 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700248 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700249 } // end if is output device
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // handle input devices
252 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700253 SortedVector <audio_io_handle_t> inputs;
254
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700256 switch (state)
257 {
258 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700259 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700261 ALOGW("setDeviceConnectionState() device already connected: %d", device);
262 return INVALID_OPERATION;
263 }
François Gaffie53615e22015-03-19 09:24:12 +0100264 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700265 if (module == NULL) {
266 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
267 device);
268 return INVALID_OPERATION;
269 }
François Gaffie44481e72016-04-20 07:49:57 +0200270
271 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
272 // parameters on newly connected devices (instead of opening the inputs...)
273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
274
Paul McLean9080a4c2015-06-18 08:24:02 -0700275 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200276 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
277 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700278 return INVALID_OPERATION;
279 }
280
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 index = mAvailableInputDevices.add(devDesc);
282 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800283 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700284 } else {
285 return NO_MEMORY;
286 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800287
François Gaffie2110e042015-03-24 08:41:51 +0100288 // Propagate device availability to Engine
289 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700291
292 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700293 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700295 ALOGW("setDeviceConnectionState() device not connected: %d", device);
296 return INVALID_OPERATION;
297 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
299 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
300
301 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200302 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
Paul McLean9080a4c2015-06-18 08:24:02 -0700304 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700306
François Gaffie2110e042015-03-24 08:41:51 +0100307 // Propagate device availability to Engine
308 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 default:
312 ALOGE("setDeviceConnectionState() invalid state: %x", state);
313 return BAD_VALUE;
314 }
315
Eric Laurentd4692962014-05-05 18:13:44 -0700316 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700317 // As the input device list can impact the output device selection, update
318 // getDeviceForStrategy() cache
319 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700320
Eric Laurent87ffa392015-05-22 10:32:38 -0700321 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
323 updateCallRouting(newDevice);
324 }
325
Eric Laurentd60560a2015-04-10 11:31:20 -0700326 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
327 cleanUpForDevice(devDesc);
328 }
329
Eric Laurentb52c1522014-05-20 11:27:36 -0700330 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700332 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700333
334 ALOGW("setDeviceConnectionState() invalid device: %x", device);
335 return BAD_VALUE;
336}
337
Eric Laurente0720872014-03-11 09:30:41 -0700338audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100339 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700340{
Eric Laurent634b7142016-04-20 13:48:02 -0700341 sp<DeviceDescriptor> devDesc =
342 mHwModules.getDeviceDescriptor(device, device_address, "",
343 (strlen(device_address) != 0)/*matchAddress*/);
344
345 if (devDesc == 0) {
346 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
347 device, device_address);
348 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
349 }
François Gaffie53615e22015-03-19 09:24:12 +0100350
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 DeviceVector *deviceVector;
352
Eric Laurente552edb2014-03-10 17:42:56 -0700353 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 deviceVector = &mAvailableInputDevices;
357 } else {
358 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
359 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
Eric Laurent634b7142016-04-20 13:48:02 -0700361
362 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800364}
365
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
367 const char *device_address,
368 const char *device_name)
369{
370 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431}
432
Eric Laurentdc462862016-07-19 12:29:53 -0700433uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434{
435 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700436 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437
Andy Hunga76c7de2016-12-13 19:14:31 -0800438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700439 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 createTxPatch = true;
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 return muteWaitMs;
475}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 sp<DeviceDescriptor> txSourceDeviceDesc;
482 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700483 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
484 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700486 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
487 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 }
489
490 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
491 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
492 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
493 // request to reuse existing output stream if one is already opened to reach the target device
494 if (output != AUDIO_IO_HANDLE_NONE) {
495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
496 ALOG_ASSERT(!outputDesc->isDuplicated(),
497 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800499 }
500
501 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 // terminate active capture if on the same HW module as the call TX source device
503 // FIXME: would be better to refine to only inputs whose profile connects to the
504 // call TX device but this information is not in the audio patch and logic here must be
505 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800506 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800507 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
508 AudioSessionCollection activeSessions =
509 activeDesc->getAudioSessions(true /*activeOnly*/);
510 for (size_t j = 0; j < activeSessions.size(); j++) {
511 audio_session_t activeSession = activeSessions.keyAt(j);
512 stopInput(activeDesc->mIoHandle, activeSession);
513 releaseInput(activeDesc->mIoHandle, activeSession);
514 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700515 }
516 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 }
Eric Laurentdc462862016-07-19 12:29:53 -0700518
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800519 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520 status_t status = mpClientInterface->createAudioPatch(
521 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800522 ALOGW_IF(status != NO_ERROR,
523 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
524 sp<AudioPatch> audioPatch;
525 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 audioPatch->mAfPatchHandle = afPatchHandle;
528 audioPatch->mUid = mUidCached;
529 }
530 return audioPatch;
531}
532
Mikhail Naganovdc769682018-05-04 15:34:08 -0700533sp<DeviceDescriptor> AudioPolicyManager::findDevice(
534 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700535 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700538 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700539}
540
Eric Laurente0720872014-03-11 09:30:41 -0700541void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700542{
543 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100544 // store previous phone state for management of sonification strategy below
545 int oldState = mEngine->getPhoneState();
546
547 if (mEngine->setPhoneState(state) != NO_ERROR) {
548 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700549 return;
550 }
François Gaffie2110e042015-03-24 08:41:51 +0100551 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700552 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700553 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700554 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800555 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 }
557
François Gaffie2110e042015-03-24 08:41:51 +0100558 /**
559 * Switching to or from incall state or switching between telephony and VoIP lead to force
560 * routing command.
561 */
562 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
563 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700564
565 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700566 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700567
Eric Laurente552edb2014-03-10 17:42:56 -0700568 int delayMs = 0;
569 if (isStateInCall(state)) {
570 nsecs_t sysTime = systemTime();
571 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700573 // mute media and sonification strategies and delay device switch by the largest
574 // latency of any output where either strategy is active.
575 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100576 if ((isStrategyActive(desc, STRATEGY_MEDIA,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime) ||
579 isStrategyActive(desc, STRATEGY_SONIFICATION,
580 SONIFICATION_HEADSET_MUSIC_DELAY,
581 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 (delayMs < (int)desc->latency()*2)) {
583 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700584 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_MEDIA, true, desc);
586 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
589 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700590 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
591 }
592 }
593
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 if (hasPrimaryOutput()) {
595 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
596 // the device returned is not necessarily reachable via this output
597 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
598 // force routing command to audio hardware when ending call
599 // even if no device change is needed
600 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
601 rxDevice = mPrimaryOutput->device();
602 }
Eric Laurente552edb2014-03-10 17:42:56 -0700603
Eric Laurent87ffa392015-05-22 10:32:38 -0700604 if (state == AUDIO_MODE_IN_CALL) {
605 updateCallRouting(rxDevice, delayMs);
606 } else if (oldState == AUDIO_MODE_IN_CALL) {
607 if (mCallRxPatch != 0) {
608 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
609 mCallRxPatch.clear();
610 }
611 if (mCallTxPatch != 0) {
612 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
613 mCallTxPatch.clear();
614 }
615 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
616 } else {
617 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700618 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700620
621 // reevaluate routing on all outputs in case tracks have been started during the call
622 for (size_t i = 0; i < mOutputs.size(); i++) {
623 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
624 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
625 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800626 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627 }
628 }
629
Eric Laurente552edb2014-03-10 17:42:56 -0700630 if (isStateInCall(state)) {
631 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700632 // force reevaluating accessibility routing when call starts
633 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 }
635
636 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 if (state == AUDIO_MODE_RINGTONE &&
638 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700639 mLimitRingtoneVolume = true;
640 } else {
641 mLimitRingtoneVolume = false;
642 }
643}
644
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700645audio_mode_t AudioPolicyManager::getPhoneState() {
646 return mEngine->getPhoneState();
647}
648
Eric Laurente0720872014-03-11 09:30:41 -0700649void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700651{
François Gaffie2110e042015-03-24 08:41:51 +0100652 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700653 if (config == mEngine->getForceUse(usage)) {
654 return;
655 }
Eric Laurente552edb2014-03-10 17:42:56 -0700656
François Gaffie2110e042015-03-24 08:41:51 +0100657 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
658 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
659 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700660 }
François Gaffie2110e042015-03-24 08:41:51 +0100661 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
662 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
663 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700664
665 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700666 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800667
Eric Laurentdc462862016-07-19 12:29:53 -0700668 //FIXME: workaround for truncated touch sounds
669 // to be removed when the problem is handled by system UI
670 uint32_t delayMs = 0;
671 uint32_t waitMs = 0;
672 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
673 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
674 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700677 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700680 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
681 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
682 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
684 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700687 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
689 }
690
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800691 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800694 if (activeDesc->mProfile->getSupportedDevices().types() &
695 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
696 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700697 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 }
Eric Laurente552edb2014-03-10 17:42:56 -0700700 }
Eric Laurente552edb2014-03-10 17:42:56 -0700701}
702
Eric Laurente0720872014-03-11 09:30:41 -0700703void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700704{
705 ALOGV("setSystemProperty() property %s, value %s", property, value);
706}
707
708// Find a direct output profile compatible with the parameters passed, even if the input flags do
709// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800710sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700711 audio_devices_t device,
712 uint32_t samplingRate,
713 audio_format_t format,
714 audio_channel_mask_t channelMask,
715 audio_output_flags_t flags)
716{
Eric Laurent861a6282015-05-18 15:40:16 -0700717 // only retain flags that will drive the direct output profile selection
718 // if explicitly requested
719 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700720 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
721 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700722 flags =
723 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
724
725 sp<IOProfile> profile;
726
Mikhail Naganovd4120142017-12-06 15:49:22 -0800727 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800728 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700730 samplingRate, NULL /*updatedSamplingRate*/,
731 format, NULL /*updatedFormat*/,
732 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700733 flags)) {
734 continue;
735 }
736 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 continue;
739 }
740 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100741 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700742 continue;
743 }
744 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100745 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700746 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700747 }
Eric Laurente552edb2014-03-10 17:42:56 -0700748 }
749 }
Eric Laurent861a6282015-05-18 15:40:16 -0700750 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700751}
752
Eric Laurentf4e63452017-11-06 19:31:46 +0000753audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700754{
Eric Laurent3b73df72014-03-11 09:06:29 -0700755 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700756 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800757
758 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
759 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
760 // format, flags, etc. This may result in some discrepancy for functions that utilize
761 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
762 // and AudioSystem::getOutputSamplingRate().
763
Eric Laurentf4e63452017-11-06 19:31:46 +0000764 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
765 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700766
Eric Laurentf4e63452017-11-06 19:31:46 +0000767 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
768 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769}
770
Eric Laurente83b55d2014-11-14 10:06:21 -0800771status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
772 audio_io_handle_t *output,
773 audio_session_t session,
774 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700775 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800776 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200777 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700778 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800779 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780{
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 audio_attributes_t attributes;
782 if (attr != NULL) {
783 if (!isValidAttributes(attr)) {
784 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
785 attr->usage, attr->content_type, attr->flags,
786 attr->tags);
787 return BAD_VALUE;
788 }
789 attributes = *attr;
790 } else {
791 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
792 ALOGE("getOutputForAttr(): invalid stream type");
793 return BAD_VALUE;
794 }
795 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800797
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700798 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
799 " session %d selectedDeviceId %d",
800 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700801 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700802
Scott Randolph7b1fd232018-06-18 15:33:03 -0700803 // TODO: check for existing client for this port ID
804 if (*portId == AUDIO_PORT_HANDLE_NONE) {
805 *portId = AudioPort::getNextUniqueId();
806 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700807
Scott Randolph7b1fd232018-06-18 15:33:03 -0700808 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700809 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700810 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800811 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700812 } else {
813 // If no explict route, is there a matching dynamic policy that applies?
814 sp<SwAudioOutputDescriptor> desc;
815 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
816 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
817 if (!audio_has_proportional_frames(config->format)) {
818 return BAD_VALUE;
819 }
820 *stream = streamTypefromAttributesInt(&attributes);
821 *output = desc->mIoHandle;
822 ALOGV("getOutputForAttr() returns output %d", *output);
823 return NO_ERROR;
824 }
825
826 // Virtual sources must always be dynamicaly or explicitly routed
827 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
828 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
829 return BAD_VALUE;
830 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700831 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700832
833 // Virtual sources must always be dynamicaly or explicitly routed
834 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
835 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
836 return BAD_VALUE;
837 }
838
839 *stream = streamTypefromAttributesInt(&attributes);
840
841 // TODO: Should this happen only if an explicit route is active?
842 // the previous code structure meant that this would always happen which
843 // would appear to result in adding a null deviceDesc when not using an
844 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700845 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200851 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852 }
853
Nadav Barb2f18162018-07-18 13:01:53 +0300854 // Set incall music only if device was explicitly set, and fallback to the device which is
855 // chosen by the engine if not.
856 // FIXME: provide a more generic approach which is not device specific and move this back
857 // to getOutputForDevice.
858 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
859 *stream == AUDIO_STREAM_MUSIC &&
860 audio_is_linear_pcm(config->format) &&
861 isInCall()) {
862 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
863 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
864 } else {
865 device = mEngine->getDeviceForStrategy(strategy);
866 }
867 }
868
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800869 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
870 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200871 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700872
Andy Hungc88b0642018-04-27 15:42:35 -0700873 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800874 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700875 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800876 return INVALID_OPERATION;
877 }
Paul McLeanaa981192015-03-21 09:55:15 -0700878
Mikhail Naganov708e0382018-05-30 09:53:04 -0700879 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700880 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
881 : AUDIO_PORT_HANDLE_NONE;
882
883 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
884
Eric Laurente83b55d2014-11-14 10:06:21 -0800885 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886}
887
888audio_io_handle_t AudioPolicyManager::getOutputForDevice(
889 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800890 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700891 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800892 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200893 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700894{
Andy Hungc88b0642018-04-27 15:42:35 -0700895 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700896 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700897
Eric Laurente552edb2014-03-10 17:42:56 -0700898 // open a direct output if required by specified parameters
899 //force direct flag if offload flag is set: offloading implies a direct output stream
900 // and all common behaviors are driven by checking only the direct flag
901 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200902 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
903 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700904 }
Nadav Bar766fb022018-01-07 12:18:03 +0200905 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
906 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700907 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800908 // only allow deep buffering for music stream type
909 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200910 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700911 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200912 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700913 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
914 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200915 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800916 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700917 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200918 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700919 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800920 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200921 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700922 AUDIO_OUTPUT_FLAG_DIRECT);
923 ALOGV("Set VoIP and Direct output flags for PCM format");
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
Mikhail Naganov708e0382018-05-30 09:53:04 -0700979 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800980 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 Laurentf3a5a602018-05-22 18:42:55 -07001160 if (newDevice != outputDesc->device()) {
1161 checkStrategyRoute(getStrategy(stream), output);
1162 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001163 } else {
1164 newDevice = AUDIO_DEVICE_NONE;
1165 }
1166
1167 uint32_t delayMs = 0;
1168
Eric Laurent733ce942017-12-07 12:18:25 -08001169 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001170
1171 if (status != NO_ERROR) {
1172 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001173 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001174 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001175 }
1176 // Automatically enable the remote submix input when output is started on a re routing mix
1177 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001178 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1179 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001180 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1181 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001182 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001183 "remote-submix");
1184 }
1185
1186 if (delayMs != 0) {
1187 usleep(delayMs * 1000);
1188 }
1189
1190 return status;
1191}
1192
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001193status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 audio_stream_type_t stream,
1195 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001196 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001197 uint32_t *delayMs)
1198{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001199 // cannot start playback of STREAM_TTS if any other output is being used
1200 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001201
1202 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001203 if (stream == AUDIO_STREAM_TTS) {
1204 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001205 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001206 return INVALID_OPERATION;
1207 } else {
1208 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1209 }
1210 } else {
1211 // some playback other than beacon starts
1212 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1213 }
1214
Eric Laurent77305a62016-07-25 16:39:22 -07001215 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001216 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001217 bool force = !outputDesc->isActive() &&
1218 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001219
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001220 // requiresMuteCheck is false when we can bypass mute strategy.
1221 // It covers a common case when there is no materially active audio
1222 // and muting would result in unnecessary delay and dropped audio.
1223 const uint32_t outputLatencyMs = outputDesc->latency();
1224 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1225
Eric Laurente552edb2014-03-10 17:42:56 -07001226 // increment usage count for this stream on the requested output:
1227 // NOTE that the usage count is the same for duplicated output and hardware output which is
1228 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1229 outputDesc->changeRefCount(stream, 1);
1230
Eric Laurent36829f92017-04-07 19:04:42 -07001231 if (stream == AUDIO_STREAM_MUSIC) {
1232 selectOutputForMusicEffects();
1233 }
1234
Eric Laurent493404d2015-04-21 15:07:36 -07001235 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001236 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001237 if (device == AUDIO_DEVICE_NONE) {
1238 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001239 }
Eric Laurent36829f92017-04-07 19:04:42 -07001240
Eric Laurente552edb2014-03-10 17:42:56 -07001241 routing_strategy strategy = getStrategy(stream);
1242 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1244 (beaconMuteLatency > 0);
1245 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001246 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001247 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001248 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001249 // An output has a shared device if
1250 // - managed by the same hw module
1251 // - supports the currently selected device
1252 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1253 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1254
Eric Laurent77305a62016-07-25 16:39:22 -07001255 // force a device change if any other output is:
1256 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001257 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001258 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001259 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001260 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001261 // change the device currently selected by the other output.
1262 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001263 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001264 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001265 force = true;
1266 }
1267 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001268 // a notification so that audio focus effect can propagate, or that a mute/unmute
1269 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001270 const uint32_t latencyMs = desc->latency();
1271 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1272
1273 if (shouldWait && isActive && (waitMs < latencyMs)) {
1274 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001275 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001276
1277 // Require mute check if another output is on a shared device
1278 // and currently active to have proper drain and avoid pops.
1279 // Note restoring AudioTracks onto this output needs to invoke
1280 // a volume ramp if there is no mute.
1281 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001282 }
1283 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001284
1285 const uint32_t muteWaitMs =
1286 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001287
Eric Laurente552edb2014-03-10 17:42:56 -07001288 // apply volume rules for current stream and device if necessary
1289 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001290 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001291 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001292 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001293
1294 // update the outputs if starting an output with a stream that can affect notification
1295 // routing
1296 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001297
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001298 // force reevaluating accessibility routing when ringtone or alarm starts
1299 if (strategy == STRATEGY_SONIFICATION) {
1300 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1301 }
Eric Laurentdc462862016-07-19 12:29:53 -07001302
1303 if (waitMs > muteWaitMs) {
1304 *delayMs = waitMs - muteWaitMs;
1305 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001306
1307 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1308 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1309 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1310 // change occurs after the MixerThread starts and causes a stream volume
1311 // glitch.
1312 //
1313 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001314 }
Eric Laurentdc462862016-07-19 12:29:53 -07001315
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001316 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1317 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1318 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1319 }
1320
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001321 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1322 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1323 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1324 }
1325
Eric Laurente552edb2014-03-10 17:42:56 -07001326 return NO_ERROR;
1327}
1328
1329
Eric Laurente0720872014-03-11 09:30:41 -07001330status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001331 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001332 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001333{
1334 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1335 ssize_t index = mOutputs.indexOfKey(output);
1336 if (index < 0) {
1337 ALOGW("stopOutput() unknown output %d", output);
1338 return BAD_VALUE;
1339 }
1340
Eric Laurentc75307b2015-03-17 15:29:32 -07001341 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001342
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 if (outputDesc->mRefCount[stream] == 1) {
1344 // Automatically disable the remote submix input when output is stopped on a
1345 // re routing mix of type MIX_TYPE_RECORDERS
1346 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1347 outputDesc->mPolicyMix != NULL &&
1348 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1349 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1350 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001351 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001352 "remote-submix");
1353 }
1354 }
1355
1356 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001357 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001358 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001359 int activityCount = mOutputRoutes.decRouteActivity(session);
1360 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1361
1362 if (forceDeviceUpdate) {
1363 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1364 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001365 }
1366
Eric Laurent3974e3b2017-12-07 17:58:43 -08001367 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1368
Eric Laurent733ce942017-12-07 12:18:25 -08001369 if (status == NO_ERROR ) {
1370 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001371 }
1372 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001373}
1374
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001375status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001376 audio_stream_type_t stream,
1377 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001378{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001379 // always handle stream stop, check which stream type is stopping
1380 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1381
Eric Laurente552edb2014-03-10 17:42:56 -07001382 if (outputDesc->mRefCount[stream] > 0) {
1383 // decrement usage count of this stream on the output
1384 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001385
Eric Laurente552edb2014-03-10 17:42:56 -07001386 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001387 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001388 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001389 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001390 // delay the device switch by twice the latency because stopOutput() is executed when
1391 // the track stop() command is received and at that time the audio track buffer can
1392 // still contain data that needs to be drained. The latency only covers the audio HAL
1393 // and kernel buffers. Also the latency does not always include additional delay in the
1394 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001395 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001396
1397 // force restoring the device selection on other active outputs if it differs from the
1398 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001399 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001400 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001401 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001402 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001403 desc->isActive() &&
1404 outputDesc->sharesHwModuleWith(desc) &&
1405 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001406 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1407 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001408
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001410 newDevice2,
1411 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001412 delayMs);
1413 // re-apply device specific volume if not done by setOutputDevice()
1414 if (!force) {
1415 applyStreamVolumes(desc, newDevice2, delayMs);
1416 }
Eric Laurente552edb2014-03-10 17:42:56 -07001417 }
1418 }
1419 // update the outputs if stopping one with a stream that can affect notification routing
1420 handleNotificationRoutingForStream(stream);
1421 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001422
1423 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1424 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1425 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1426 }
1427
Eric Laurent36829f92017-04-07 19:04:42 -07001428 if (stream == AUDIO_STREAM_MUSIC) {
1429 selectOutputForMusicEffects();
1430 }
Eric Laurente552edb2014-03-10 17:42:56 -07001431 return NO_ERROR;
1432 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001433 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001434 return INVALID_OPERATION;
1435 }
1436}
1437
Eric Laurente83b55d2014-11-14 10:06:21 -08001438void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001439 audio_stream_type_t stream __unused,
1440 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001441{
1442 ALOGV("releaseOutput() %d", output);
1443 ssize_t index = mOutputs.indexOfKey(output);
1444 if (index < 0) {
1445 ALOGW("releaseOutput() releasing unknown output %d", output);
1446 return;
1447 }
1448
Paul McLeanaa981192015-03-21 09:55:15 -07001449 // Routing
1450 mOutputRoutes.removeRoute(session);
1451
Eric Laurentc75307b2015-03-17 15:29:32 -07001452 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001453 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001454 if (desc->mDirectOpenCount <= 0) {
1455 ALOGW("releaseOutput() invalid open count %d for output %d",
1456 desc->mDirectOpenCount, output);
1457 return;
1458 }
1459 if (--desc->mDirectOpenCount == 0) {
1460 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001461 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001462 }
1463 }
1464}
1465
1466
Eric Laurentcaf7f482014-11-25 17:50:47 -08001467status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1468 audio_io_handle_t *input,
1469 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001470 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001471 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001472 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001473 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001474 input_type_t *inputType,
1475 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001476{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001477 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001478 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001479 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
Eric Laurentad2e7b92017-09-14 20:06:42 -07001481 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001482 // handle legacy remote submix case where the address was not always specified
1483 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001484 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001485 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001486 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001487 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001488
Eric Laurentfe231122017-11-17 17:48:06 -08001489 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1490 inputSource = AUDIO_SOURCE_MIC;
1491 }
1492
Paul McLean466dc8e2015-04-17 13:15:36 -06001493 // Explicit routing?
1494 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001495 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001496 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001497 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001498 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001499
Eric Laurentad2e7b92017-09-14 20:06:42 -07001500 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1501 // possible
1502 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1503 *input != AUDIO_IO_HANDLE_NONE) {
1504 ssize_t index = mInputs.indexOfKey(*input);
1505 if (index < 0) {
1506 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1507 status = BAD_VALUE;
1508 goto error;
1509 }
1510 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1511 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1512 if (audioSession == 0) {
1513 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1514 status = BAD_VALUE;
1515 goto error;
1516 }
1517 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1518 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001519 // corresponds to a new client and is only permitted from the same UID.
1520 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001521 if (audioSession->openCount() == 1) {
1522 audioSession->setUid(uid);
1523 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001524 if (!audioSession->isSilenced()) {
1525 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1526 uid, session, audioSession->uid());
1527 status = INVALID_OPERATION;
1528 goto error;
1529 }
1530 audioSession->setUid(uid);
1531 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001532 }
1533 audioSession->changeOpenCount(1);
1534 *inputType = API_INPUT_LEGACY;
1535 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1536 *portId = AudioPort::getNextUniqueId();
1537 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001538 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001539 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1540 : AUDIO_PORT_HANDLE_NONE;
1541 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1542
1543 return NO_ERROR;
1544 }
1545
1546 *input = AUDIO_IO_HANDLE_NONE;
1547 *inputType = API_INPUT_INVALID;
1548
Eric Laurentad2e7b92017-09-14 20:06:42 -07001549 halInputSource = inputSource;
1550
1551 // TODO: check for existing client for this port ID
1552 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1553 *portId = AudioPort::getNextUniqueId();
1554 }
1555
1556 audio_devices_t device;
1557
Eric Laurentc447ded2015-01-06 08:47:05 -08001558 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001559 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001560 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1561 if (status != NO_ERROR) {
1562 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001563 }
1564 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001565 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1566 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001567 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001568 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001569 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001570 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001571 status = BAD_VALUE;
1572 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 }
Eric Laurentc722f302014-12-10 11:21:49 -08001574 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001575 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001576 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1577 // there is an external policy, but this input is attached to a mix of recorders,
1578 // meaning it receives audio injected into the framework, so the recorder doesn't
1579 // know about it and is therefore considered "legacy"
1580 *inputType = API_INPUT_LEGACY;
1581 } else {
1582 // recording a mix of players defined by an external policy, we're rerouting for
1583 // an external policy
1584 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1585 }
Eric Laurentc722f302014-12-10 11:21:49 -08001586 } else if (audio_is_remote_submix_device(device)) {
1587 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001588 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001589 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1590 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001591 } else {
1592 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001593 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001594
Eric Laurent599c7582015-12-07 18:05:55 -08001595 }
1596
1597 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001598 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001599 policyMix);
1600 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001601 status = INVALID_OPERATION;
1602 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001603 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001604
Mikhail Naganov708e0382018-05-30 09:53:04 -07001605 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001606 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1607 : AUDIO_PORT_HANDLE_NONE;
1608
1609 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1610 *input, *inputType, *selectedDeviceId);
1611
Eric Laurent599c7582015-12-07 18:05:55 -08001612 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001613
1614error:
1615 mInputRoutes.removeRoute(session);
1616 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001617}
1618
1619
1620audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1621 String8 address,
1622 audio_session_t session,
1623 uid_t uid,
1624 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001625 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001626 audio_input_flags_t flags,
1627 AudioMix *policyMix)
1628{
1629 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1630 audio_source_t halInputSource = inputSource;
1631 bool isSoundTrigger = false;
1632
1633 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1634 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1635 if (index >= 0) {
1636 input = mSoundTriggerSessions.valueFor(session);
1637 isSoundTrigger = true;
1638 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1639 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1640 } else {
1641 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001642 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001643 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001644 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001645 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001646 }
1647
Andy Hungf129b032015-04-07 13:45:50 -07001648 // find a compatible input profile (not necessarily identical in parameters)
1649 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001650 // sampling rate and flags may be updated by getInputProfile
1651 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1652 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001653 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001654 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001655 audio_input_flags_t profileFlags = flags;
1656 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001657 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001658 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001659 profileSamplingRate, profileFormat, profileChannelMask,
1660 profileFlags);
1661 if (profile != 0) {
1662 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001663 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1664 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001665 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1666 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1667 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001668 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001669 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1670 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001671 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001672 }
Eric Laurente552edb2014-03-10 17:42:56 -07001673 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001674 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001675 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001676 if (samplingRate == 0) {
1677 samplingRate = profileSamplingRate;
1678 }
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurent322b4d22015-04-03 15:57:54 -07001680 if (profile->getModuleHandle() == 0) {
1681 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001682 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001683 }
1684
Eric Laurent599c7582015-12-07 18:05:55 -08001685 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001686 inputSource,
1687 config->format,
1688 samplingRate,
1689 config->channel_mask,
1690 flags,
1691 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001692 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001693
Eric Laurent3974e3b2017-12-07 17:58:43 -08001694 if (!profile->canOpenNewIo()) {
1695 return AUDIO_IO_HANDLE_NONE;
1696 }
1697
Eric Laurentfe231122017-11-17 17:48:06 -08001698 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001699
Eric Laurentfe231122017-11-17 17:48:06 -08001700 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1701 lConfig.sample_rate = profileSamplingRate;
1702 lConfig.channel_mask = profileChannelMask;
1703 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001704
Eric Laurent53b810e2017-12-10 17:25:10 -08001705 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001706 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001707 // the inputs vector must be of size >= 1, but we don't want to crash here
1708 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1709 }
1710
Eric Laurentfe231122017-11-17 17:48:06 -08001711 status_t status = inputDesc->open(&lConfig, device, address,
1712 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001713
1714 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001715 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001716 (profileSamplingRate != lConfig.sample_rate) ||
1717 !audio_formats_match(profileFormat, lConfig.format) ||
1718 (profileChannelMask != lConfig.channel_mask)) {
1719 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001720 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001721 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001722 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001723 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001724 }
Eric Laurent599c7582015-12-07 18:05:55 -08001725 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001726 }
1727
Eric Laurentc722f302014-12-10 11:21:49 -08001728 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001729 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001730
Eric Laurent599c7582015-12-07 18:05:55 -08001731 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001732 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001733
Eric Laurent599c7582015-12-07 18:05:55 -08001734 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001735}
1736
Eric Laurentbb948092017-01-23 18:33:30 -08001737//static
1738bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1739{
1740 return (source == AUDIO_SOURCE_HOTWORD) ||
1741 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1742 (source == AUDIO_SOURCE_FM_TUNER);
1743}
1744
Eric Laurentfb66dd92016-01-28 18:32:03 -08001745bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1746 const sp<AudioSession>& audioSession)
1747{
1748 // Do not allow capture if an active voice call is using a software patch and
1749 // the call TX source device is on the same HW module.
1750 // FIXME: would be better to refine to only inputs whose profile connects to the
1751 // call TX device but this information is not in the audio patch
1752 if (mCallTxPatch != 0 &&
1753 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1754 return false;
1755 }
1756
1757 // starting concurrent capture is enabled if:
1758 // 1) capturing for re-routing
1759 // 2) capturing for HOTWORD source
1760 // 3) capturing for FM TUNER source
1761 // 3) All other active captures are either for re-routing or HOTWORD
1762
1763 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001764 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001765 return true;
1766 }
1767
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001768 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001769 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001770 !is_virtual_input_device(activeInput->mDevice)) {
1771 return false;
1772 }
1773 }
1774
1775 return true;
1776}
1777
Chris Thornton2b864642017-06-27 21:26:07 -07001778// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1779bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1780 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1781 bool soundTriggerSupportsConcurrentCapture = false;
1782 unsigned int numModules = 0;
1783 struct sound_trigger_module_descriptor* nModules = NULL;
1784
1785 status_t status = SoundTrigger::listModules(nModules, &numModules);
1786 if (status == NO_ERROR && numModules != 0) {
1787 nModules = (struct sound_trigger_module_descriptor*) calloc(
1788 numModules, sizeof(struct sound_trigger_module_descriptor));
1789 if (nModules == NULL) {
1790 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1791 // ram the next time this function is called.
1792 ALOGE("Failed to allocate buffer for module descriptors");
1793 return false;
1794 }
1795
1796 status = SoundTrigger::listModules(nModules, &numModules);
1797 if (status == NO_ERROR) {
1798 soundTriggerSupportsConcurrentCapture = true;
1799 for (size_t i = 0; i < numModules; ++i) {
1800 soundTriggerSupportsConcurrentCapture &=
1801 nModules[i].properties.concurrent_capture;
1802 }
1803 }
1804 free(nModules);
1805 }
1806 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1807 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1808 }
1809 return mSoundTriggerSupportsConcurrentCapture;
1810}
1811
Eric Laurentfb66dd92016-01-28 18:32:03 -08001812
Eric Laurent4dc68062014-07-28 17:26:49 -07001813status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001814 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001815 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001816 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001817{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001818
1819 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1820 input, session, silenced, *concurrency);
1821
Eric Laurentfb66dd92016-01-28 18:32:03 -08001822 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 ssize_t index = mInputs.indexOfKey(input);
1825 if (index < 0) {
1826 ALOGW("startInput() unknown input %d", input);
1827 return BAD_VALUE;
1828 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001829 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001830
Eric Laurent599c7582015-12-07 18:05:55 -08001831 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1832 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001833 ALOGW("startInput() unknown session %d on input %d", session, input);
1834 return BAD_VALUE;
1835 }
1836
Eric Laurent74708e72017-04-07 17:13:42 -07001837 if (!is_virtual_input_device(inputDesc->mDevice)) {
1838 if (mCallTxPatch != 0 &&
1839 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1840 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001841 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001842 return INVALID_OPERATION;
1843 }
1844
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001845 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001846
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001847 // If a UID is idle and records silence and another not silenced recording starts
1848 // from another UID (idle or active) we stop the current idle UID recording in
1849 // favor of the new one - "There can be only one" TM
1850 if (!silenced) {
1851 for (const auto& activeDesc : activeInputs) {
1852 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1853 activeDesc->getId() == inputDesc->getId()) {
1854 continue;
1855 }
1856
1857 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1858 true /*activeOnly*/);
1859 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1860 if (activeSession->isSilenced()) {
1861 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1862 audio_session_t activeSessionId = activeSession->session();
1863 stopInput(activeInput, activeSessionId);
1864 releaseInput(activeInput, activeSessionId);
1865 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1866 activeInputs = mInputs.getActiveInputs();
1867 }
1868 }
1869 }
1870
1871 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001872 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1873 activeDesc->getId() == inputDesc->getId()) {
1874 continue;
1875 }
1876
Eric Laurent74708e72017-04-07 17:13:42 -07001877 audio_source_t activeSource = activeDesc->inputSource(true);
1878 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1879 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1880 if (activeDesc->hasPreemptedSession(session)) {
1881 ALOGW("startInput(%d) failed for HOTWORD: "
1882 "other input %d already started for HOTWORD",
1883 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001884 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001885 return INVALID_OPERATION;
1886 }
1887 } else {
1888 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1889 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001890 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001891 return INVALID_OPERATION;
1892 }
1893 } else {
1894 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1895 ALOGW("startInput(%d) failed: other input %d already started",
1896 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001897 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001898 return INVALID_OPERATION;
1899 }
1900 }
1901 }
1902
Chris Thornton2b864642017-06-27 21:26:07 -07001903 // We only need to check if the sound trigger session supports concurrent capture if the
1904 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1905 // that's running.
1906 const bool allowConcurrentWithSoundTrigger =
1907 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1908
Eric Laurent74708e72017-04-07 17:13:42 -07001909 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001910 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001911 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1912 continue;
1913 }
1914
Eric Laurent74708e72017-04-07 17:13:42 -07001915 audio_source_t activeSource = activeDesc->inputSource(true);
1916 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1917 AudioSessionCollection activeSessions =
1918 activeDesc->getAudioSessions(true /*activeOnly*/);
1919 audio_session_t activeSession = activeSessions.keyAt(0);
1920 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1921 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001922 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001923 sessions.add(activeSession);
1924 inputDesc->setPreemptedSessions(sessions);
1925 stopInput(activeHandle, activeSession);
1926 releaseInput(activeHandle, activeSession);
1927 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1928 input, activeDesc->mIoHandle);
1929 }
1930 }
1931 }
Eric Laurente552edb2014-03-10 17:42:56 -07001932
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001933 // Make sure we start with the correct silence state
1934 audioSession->setSilenced(silenced);
1935
Eric Laurent313d1e72016-01-29 09:56:57 -08001936 // increment activity count before calling getNewInputDevice() below as only active sessions
1937 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07001938 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08001939
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001940 // Routing?
1941 mInputRoutes.incRouteActivity(session);
1942
Eric Laurent2157f5b2018-04-25 18:33:02 -07001943 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001944 // indicate active capture to sound trigger service if starting capture from a mic on
1945 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001946 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001947 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001948
Eric Laurent733ce942017-12-07 12:18:25 -08001949 status_t status = inputDesc->start();
1950 if (status != NO_ERROR) {
1951 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07001952 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08001953 return status;
1954 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001955
Eric Laurent733ce942017-12-07 12:18:25 -08001956 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001957 // if input maps to a dynamic policy with an activity listener, notify of state change
1958 if ((inputDesc->mPolicyMix != NULL)
1959 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1960 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1961 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001962 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001963
Eric Laurentf7c50102016-09-30 15:19:43 -07001964 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1965 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001966 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001967 SoundTrigger::setCaptureState(true);
1968 }
1969
1970 // automatically enable the remote submix output when input is started if not
1971 // used by a policy mix of type MIX_TYPE_RECORDERS
1972 // For remote submix (a virtual device), we open only one input per capture request.
1973 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1974 String8 address = String8("");
1975 if (inputDesc->mPolicyMix == NULL) {
1976 address = String8("0");
1977 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1978 address = inputDesc->mPolicyMix->mDeviceAddress;
1979 }
1980 if (address != "") {
1981 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1982 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1983 address, "remote-submix");
1984 }
Eric Laurentc722f302014-12-10 11:21:49 -08001985 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001986 }
Eric Laurente552edb2014-03-10 17:42:56 -07001987 }
1988
Eric Laurent599c7582015-12-07 18:05:55 -08001989 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001990
Eric Laurente552edb2014-03-10 17:42:56 -07001991 return NO_ERROR;
1992}
1993
Eric Laurent4dc68062014-07-28 17:26:49 -07001994status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1995 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001996{
1997 ALOGV("stopInput() input %d", input);
1998 ssize_t index = mInputs.indexOfKey(input);
1999 if (index < 0) {
2000 ALOGW("stopInput() unknown input %d", input);
2001 return BAD_VALUE;
2002 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002003 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002004
Eric Laurent599c7582015-12-07 18:05:55 -08002005 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002006 if (index < 0) {
2007 ALOGW("stopInput() unknown session %d on input %d", session, input);
2008 return BAD_VALUE;
2009 }
2010
Eric Laurent599c7582015-12-07 18:05:55 -08002011 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002012 ALOGW("stopInput() input %d already stopped", input);
2013 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002014 }
2015
Eric Laurenta18dced2018-07-20 15:14:54 -07002016 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002017
2018 // Routing?
2019 mInputRoutes.decRouteActivity(session);
2020
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002021 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002022 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002023 if (inputDesc->isActive()) {
2024 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2025 } else {
2026 // if input maps to a dynamic policy with an activity listener, notify of state change
2027 if ((inputDesc->mPolicyMix != NULL)
2028 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2029 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2030 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002031 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002032
2033 // automatically disable the remote submix output when input is stopped if not
2034 // used by a policy mix of type MIX_TYPE_RECORDERS
2035 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2036 String8 address = String8("");
2037 if (inputDesc->mPolicyMix == NULL) {
2038 address = String8("0");
2039 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2040 address = inputDesc->mPolicyMix->mDeviceAddress;
2041 }
2042 if (address != "") {
2043 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2044 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2045 address, "remote-submix");
2046 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002047 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002048
Eric Laurentf7c50102016-09-30 15:19:43 -07002049 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002050 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002051
Eric Laurentf7c50102016-09-30 15:19:43 -07002052 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2053 // primary HW module
2054 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2055 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2056 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002057 SoundTrigger::setCaptureState(false);
2058 }
2059 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002060 }
Eric Laurente552edb2014-03-10 17:42:56 -07002061 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002062 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002063}
2064
Eric Laurent4dc68062014-07-28 17:26:49 -07002065void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2066 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002067{
2068 ALOGV("releaseInput() %d", input);
2069 ssize_t index = mInputs.indexOfKey(input);
2070 if (index < 0) {
2071 ALOGW("releaseInput() releasing unknown input %d", input);
2072 return;
2073 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002074
2075 // Routing
2076 mInputRoutes.removeRoute(session);
2077
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002078 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2079 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002080
Eric Laurent599c7582015-12-07 18:05:55 -08002081 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002082 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002083 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2084 return;
2085 }
Eric Laurent599c7582015-12-07 18:05:55 -08002086
2087 if (audioSession->openCount() == 0) {
2088 ALOGW("releaseInput() invalid open count %d on session %d",
2089 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002090 return;
2091 }
Eric Laurent599c7582015-12-07 18:05:55 -08002092
2093 if (audioSession->changeOpenCount(-1) == 0) {
2094 inputDesc->removeAudioSession(session);
2095 }
2096
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002097 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002098 ALOGV("releaseInput() exit > 0");
2099 return;
2100 }
2101
Eric Laurent05b90f82014-08-27 15:32:29 -07002102 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002103 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002104 ALOGV("releaseInput() exit");
2105}
2106
Eric Laurentd4692962014-05-05 18:13:44 -07002107void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002108 bool patchRemoved = false;
2109
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002110 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002111 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002112 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002113 if (patch_index >= 0) {
2114 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002115 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002116 mAudioPatches.removeItemsAt(patch_index);
2117 patchRemoved = true;
2118 }
Eric Laurentfe231122017-11-17 17:48:06 -08002119 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002120 }
jiabin829a00b2018-04-04 16:28:32 -07002121 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002122 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002123 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002124 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002125
2126 if (patchRemoved) {
2127 mpClientInterface->onAudioPatchListUpdate();
2128 }
Eric Laurentd4692962014-05-05 18:13:44 -07002129}
2130
Eric Laurente0720872014-03-11 09:30:41 -07002131void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002132 int indexMin,
2133 int indexMax)
2134{
2135 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002136 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002137
2138 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002139 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2140 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002141 continue;
2142 }
2143 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002144 }
Eric Laurente552edb2014-03-10 17:42:56 -07002145}
2146
Eric Laurente0720872014-03-11 09:30:41 -07002147status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002148 int index,
2149 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002150{
2151
Nadav Bar7c605f62017-12-25 00:01:52 +02002152 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2153 // app that has MODIFY_PHONE_STATE permission.
2154 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2155 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002156 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002157 return BAD_VALUE;
2158 }
2159 if (!audio_is_output_device(device)) {
2160 return BAD_VALUE;
2161 }
2162
2163 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002164 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002165
Eric Laurent1fd372e2016-04-06 14:23:53 -07002166 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002167 stream, device, index);
2168
Eric Laurent28d09f02016-03-08 10:43:05 -08002169 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002170 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2171 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002172 continue;
2173 }
2174 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2175 }
Eric Laurente552edb2014-03-10 17:42:56 -07002176
Eric Laurent1fd372e2016-04-06 14:23:53 -07002177 // update volume on all outputs and streams matching the following:
2178 // - The requested stream (or a stream matching for volume control) is active on the output
2179 // - The device (or devices) selected by the strategy corresponding to this stream includes
2180 // the requested device
2181 // - For non default requested device, currently selected device on the output is either the
2182 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002183 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2184 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002185 status_t status = NO_ERROR;
2186 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002187 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2188 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002189 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002190 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002191 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002192 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002193 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002194 continue;
2195 }
Eric Laurent794fde22016-03-11 09:50:45 -08002196 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002197 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2198 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002199 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2200 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002201 continue;
2202 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002203 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002204 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002205 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002206 applyVolume = (curDevice & curStreamDevice) != 0;
2207 } else {
2208 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002209 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002210 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002211 // rescale index before applying to curStream as ranges may be different for
2212 // stream and curStream
2213 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002214 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002215 //FIXME: workaround for truncated touch sounds
2216 // delayed volume change for system stream to be removed when the problem is
2217 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002218 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002219 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002220 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002221 if (volStatus != NO_ERROR) {
2222 status = volStatus;
2223 }
2224 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002225 }
Eric Laurente552edb2014-03-10 17:42:56 -07002226 }
2227 return status;
2228}
2229
Eric Laurente0720872014-03-11 09:30:41 -07002230status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002231 int *index,
2232 audio_devices_t device)
2233{
2234 if (index == NULL) {
2235 return BAD_VALUE;
2236 }
2237 if (!audio_is_output_device(device)) {
2238 return BAD_VALUE;
2239 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002240 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002241 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002242 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002243 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2244 }
François Gaffiedfd74092015-03-19 12:10:59 +01002245 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002246
François Gaffied1ab2bd2015-12-02 18:20:06 +01002247 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002248 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2249 return NO_ERROR;
2250}
2251
Eric Laurent36829f92017-04-07 19:04:42 -07002252audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002253{
2254 // select one output among several suitable for global effects.
2255 // The priority is as follows:
2256 // 1: An offloaded output. If the effect ends up not being offloadable,
2257 // AudioFlinger will invalidate the track and the offloaded output
2258 // will be closed causing the effect to be moved to a PCM output.
2259 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002260 // 3: The primary output
2261 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002262
Eric Laurent3b73df72014-03-11 09:06:29 -07002263 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002264 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002265 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002266
Eric Laurent36829f92017-04-07 19:04:42 -07002267 if (outputs.size() == 0) {
2268 return AUDIO_IO_HANDLE_NONE;
2269 }
Eric Laurente552edb2014-03-10 17:42:56 -07002270
Eric Laurent36829f92017-04-07 19:04:42 -07002271 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2272 bool activeOnly = true;
2273
2274 while (output == AUDIO_IO_HANDLE_NONE) {
2275 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2276 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2277 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2278
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002279 for (audio_io_handle_t output : outputs) {
2280 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002281 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2282 continue;
2283 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002284 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2285 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002286 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002287 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002288 }
2289 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002290 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002291 }
2292 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002293 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002294 }
2295 }
2296 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2297 output = outputOffloaded;
2298 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2299 output = outputDeepBuffer;
2300 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2301 output = outputPrimary;
2302 } else {
2303 output = outputs[0];
2304 }
2305 activeOnly = false;
2306 }
2307
2308 if (output != mMusicEffectOutput) {
2309 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2310 mMusicEffectOutput = output;
2311 }
2312
2313 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002314 return output;
2315}
2316
Eric Laurent36829f92017-04-07 19:04:42 -07002317audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2318{
2319 return selectOutputForMusicEffects();
2320}
2321
Eric Laurente0720872014-03-11 09:30:41 -07002322status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002323 audio_io_handle_t io,
2324 uint32_t strategy,
2325 int session,
2326 int id)
2327{
2328 ssize_t index = mOutputs.indexOfKey(io);
2329 if (index < 0) {
2330 index = mInputs.indexOfKey(io);
2331 if (index < 0) {
2332 ALOGW("registerEffect() unknown io %d", io);
2333 return INVALID_OPERATION;
2334 }
2335 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002336 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002337}
2338
Eric Laurentc75307b2015-03-17 15:29:32 -07002339bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2340{
Eric Laurent28d09f02016-03-08 10:43:05 -08002341 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002342 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2343 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002344 continue;
2345 }
2346 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2347 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002348 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002349}
2350
2351bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2352{
2353 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2354}
2355
Eric Laurente0720872014-03-11 09:30:41 -07002356bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002357{
2358 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002359 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002360 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002361 return true;
2362 }
2363 }
2364 return false;
2365}
2366
Eric Laurent275e8e92014-11-30 15:14:47 -08002367// Register a list of custom mixes with their attributes and format.
2368// When a mix is registered, corresponding input and output profiles are
2369// added to the remote submix hw module. The profile contains only the
2370// parameters (sampling rate, format...) specified by the mix.
2371// The corresponding input remote submix device is also connected.
2372//
2373// When a remote submix device is connected, the address is checked to select the
2374// appropriate profile and the corresponding input or output stream is opened.
2375//
2376// When capture starts, getInputForAttr() will:
2377// - 1 look for a mix matching the address passed in attribtutes tags if any
2378// - 2 if none found, getDeviceForInputSource() will:
2379// - 2.1 look for a mix matching the attributes source
2380// - 2.2 if none found, default to device selection by policy rules
2381// At this time, the corresponding output remote submix device is also connected
2382// and active playback use cases can be transferred to this mix if needed when reconnecting
2383// after AudioTracks are invalidated
2384//
2385// When playback starts, getOutputForAttr() will:
2386// - 1 look for a mix matching the address passed in attribtutes tags if any
2387// - 2 if none found, look for a mix matching the attributes usage
2388// - 3 if none found, default to device and output selection by policy rules.
2389
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002390status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002391{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002392 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2393 status_t res = NO_ERROR;
2394
2395 sp<HwModule> rSubmixModule;
2396 // examine each mix's route type
2397 for (size_t i = 0; i < mixes.size(); i++) {
2398 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2399 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2400 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002401 break;
2402 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002403 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002404 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002405 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002406 rSubmixModule = mHwModules.getModuleFromName(
2407 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2408 if (rSubmixModule == 0) {
2409 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2410 i);
2411 res = INVALID_OPERATION;
2412 break;
2413 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002414 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002415
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002416 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002417
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002418 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002419 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002420 res = INVALID_OPERATION;
2421 break;
2422 }
2423 audio_config_t outputConfig = mixes[i].mFormat;
2424 audio_config_t inputConfig = mixes[i].mFormat;
2425 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2426 // stereo and let audio flinger do the channel conversion if needed.
2427 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2428 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2429 rSubmixModule->addOutputProfile(address, &outputConfig,
2430 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2431 rSubmixModule->addInputProfile(address, &inputConfig,
2432 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002433
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002434 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2435 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2436 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2437 address.string(), "remote-submix");
2438 } else {
2439 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2440 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2441 address.string(), "remote-submix");
2442 }
2443 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002444 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002445 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002446 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2447 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002448
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002449 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002450 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2451 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2452 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2453 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2454 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2455 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002456 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2457 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002458 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2459 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002460 } else {
2461 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002462 }
2463 break;
2464 }
2465 }
2466
2467 if (res != NO_ERROR) {
2468 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002469 i, device, address.string());
2470 res = INVALID_OPERATION;
2471 break;
2472 } else if (!foundOutput) {
2473 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2474 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 res = INVALID_OPERATION;
2476 break;
2477 }
Eric Laurentc722f302014-12-10 11:21:49 -08002478 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002479 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 if (res != NO_ERROR) {
2481 unregisterPolicyMixes(mixes);
2482 }
2483 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002484}
2485
2486status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2487{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002488 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002489 status_t res = NO_ERROR;
2490 sp<HwModule> rSubmixModule;
2491 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002492 for (const auto& mix : mixes) {
2493 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002494
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002495 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002496 rSubmixModule = mHwModules.getModuleFromName(
2497 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2498 if (rSubmixModule == 0) {
2499 res = INVALID_OPERATION;
2500 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002501 }
2502 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002503
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002504 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002505
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002506 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2507 res = INVALID_OPERATION;
2508 continue;
2509 }
2510
2511 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2512 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2513 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2514 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2515 address.string(), "remote-submix");
2516 }
2517 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2519 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2520 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2521 address.string(), "remote-submix");
2522 }
2523 rSubmixModule->removeOutputProfile(address);
2524 rSubmixModule->removeInputProfile(address);
2525
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002526 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2527 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002528 res = INVALID_OPERATION;
2529 continue;
2530 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002532 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002534}
2535
Eric Laurente552edb2014-03-10 17:42:56 -07002536
Eric Laurente0720872014-03-11 09:30:41 -07002537status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002538{
Eric Laurente552edb2014-03-10 17:42:56 -07002539 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002540 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2541 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002542 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002543 std::string stateLiteral;
2544 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002545 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2546 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2547 "communications", "media", "record", "dock", "system",
2548 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2549 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2550 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2551 result.appendFormat(" Force use for %s: %d\n",
2552 forceUses[i], mEngine->getForceUse(i));
2553 }
2554 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2555 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2556 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002557 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002558
François Gaffie112b0af2015-11-19 16:13:25 +01002559 mAvailableOutputDevices.dump(fd, String8("Available output"));
2560 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002561 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002562 mOutputs.dump(fd);
2563 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002564 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002565 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002566 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002567 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002568
2569 return NO_ERROR;
2570}
2571
2572// This function checks for the parameters which can be offloaded.
2573// This can be enhanced depending on the capability of the DSP and policy
2574// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002575bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002576{
2577 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002578 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002579 offloadInfo.sample_rate, offloadInfo.channel_mask,
2580 offloadInfo.format,
2581 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2582 offloadInfo.has_video);
2583
Andy Hung2ddee192015-12-18 17:34:44 -08002584 if (mMasterMono) {
2585 return false; // no offloading if mono is set.
2586 }
2587
Eric Laurente552edb2014-03-10 17:42:56 -07002588 // Check if offload has been disabled
2589 char propValue[PROPERTY_VALUE_MAX];
2590 if (property_get("audio.offload.disable", propValue, "0")) {
2591 if (atoi(propValue) != 0) {
2592 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2593 return false;
2594 }
2595 }
2596
2597 // Check if stream type is music, then only allow offload as of now.
2598 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2599 {
2600 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2601 return false;
2602 }
2603
2604 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002605 const bool allowOffloadWithVideo =
2606 property_get_bool("audio.offload.video", false /* default_value */);
2607 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002608 ALOGV("isOffloadSupported: has_video == true, returning false");
2609 return false;
2610 }
2611
2612 //If duration is less than minimum value defined in property, return false
2613 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2614 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2615 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2616 return false;
2617 }
2618 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2619 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2620 return false;
2621 }
2622
2623 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2624 // creating an offloaded track and tearing it down immediately after start when audioflinger
2625 // detects there is an active non offloadable effect.
2626 // FIXME: We should check the audio session here but we do not have it in this context.
2627 // This may prevent offloading in rare situations where effects are left active by apps
2628 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002629 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002630 return false;
2631 }
2632
2633 // See if there is a profile to support this.
2634 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002635 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002636 offloadInfo.sample_rate,
2637 offloadInfo.format,
2638 offloadInfo.channel_mask,
2639 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002640 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2641 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002642}
2643
Eric Laurent6a94d692014-05-20 11:18:06 -07002644status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2645 audio_port_type_t type,
2646 unsigned int *num_ports,
2647 struct audio_port *ports,
2648 unsigned int *generation)
2649{
2650 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2651 generation == NULL) {
2652 return BAD_VALUE;
2653 }
2654 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2655 if (ports == NULL) {
2656 *num_ports = 0;
2657 }
2658
2659 size_t portsWritten = 0;
2660 size_t portsMax = *num_ports;
2661 *num_ports = 0;
2662 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002663 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2664 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002665 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002666 for (const auto& dev : mAvailableOutputDevices) {
2667 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002668 continue;
2669 }
2670 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002671 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002672 }
2673 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002674 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002675 }
2676 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002677 for (const auto& dev : mAvailableInputDevices) {
2678 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002679 continue;
2680 }
2681 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002682 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002683 }
2684 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002685 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002686 }
2687 }
2688 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2689 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2690 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2691 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2692 }
2693 *num_ports += mInputs.size();
2694 }
2695 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002696 size_t numOutputs = 0;
2697 for (size_t i = 0; i < mOutputs.size(); i++) {
2698 if (!mOutputs[i]->isDuplicated()) {
2699 numOutputs++;
2700 if (portsWritten < portsMax) {
2701 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2702 }
2703 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002704 }
Eric Laurent84c70242014-06-23 08:46:27 -07002705 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 }
2707 }
2708 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002709 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002710 return NO_ERROR;
2711}
2712
Eric Laurent99fcae42018-05-17 16:59:18 -07002713status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002714{
Eric Laurent99fcae42018-05-17 16:59:18 -07002715 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2716 return BAD_VALUE;
2717 }
2718 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2719 if (dev != 0) {
2720 dev->toAudioPort(port);
2721 return NO_ERROR;
2722 }
2723 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2724 if (dev != 0) {
2725 dev->toAudioPort(port);
2726 return NO_ERROR;
2727 }
2728 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2729 if (out != 0) {
2730 out->toAudioPort(port);
2731 return NO_ERROR;
2732 }
2733 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2734 if (in != 0) {
2735 in->toAudioPort(port);
2736 return NO_ERROR;
2737 }
2738 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002739}
2740
Eric Laurent6a94d692014-05-20 11:18:06 -07002741status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2742 audio_patch_handle_t *handle,
2743 uid_t uid)
2744{
2745 ALOGV("createAudioPatch()");
2746
2747 if (handle == NULL || patch == NULL) {
2748 return BAD_VALUE;
2749 }
2750 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2751
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002752 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002753 return BAD_VALUE;
2754 }
2755 // only one source per audio patch supported for now
2756 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 return INVALID_OPERATION;
2758 }
Eric Laurent874c42872014-08-08 15:13:39 -07002759
2760 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002761 return INVALID_OPERATION;
2762 }
Eric Laurent874c42872014-08-08 15:13:39 -07002763 for (size_t i = 0; i < patch->num_sinks; i++) {
2764 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2765 return INVALID_OPERATION;
2766 }
2767 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002768
2769 sp<AudioPatch> patchDesc;
2770 ssize_t index = mAudioPatches.indexOfKey(*handle);
2771
Eric Laurent6a94d692014-05-20 11:18:06 -07002772 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2773 patch->sources[0].role,
2774 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002775#if LOG_NDEBUG == 0
2776 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002777 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002778 patch->sinks[i].role,
2779 patch->sinks[i].type);
2780 }
2781#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002782
2783 if (index >= 0) {
2784 patchDesc = mAudioPatches.valueAt(index);
2785 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2786 mUidCached, patchDesc->mUid, uid);
2787 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2788 return INVALID_OPERATION;
2789 }
2790 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002791 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002792 }
2793
2794 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002795 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002796 if (outputDesc == NULL) {
2797 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2798 return BAD_VALUE;
2799 }
Eric Laurent84c70242014-06-23 08:46:27 -07002800 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2801 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002802 if (patchDesc != 0) {
2803 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2804 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2805 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2806 return BAD_VALUE;
2807 }
2808 }
Eric Laurent874c42872014-08-08 15:13:39 -07002809 DeviceVector devices;
2810 for (size_t i = 0; i < patch->num_sinks; i++) {
2811 // Only support mix to devices connection
2812 // TODO add support for mix to mix connection
2813 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2814 ALOGV("createAudioPatch() source mix but sink is not a device");
2815 return INVALID_OPERATION;
2816 }
2817 sp<DeviceDescriptor> devDesc =
2818 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2819 if (devDesc == 0) {
2820 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2821 return BAD_VALUE;
2822 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002823
François Gaffie53615e22015-03-19 09:24:12 +01002824 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002825 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002826 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002827 NULL, // updatedSamplingRate
2828 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002829 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002830 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002831 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002832 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002833 ALOGV("createAudioPatch() profile not supported for device %08x",
2834 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002835 return INVALID_OPERATION;
2836 }
2837 devices.add(devDesc);
2838 }
2839 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002840 return INVALID_OPERATION;
2841 }
Eric Laurent874c42872014-08-08 15:13:39 -07002842
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 // TODO: reconfigure output format and channels here
2844 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002845 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002846 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002847 index = mAudioPatches.indexOfKey(*handle);
2848 if (index >= 0) {
2849 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2850 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2851 }
2852 patchDesc = mAudioPatches.valueAt(index);
2853 patchDesc->mUid = uid;
2854 ALOGV("createAudioPatch() success");
2855 } else {
2856 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2857 return INVALID_OPERATION;
2858 }
2859 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2860 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2861 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002862 // only one sink supported when connecting an input device to a mix
2863 if (patch->num_sinks > 1) {
2864 return INVALID_OPERATION;
2865 }
François Gaffie53615e22015-03-19 09:24:12 +01002866 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002867 if (inputDesc == NULL) {
2868 return BAD_VALUE;
2869 }
2870 if (patchDesc != 0) {
2871 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2872 return BAD_VALUE;
2873 }
2874 }
2875 sp<DeviceDescriptor> devDesc =
2876 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2877 if (devDesc == 0) {
2878 return BAD_VALUE;
2879 }
2880
François Gaffie53615e22015-03-19 09:24:12 +01002881 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002882 devDesc->mAddress,
2883 patch->sinks[0].sample_rate,
2884 NULL, /*updatedSampleRate*/
2885 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002886 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002887 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002888 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002889 // FIXME for the parameter type,
2890 // and the NONE
2891 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002892 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002893 return INVALID_OPERATION;
2894 }
2895 // TODO: reconfigure output format and channels here
2896 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002897 devDesc->type(), inputDesc->mIoHandle);
2898 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002899 index = mAudioPatches.indexOfKey(*handle);
2900 if (index >= 0) {
2901 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2902 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2903 }
2904 patchDesc = mAudioPatches.valueAt(index);
2905 patchDesc->mUid = uid;
2906 ALOGV("createAudioPatch() success");
2907 } else {
2908 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2909 return INVALID_OPERATION;
2910 }
2911 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2912 // device to device connection
2913 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002914 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 return BAD_VALUE;
2916 }
2917 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002918 sp<DeviceDescriptor> srcDeviceDesc =
2919 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002920 if (srcDeviceDesc == 0) {
2921 return BAD_VALUE;
2922 }
Eric Laurent874c42872014-08-08 15:13:39 -07002923
Eric Laurent6a94d692014-05-20 11:18:06 -07002924 //update source and sink with our own data as the data passed in the patch may
2925 // be incomplete.
2926 struct audio_patch newPatch = *patch;
2927 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002928
Eric Laurent874c42872014-08-08 15:13:39 -07002929 for (size_t i = 0; i < patch->num_sinks; i++) {
2930 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2931 ALOGV("createAudioPatch() source device but one sink is not a device");
2932 return INVALID_OPERATION;
2933 }
2934
2935 sp<DeviceDescriptor> sinkDeviceDesc =
2936 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2937 if (sinkDeviceDesc == 0) {
2938 return BAD_VALUE;
2939 }
2940 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2941
Eric Laurent3bcf8592015-04-03 12:13:24 -07002942 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002943 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07002944 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002945 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002946 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002947 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002948 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002949 return INVALID_OPERATION;
2950 }
Eric Laurent874c42872014-08-08 15:13:39 -07002951 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002952 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002953 // if the sink device is reachable via an opened output stream, request to go via
2954 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002955 audio_io_handle_t output = selectOutput(outputs,
2956 AUDIO_OUTPUT_FLAG_NONE,
2957 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002958 if (output != AUDIO_IO_HANDLE_NONE) {
2959 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2960 if (outputDesc->isDuplicated()) {
2961 return INVALID_OPERATION;
2962 }
2963 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002964 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002965 newPatch.num_sources = 2;
2966 }
Eric Laurent83b88082014-06-20 18:31:16 -07002967 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002968 }
2969 // TODO: check from routing capabilities in config file and other conflicting patches
2970
Mikhail Naganovdc769682018-05-04 15:34:08 -07002971 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
2972 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002973 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2974 status);
2975 return INVALID_OPERATION;
2976 }
2977 } else {
2978 return BAD_VALUE;
2979 }
2980 } else {
2981 return BAD_VALUE;
2982 }
2983 return NO_ERROR;
2984}
2985
2986status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2987 uid_t uid)
2988{
2989 ALOGV("releaseAudioPatch() patch %d", handle);
2990
2991 ssize_t index = mAudioPatches.indexOfKey(handle);
2992
2993 if (index < 0) {
2994 return BAD_VALUE;
2995 }
2996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2997 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2998 mUidCached, patchDesc->mUid, uid);
2999 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3000 return INVALID_OPERATION;
3001 }
3002
3003 struct audio_patch *patch = &patchDesc->mPatch;
3004 patchDesc->mUid = mUidCached;
3005 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003006 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003007 if (outputDesc == NULL) {
3008 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3009 return BAD_VALUE;
3010 }
3011
Eric Laurentc75307b2015-03-17 15:29:32 -07003012 setOutputDevice(outputDesc,
3013 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 true,
3015 0,
3016 NULL);
3017 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3018 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003019 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003020 if (inputDesc == NULL) {
3021 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3022 return BAD_VALUE;
3023 }
3024 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003025 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003026 true,
3027 NULL);
3028 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3030 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3031 status, patchDesc->mAfPatchHandle);
3032 removeAudioPatch(patchDesc->mHandle);
3033 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003034 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003035 } else {
3036 return BAD_VALUE;
3037 }
3038 } else {
3039 return BAD_VALUE;
3040 }
3041 return NO_ERROR;
3042}
3043
3044status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3045 struct audio_patch *patches,
3046 unsigned int *generation)
3047{
François Gaffie53615e22015-03-19 09:24:12 +01003048 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 return BAD_VALUE;
3050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003052 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003053}
3054
Eric Laurente1715a42014-05-20 11:30:42 -07003055status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003056{
Eric Laurente1715a42014-05-20 11:30:42 -07003057 ALOGV("setAudioPortConfig()");
3058
3059 if (config == NULL) {
3060 return BAD_VALUE;
3061 }
3062 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3063 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003064 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3065 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003066 }
3067
Eric Laurenta121f902014-06-03 13:32:54 -07003068 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003069 if (config->type == AUDIO_PORT_TYPE_MIX) {
3070 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003071 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003072 if (outputDesc == NULL) {
3073 return BAD_VALUE;
3074 }
Eric Laurent84c70242014-06-23 08:46:27 -07003075 ALOG_ASSERT(!outputDesc->isDuplicated(),
3076 "setAudioPortConfig() called on duplicated output %d",
3077 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003078 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003079 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003080 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003081 if (inputDesc == NULL) {
3082 return BAD_VALUE;
3083 }
Eric Laurenta121f902014-06-03 13:32:54 -07003084 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003085 } else {
3086 return BAD_VALUE;
3087 }
3088 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3089 sp<DeviceDescriptor> deviceDesc;
3090 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3091 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3092 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3093 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3094 } else {
3095 return BAD_VALUE;
3096 }
3097 if (deviceDesc == NULL) {
3098 return BAD_VALUE;
3099 }
Eric Laurenta121f902014-06-03 13:32:54 -07003100 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003101 } else {
3102 return BAD_VALUE;
3103 }
3104
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003105 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003106 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3107 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003108 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003109 audioPortConfig->toAudioPortConfig(&newConfig, config);
3110 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003111 }
Eric Laurenta121f902014-06-03 13:32:54 -07003112 if (status != NO_ERROR) {
3113 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003114 }
Eric Laurente1715a42014-05-20 11:30:42 -07003115
3116 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003117}
3118
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003119void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3120{
Eric Laurentd60560a2015-04-10 11:31:20 -07003121 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003122 clearAudioPatches(uid);
3123 clearSessionRoutes(uid);
3124}
3125
Eric Laurent6a94d692014-05-20 11:18:06 -07003126void AudioPolicyManager::clearAudioPatches(uid_t uid)
3127{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003128 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003129 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3130 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003131 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 }
3133 }
3134}
3135
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003136void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3137 audio_io_handle_t ouptutToSkip)
3138{
3139 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3140 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3141 for (size_t j = 0; j < mOutputs.size(); j++) {
3142 if (mOutputs.keyAt(j) == ouptutToSkip) {
3143 continue;
3144 }
3145 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3146 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3147 continue;
3148 }
3149 // If the default device for this strategy is on another output mix,
3150 // invalidate all tracks in this strategy to force re connection.
3151 // Otherwise select new device on the output mix.
3152 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003153 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003154 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3155 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3156 }
3157 }
3158 } else {
3159 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3160 setOutputDevice(outputDesc, newDevice, false);
3161 }
3162 }
3163}
3164
3165void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3166{
3167 // remove output routes associated with this uid
3168 SortedVector<routing_strategy> affectedStrategies;
3169 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3170 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3171 if (route->mUid == uid) {
3172 mOutputRoutes.removeItemsAt(i);
3173 if (route->mDeviceDescriptor != 0) {
3174 affectedStrategies.add(getStrategy(route->mStreamType));
3175 }
3176 }
3177 }
3178 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003179 for (const auto& strategy : affectedStrategies) {
3180 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003181 }
3182
3183 // remove input routes associated with this uid
3184 SortedVector<audio_source_t> affectedSources;
3185 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3186 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3187 if (route->mUid == uid) {
3188 mInputRoutes.removeItemsAt(i);
3189 if (route->mDeviceDescriptor != 0) {
3190 affectedSources.add(route->mSource);
3191 }
3192 }
3193 }
3194 // reroute inputs if necessary
3195 SortedVector<audio_io_handle_t> inputsToClose;
3196 for (size_t i = 0; i < mInputs.size(); i++) {
3197 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003198 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003199 inputsToClose.add(inputDesc->mIoHandle);
3200 }
3201 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003202 for (const auto& input : inputsToClose) {
3203 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003204 }
3205}
3206
Eric Laurentd60560a2015-04-10 11:31:20 -07003207void AudioPolicyManager::clearAudioSources(uid_t uid)
3208{
3209 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3210 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3211 if (sourceDesc->mUid == uid) {
3212 stopAudioSource(mAudioSources.keyAt(i));
3213 }
3214 }
3215}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003216
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003217status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3218 audio_io_handle_t *ioHandle,
3219 audio_devices_t *device)
3220{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003221 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3222 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003223 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003224
François Gaffiedf372692015-03-19 10:43:27 +01003225 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003226}
3227
Eric Laurentd60560a2015-04-10 11:31:20 -07003228status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3229 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003230 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003231 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003232{
Eric Laurentd60560a2015-04-10 11:31:20 -07003233 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3234 if (source == NULL || attributes == NULL || handle == NULL) {
3235 return BAD_VALUE;
3236 }
3237
Glenn Kasten559d4392016-03-29 13:42:57 -07003238 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003239
3240 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3241 source->type != AUDIO_PORT_TYPE_DEVICE) {
3242 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3243 return INVALID_OPERATION;
3244 }
3245
3246 sp<DeviceDescriptor> srcDeviceDesc =
3247 mAvailableInputDevices.getDevice(source->ext.device.type,
3248 String8(source->ext.device.address));
3249 if (srcDeviceDesc == 0) {
3250 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3251 return BAD_VALUE;
3252 }
3253 sp<AudioSourceDescriptor> sourceDesc =
3254 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3255
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003256 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003257 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3258 sourceDesc->mPatchDesc = patchDesc;
3259
3260 status_t status = connectAudioSource(sourceDesc);
3261 if (status == NO_ERROR) {
3262 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3263 *handle = sourceDesc->getHandle();
3264 }
3265 return status;
3266}
3267
3268status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3269{
3270 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3271
3272 // make sure we only have one patch per source.
3273 disconnectAudioSource(sourceDesc);
3274
3275 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003276 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003277 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3278
3279 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3280 sp<DeviceDescriptor> sinkDeviceDesc =
3281 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3282
3283 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003284
3285 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3286 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003287 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003288 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3289 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3290 // create patch between src device and output device
3291 // create Hwoutput and add to mHwOutputs
3292 } else {
3293 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3294 audio_io_handle_t output =
3295 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3296 if (output == AUDIO_IO_HANDLE_NONE) {
3297 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3298 return INVALID_OPERATION;
3299 }
3300 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3301 if (outputDesc->isDuplicated()) {
3302 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3303 return INVALID_OPERATION;
3304 }
Eric Laurent733ce942017-12-07 12:18:25 -08003305 status_t status = outputDesc->start();
3306 if (status != NO_ERROR) {
3307 return status;
3308 }
3309
Eric Laurentd60560a2015-04-10 11:31:20 -07003310 // create a special patch with no sink and two sources:
3311 // - the second source indicates to PatchPanel through which output mix this patch should
3312 // be connected as well as the stream type for volume control
3313 // - the sink is defined by whatever output device is currently selected for the output
3314 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003315 PatchBuilder patchBuilder;
3316 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3317 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003318 &afPatchHandle,
3319 0);
3320 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3321 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003322 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003323 if (status != NO_ERROR) {
3324 ALOGW("%s patch panel could not connect device patch, error %d",
3325 __FUNCTION__, status);
3326 return INVALID_OPERATION;
3327 }
3328 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003329 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003330
3331 if (status != NO_ERROR) {
3332 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3333 return status;
3334 }
3335 sourceDesc->mSwOutput = outputDesc;
3336 if (delayMs != 0) {
3337 usleep(delayMs * 1000);
3338 }
3339 }
3340
3341 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3342 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3343
3344 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003345}
3346
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07003347status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle)
Eric Laurent554a2772015-04-10 11:29:24 -07003348{
Eric Laurentd60560a2015-04-10 11:31:20 -07003349 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3350 ALOGV("%s handle %d", __FUNCTION__, handle);
3351 if (sourceDesc == 0) {
3352 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3353 return BAD_VALUE;
3354 }
3355 status_t status = disconnectAudioSource(sourceDesc);
3356
3357 mAudioSources.removeItem(handle);
3358 return status;
3359}
3360
Andy Hung2ddee192015-12-18 17:34:44 -08003361status_t AudioPolicyManager::setMasterMono(bool mono)
3362{
3363 if (mMasterMono == mono) {
3364 return NO_ERROR;
3365 }
3366 mMasterMono = mono;
3367 // if enabling mono we close all offloaded devices, which will invalidate the
3368 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3369 // for recreating the new AudioTrack as non-offloaded PCM.
3370 //
3371 // If disabling mono, we leave all tracks as is: we don't know which clients
3372 // and tracks are able to be recreated as offloaded. The next "song" should
3373 // play back offloaded.
3374 if (mMasterMono) {
3375 Vector<audio_io_handle_t> offloaded;
3376 for (size_t i = 0; i < mOutputs.size(); ++i) {
3377 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3378 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3379 offloaded.push(desc->mIoHandle);
3380 }
3381 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003382 for (const auto& handle : offloaded) {
3383 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003384 }
3385 }
3386 // update master mono for all remaining outputs
3387 for (size_t i = 0; i < mOutputs.size(); ++i) {
3388 updateMono(mOutputs.keyAt(i));
3389 }
3390 return NO_ERROR;
3391}
3392
3393status_t AudioPolicyManager::getMasterMono(bool *mono)
3394{
3395 *mono = mMasterMono;
3396 return NO_ERROR;
3397}
3398
Eric Laurentac9cef52017-06-09 15:46:26 -07003399float AudioPolicyManager::getStreamVolumeDB(
3400 audio_stream_type_t stream, int index, audio_devices_t device)
3401{
3402 return computeVolume(stream, index, device);
3403}
3404
jiabin81772902018-04-02 17:52:27 -07003405status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3406 FormatVector& formats) {
3407 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3408 return BAD_VALUE;
3409 }
3410 String8 reply;
3411 reply = mpClientInterface->getParameters(
3412 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3413 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3414 AudioParameter repliedParameters(reply);
3415 if (repliedParameters.get(
3416 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3417 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3418 return BAD_VALUE;
3419 }
3420 for (auto format : formatsFromString(reply.string())) {
3421 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3422 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3423 if (format == AAC_FORMATS[i]) {
3424 format = AUDIO_FORMAT_AAC_LC;
3425 break;
3426 }
3427 }
3428 bool exist = false;
3429 for (size_t i = 0; i < formats.size(); i++) {
3430 if (format == formats[i]) {
3431 exist = true;
3432 break;
3433 }
3434 }
3435 bool isSurroundFormat = false;
3436 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3437 if (SURROUND_FORMATS[i] == format) {
3438 isSurroundFormat = true;
3439 break;
3440 }
3441 }
3442 if (!exist && isSurroundFormat) {
3443 formats.add(format);
3444 }
3445 }
3446 return NO_ERROR;
3447}
3448
3449status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3450 audio_format_t *surroundFormats,
3451 bool *surroundFormatsEnabled,
3452 bool reported)
3453{
3454 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3455 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3456 return BAD_VALUE;
3457 }
3458 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3459 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3460
3461 // Only return value if there is HDMI output.
3462 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3463 return INVALID_OPERATION;
3464 }
3465
3466 size_t formatsWritten = 0;
3467 size_t formatsMax = *numSurroundFormats;
3468 *numSurroundFormats = 0;
3469 FormatVector formats;
3470 if (reported) {
3471 // Only get surround formats which are reported by device.
3472 // First list already open outputs that can be routed to this device
3473 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3474 SortedVector<audio_io_handle_t> outputs;
3475 bool reportedFormatFound = false;
3476 status_t status;
3477 sp<SwAudioOutputDescriptor> desc;
3478 for (size_t i = 0; i < mOutputs.size(); i++) {
3479 desc = mOutputs.valueAt(i);
3480 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3481 outputs.add(mOutputs.keyAt(i));
3482 }
3483 }
3484 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003485 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003486 AUDIO_DEVICE_OUT_HDMI);
3487 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3488 String8 address = hdmiOutputDevices[i]->mAddress;
3489 for (const auto& hwModule : mHwModules) {
3490 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3491 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3492 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3493 profile->supportDeviceAddress(address)) {
3494 size_t j;
3495 for (j = 0; j < outputs.size(); j++) {
3496 desc = mOutputs.valueFor(outputs.itemAt(j));
3497 if (!desc->isDuplicated() && desc->mProfile == profile) {
3498 break;
3499 }
3500 }
3501 if (j != outputs.size()) {
3502 status = getSupportedFormats(outputs.itemAt(j), formats);
3503 reportedFormatFound |= (status == NO_ERROR);
3504 continue;
3505 }
3506
3507 if (!profile->canOpenNewIo()) {
3508 ALOGW("Max Output number %u already opened for this profile %s",
3509 profile->maxOpenCount, profile->getTagName().c_str());
3510 continue;
3511 }
3512
3513 ALOGV("opening output for device %08x with params %s profile %p name %s",
3514 device, address.string(), profile.get(), profile->getName().string());
3515 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3516 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3517 status_t status = desc->open(nullptr, device, address,
3518 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3519 &output);
3520
3521 if (status == NO_ERROR) {
3522 status = getSupportedFormats(output, formats);
3523 reportedFormatFound |= (status == NO_ERROR);
3524 desc->close();
3525 output = AUDIO_IO_HANDLE_NONE;
3526 }
3527 }
3528 }
3529 }
3530 }
3531
3532 if (!reportedFormatFound) {
3533 return UNKNOWN_ERROR;
3534 }
3535 } else {
3536 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3537 formats.add(SURROUND_FORMATS[i]);
3538 }
3539 }
3540 for (size_t i = 0; i < formats.size(); i++) {
3541 if (formatsWritten < formatsMax) {
3542 surroundFormats[formatsWritten] = formats[i];
3543 bool formatEnabled = false;
3544 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3545 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3546 formatEnabled =
3547 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3548 break;
3549 }
3550 } else {
3551 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3552 }
3553 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3554 }
3555 (*numSurroundFormats)++;
3556 }
3557 return NO_ERROR;
3558}
3559
3560status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3561{
3562 // Check if audio format is a surround formats.
3563 bool isSurroundFormat = false;
3564 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3565 if (audioFormat == SURROUND_FORMATS[i]) {
3566 isSurroundFormat = true;
3567 break;
3568 }
3569 }
3570 if (!isSurroundFormat) {
3571 return BAD_VALUE;
3572 }
3573
3574 // Should only be called when MANUAL.
3575 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3576 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3577 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3578 return INVALID_OPERATION;
3579 }
3580
3581 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3582 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3583 return NO_ERROR;
3584 }
3585
3586 // The operation is valid only when there is HDMI output available.
3587 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3588 return INVALID_OPERATION;
3589 }
3590
3591 if (enabled) {
3592 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3593 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3594 mSurroundFormats.insert(AAC_FORMATS[i]);
3595 }
3596 } else {
3597 mSurroundFormats.insert(audioFormat);
3598 }
3599 } else {
3600 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3601 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3602 mSurroundFormats.erase(AAC_FORMATS[i]);
3603 }
3604 } else {
3605 mSurroundFormats.erase(audioFormat);
3606 }
3607 }
3608
3609 sp<SwAudioOutputDescriptor> outputDesc;
3610 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003611 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003612 AUDIO_DEVICE_OUT_HDMI);
3613 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3614 // Simulate reconnection to update enabled surround sound formats.
3615 String8 address = hdmiOutputDevices[i]->mAddress;
3616 String8 name = hdmiOutputDevices[i]->getName();
3617 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3618 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3619 address.c_str(),
3620 name.c_str());
3621 if (status != NO_ERROR) {
3622 continue;
3623 }
3624 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3625 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3626 address.c_str(),
3627 name.c_str());
3628 profileUpdated |= (status == NO_ERROR);
3629 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003630 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003631 AUDIO_DEVICE_IN_HDMI);
3632 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3633 // Simulate reconnection to update enabled surround sound formats.
3634 String8 address = hdmiInputDevices[i]->mAddress;
3635 String8 name = hdmiInputDevices[i]->getName();
3636 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3637 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3638 address.c_str(),
3639 name.c_str());
3640 if (status != NO_ERROR) {
3641 continue;
3642 }
3643 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3644 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3645 address.c_str(),
3646 name.c_str());
3647 profileUpdated |= (status == NO_ERROR);
3648 }
3649
3650 // Undo the surround formats change due to no audio profiles updated.
3651 if (!profileUpdated) {
3652 if (enabled) {
3653 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3654 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3655 mSurroundFormats.erase(AAC_FORMATS[i]);
3656 }
3657 } else {
3658 mSurroundFormats.erase(audioFormat);
3659 }
3660 } else {
3661 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3662 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3663 mSurroundFormats.insert(AAC_FORMATS[i]);
3664 }
3665 } else {
3666 mSurroundFormats.insert(audioFormat);
3667 }
3668 }
3669 }
3670
3671 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3672}
3673
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003674void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3675{
3676 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3677
3678 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3679 for (size_t i = 0; i < activeInputs.size(); i++) {
3680 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3681 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3682 for (size_t j = 0; j < activeSessions.size(); j++) {
3683 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3684 if (activeSession->uid() == uid) {
3685 activeSession->setSilenced(silenced);
3686 }
3687 }
3688 }
3689}
3690
Eric Laurentd60560a2015-04-10 11:31:20 -07003691status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3692{
3693 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3694
3695 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3696 if (patchDesc == 0) {
3697 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3698 sourceDesc->mPatchDesc->mHandle);
3699 return BAD_VALUE;
3700 }
3701 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3702
Eric Laurent28d09f02016-03-08 10:43:05 -08003703 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003704 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3705 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003706 status_t status = stopSource(swOutputDesc, stream, false);
3707 if (status == NO_ERROR) {
3708 swOutputDesc->stop();
3709 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003710 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3711 } else {
3712 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3713 if (hwOutputDesc != 0) {
3714 // release patch between src device and output device
3715 // close Hwoutput and remove from mHwOutputs
3716 } else {
3717 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3718 }
3719 }
3720 return NO_ERROR;
3721}
3722
3723sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3724 audio_io_handle_t output, routing_strategy strategy)
3725{
3726 sp<AudioSourceDescriptor> source;
3727 for (size_t i = 0; i < mAudioSources.size(); i++) {
3728 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3729 routing_strategy sourceStrategy =
3730 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3731 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3732 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3733 source = sourceDesc;
3734 break;
3735 }
3736 }
3737 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003738}
3739
Eric Laurente552edb2014-03-10 17:42:56 -07003740// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003741// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003742// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003743uint32_t AudioPolicyManager::nextAudioPortGeneration()
3744{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003745 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003746}
3747
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003748#ifdef USE_XML_AUDIO_POLICY_CONF
3749// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3750static const char *kConfigLocationList[] =
3751 {"/odm/etc", "/vendor/etc", "/system/etc"};
3752static const int kConfigLocationListSize =
3753 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3754
3755static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3756 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003757 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003758 status_t ret;
3759
Petri Gyntherf497f292018-04-17 18:46:10 -07003760 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3761 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3762 // A2DP offload supported but disabled: try to use special XML file
3763 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3764 }
3765 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3766
3767 for (const char* fileName : fileNames) {
3768 for (int i = 0; i < kConfigLocationListSize; i++) {
3769 PolicySerializer serializer;
3770 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3771 "%s/%s", kConfigLocationList[i], fileName);
3772 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3773 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003774 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003775 return ret;
3776 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003777 }
3778 }
3779 return ret;
3780}
3781#endif
3782
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003783AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3784 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003785 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003786 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003787 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003788 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003789 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003790#ifdef USE_XML_AUDIO_POLICY_CONF
3791 mVolumeCurves(new VolumeCurvesCollection()),
3792 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003793 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003794#else
3795 mVolumeCurves(new StreamDescriptorCollection()),
3796 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3797 mDefaultOutputDevice),
3798#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003799 mAudioPortGeneration(1),
3800 mBeaconMuteRefCount(0),
3801 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003802 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003803 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003804 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003805 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3806 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003807{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003808}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003809
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003810AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3811 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3812{
3813 loadConfig();
3814 initialize();
3815}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003816
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003817void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003818#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003819 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003820#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003821 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3822 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003823#endif
3824 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003825 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003826 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003827}
3828
3829status_t AudioPolicyManager::initialize() {
3830 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003831
3832 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003833 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3834 if (!engineInstance) {
3835 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003836 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003837 }
3838 // Retrieve the Policy Manager Interface
3839 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3840 if (mEngine == NULL) {
3841 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003842 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003843 }
3844 mEngine->setObserver(this);
3845 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003846 if (status != NO_ERROR) {
3847 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3848 return status;
3849 }
François Gaffie2110e042015-03-24 08:41:51 +01003850
Eric Laurent3a4311c2014-03-17 12:00:47 -07003851 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003852 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003853 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3854 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003855 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003856 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003857 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3858 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003859 continue;
3860 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003861 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003862 // open all output streams needed to access attached devices
3863 // except for direct output streams that are only opened when they are actually
3864 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003865 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003866 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003867 if (!outProfile->canOpenNewIo()) {
3868 ALOGE("Invalid Output profile max open count %u for profile %s",
3869 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3870 continue;
3871 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003872 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003873 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003874 continue;
3875 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003876 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003877 mTtsOutputAvailable = true;
3878 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003879
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003880 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003881 continue;
3882 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003883 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003884 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3885 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003886 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003887 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003888 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003889 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003890 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003891 if ((profileType & outputDeviceTypes) == 0) {
3892 continue;
3893 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003894 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3895 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003896 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003897 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3898 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003899 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3900 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003901 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003902 status_t status = outputDesc->open(nullptr, profileType, address,
3903 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003904
3905 if (status != NO_ERROR) {
3906 ALOGW("Cannot open output stream for device %08x on hw module %s",
3907 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003908 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003909 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003910 for (const auto& dev : supportedDevices) {
3911 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003912 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003913 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003914 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003915 }
3916 }
3917 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003918 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003919 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003920 }
3921 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003922 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003923 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003924 true,
3925 0,
3926 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003927 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003928 }
Eric Laurente552edb2014-03-10 17:42:56 -07003929 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003930 // open input streams needed to access attached devices to validate
3931 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003932 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003933 if (!inProfile->canOpenNewIo()) {
3934 ALOGE("Invalid Input profile max open count %u for profile %s",
3935 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3936 continue;
3937 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003938 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003939 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003940 continue;
3941 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003942 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003943 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003944 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3945
Eric Laurentd78f1532014-09-16 16:38:20 -07003946 if ((profileType & inputDeviceTypes) == 0) {
3947 continue;
3948 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003949 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003950 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003951
Mikhail Naganov708e0382018-05-30 09:53:04 -07003952 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003953 // the inputs vector must be of size >= 1, but we don't want to crash here
3954 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3955 : String8("");
3956 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3957 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3958
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003960 status_t status = inputDesc->open(nullptr,
3961 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003962 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003963 AUDIO_SOURCE_MIC,
3964 AUDIO_INPUT_FLAG_NONE,
3965 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003966
3967 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003968 for (const auto& dev : inProfile->getSupportedDevices()) {
3969 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003970 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003971 if (index >= 0) {
3972 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3973 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003974 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003975 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003976 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003977 }
3978 }
Eric Laurentfe231122017-11-17 17:48:06 -08003979 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 } else {
3981 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003982 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003983 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003984 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003985 }
3986 }
3987 // make sure all attached devices have been allocated a unique ID
3988 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003989 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003991 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3992 continue;
3993 }
François Gaffie2110e042015-03-24 08:41:51 +01003994 // The device is now validated and can be appended to the available devices of the engine
3995 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3996 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003997 i++;
3998 }
3999 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004000 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004001 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004002 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4003 continue;
4004 }
François Gaffie2110e042015-03-24 08:41:51 +01004005 // The device is now validated and can be appended to the available devices of the engine
4006 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4007 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004008 i++;
4009 }
4010 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004011 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004012 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004013 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004014 }
jiabin9ff780e2018-03-19 18:19:52 -07004015 // If microphones address is empty, set it according to device type
4016 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4017 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4018 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4019 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4020 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4021 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4022 }
4023 }
4024 }
Eric Laurente552edb2014-03-10 17:42:56 -07004025
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004026 if (mPrimaryOutput == 0) {
4027 ALOGE("Failed to open primary output");
4028 status = NO_INIT;
4029 }
Eric Laurente552edb2014-03-10 17:42:56 -07004030
4031 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004032 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004033}
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
Eric Laurente552edb2014-03-10 17:42:56 -07004037 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004038 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004039 }
4040 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004041 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004042 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004043 mAvailableOutputDevices.clear();
4044 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004045 mOutputs.clear();
4046 mInputs.clear();
4047 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004048 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004049 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004050}
4051
Eric Laurente0720872014-03-11 09:30:41 -07004052status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004053{
Eric Laurent87ffa392015-05-22 10:32:38 -07004054 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004055}
4056
Eric Laurente552edb2014-03-10 17:42:56 -07004057// ---
4058
Eric Laurent98e38192018-02-15 18:31:53 -08004059void AudioPolicyManager::addOutput(audio_io_handle_t output,
4060 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004061{
Eric Laurent1c333e22014-05-20 10:48:17 -07004062 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004063 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004064 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004065 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004066 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004067}
4068
François Gaffie53615e22015-03-19 09:24:12 +01004069void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4070{
4071 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004072 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004073}
4074
Eric Laurent98e38192018-02-15 18:31:53 -08004075void AudioPolicyManager::addInput(audio_io_handle_t input,
4076 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004077{
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004079 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004080}
Eric Laurente552edb2014-03-10 17:42:56 -07004081
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004082void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004083 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004084 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004085 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004086 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004087 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004088 if (devDesc != 0) {
4089 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4090 desc->mIoHandle, address.string());
4091 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004092 }
4093}
4094
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004095status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004096 audio_policy_dev_state_t state,
4097 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004098 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004099{
François Gaffie53615e22015-03-19 09:24:12 +01004100 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004101 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004102
4103 if (audio_device_is_digital(device)) {
4104 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004105 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004106 }
Eric Laurente552edb2014-03-10 17:42:56 -07004107
Eric Laurent3b73df72014-03-11 09:06:29 -07004108 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004109 // first list already open outputs that can be routed to this device
4110 for (size_t i = 0; i < mOutputs.size(); i++) {
4111 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004112 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004113 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004114 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4115 outputs.add(mOutputs.keyAt(i));
4116 } else {
4117 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004118 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004119 }
Eric Laurente552edb2014-03-10 17:42:56 -07004120 }
4121 }
4122 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004123 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004124 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004125 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4126 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004127 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004128 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004129 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004130 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004131 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4132 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004133 }
Eric Laurente552edb2014-03-10 17:42:56 -07004134 }
4135 }
4136 }
4137
Eric Laurent7b279bb2015-12-14 10:18:23 -08004138 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004139
Eric Laurente552edb2014-03-10 17:42:56 -07004140 if (profiles.isEmpty() && outputs.isEmpty()) {
4141 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4142 return BAD_VALUE;
4143 }
4144
4145 // open outputs for matching profiles if needed. Direct outputs are also opened to
4146 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4147 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004148 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004149
4150 // nothing to do if one output is already opened for this profile
4151 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004152 for (j = 0; j < outputs.size(); j++) {
4153 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004154 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004155 // matching profile: save the sample rates, format and channel masks supported
4156 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004157 if (audio_device_is_digital(device)) {
4158 devDesc->importAudioPort(profile);
4159 }
Eric Laurente552edb2014-03-10 17:42:56 -07004160 break;
4161 }
4162 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004164 continue;
4165 }
4166
Eric Laurent3974e3b2017-12-07 17:58:43 -08004167 if (!profile->canOpenNewIo()) {
4168 ALOGW("Max Output number %u already opened for this profile %s",
4169 profile->maxOpenCount, profile->getTagName().c_str());
4170 continue;
4171 }
4172
Eric Laurent83efe1c2017-07-09 16:51:08 -07004173 ALOGV("opening output for device %08x with params %s profile %p name %s",
4174 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004175 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004176 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004177 status_t status = desc->open(nullptr, device, address,
4178 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004179
Eric Laurentfe231122017-11-17 17:48:06 -08004180 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004181 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004182 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004183 char *param = audio_device_address_to_parameter(device, address);
4184 mpClientInterface->setParameters(output, String8(param));
4185 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004186 }
Phil Burk00eeb322016-03-31 12:41:00 -07004187 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004188 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004189 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004190 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004191 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004192 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004193 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004194 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004195 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4196 profile->pickAudioProfile(
4197 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004198 config.offload_info.sample_rate = config.sample_rate;
4199 config.offload_info.channel_mask = config.channel_mask;
4200 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004201
4202 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4203 AUDIO_OUTPUT_FLAG_NONE, &output);
4204 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004205 output = AUDIO_IO_HANDLE_NONE;
4206 }
Eric Laurentd4692962014-05-05 18:13:44 -07004207 }
4208
Eric Laurentcf2c0212014-07-25 16:20:43 -07004209 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004210 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004211 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004212 sp<AudioPolicyMix> policyMix;
4213 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004214 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4215 address.string());
4216 }
François Gaffie036e1e92015-03-19 10:16:24 +01004217 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004218 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004219
Eric Laurent87ffa392015-05-22 10:32:38 -07004220 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4221 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004222 // no duplicated output for direct outputs and
4223 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004224 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004225
Eric Laurentd4692962014-05-05 18:13:44 -07004226 //TODO: configure audio effect output stage here
4227
4228 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004229 sp<SwAudioOutputDescriptor> dupOutputDesc =
4230 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4231 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4232 &duplicatedOutput);
4233 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004234 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004235 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004236 } else {
4237 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004238 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004239 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004240 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004241 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004242 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004243 }
Eric Laurente552edb2014-03-10 17:42:56 -07004244 }
4245 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004246 } else {
4247 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004248 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004249 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004250 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004251 profiles.removeAt(profile_index);
4252 profile_index--;
4253 } else {
4254 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004255 // Load digital format info only for digital devices
4256 if (audio_device_is_digital(device)) {
4257 devDesc->importAudioPort(profile);
4258 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004259
François Gaffie53615e22015-03-19 09:24:12 +01004260 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004261 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4262 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004263 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004264 NULL/*patch handle*/, address.string());
4265 }
Eric Laurente552edb2014-03-10 17:42:56 -07004266 ALOGV("checkOutputsForDevice(): adding output %d", output);
4267 }
4268 }
4269
4270 if (profiles.isEmpty()) {
4271 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4272 return BAD_VALUE;
4273 }
Eric Laurentd4692962014-05-05 18:13:44 -07004274 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004275 // check if one opened output is not needed any more after disconnecting one device
4276 for (size_t i = 0; i < mOutputs.size(); i++) {
4277 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004278 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004279 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004280 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004281 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004282 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004283 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004284 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4285 mOutputs.keyAt(i));
4286 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004287 }
Eric Laurente552edb2014-03-10 17:42:56 -07004288 }
4289 }
Eric Laurentd4692962014-05-05 18:13:44 -07004290 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004291 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004292 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4293 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004294 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004295 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004296 "clearing direct output profile %zu on module %s",
4297 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004298 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004299 }
4300 }
4301 }
4302 }
4303 return NO_ERROR;
4304}
4305
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004306status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004307 audio_policy_dev_state_t state,
4308 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004309 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004310{
Paul McLean9080a4c2015-06-18 08:24:02 -07004311 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004312 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004313
4314 if (audio_device_is_digital(device)) {
4315 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004316 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004317 }
4318
Eric Laurentd4692962014-05-05 18:13:44 -07004319 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4320 // first list already open inputs that can be routed to this device
4321 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4322 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004323 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004324 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4325 inputs.add(mInputs.keyAt(input_index));
4326 }
4327 }
4328
4329 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004330 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004331 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004332 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004333 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004334 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004335 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004336
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004337 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004338 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004339 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004340 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004341 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4342 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004343 }
Eric Laurentd4692962014-05-05 18:13:44 -07004344 }
4345 }
4346 }
4347
4348 if (profiles.isEmpty() && inputs.isEmpty()) {
4349 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4350 return BAD_VALUE;
4351 }
4352
4353 // open inputs for matching profiles if needed. Direct inputs are also opened to
4354 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4355 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4356
Eric Laurent1c333e22014-05-20 10:48:17 -07004357 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004358
Eric Laurentd4692962014-05-05 18:13:44 -07004359 // nothing to do if one input is already opened for this profile
4360 size_t input_index;
4361 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4362 desc = mInputs.valueAt(input_index);
4363 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004364 if (audio_device_is_digital(device)) {
4365 devDesc->importAudioPort(profile);
4366 }
Eric Laurentd4692962014-05-05 18:13:44 -07004367 break;
4368 }
4369 }
4370 if (input_index != mInputs.size()) {
4371 continue;
4372 }
4373
Eric Laurent3974e3b2017-12-07 17:58:43 -08004374 if (!profile->canOpenNewIo()) {
4375 ALOGW("Max Input number %u already opened for this profile %s",
4376 profile->maxOpenCount, profile->getTagName().c_str());
4377 continue;
4378 }
4379
Eric Laurentfe231122017-11-17 17:48:06 -08004380 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004381 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004382 status_t status = desc->open(nullptr,
4383 device,
4384 address,
4385 AUDIO_SOURCE_MIC,
4386 AUDIO_INPUT_FLAG_NONE,
4387 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004388
Eric Laurentcf2c0212014-07-25 16:20:43 -07004389 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004390 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004391 char *param = audio_device_address_to_parameter(device, address);
4392 mpClientInterface->setParameters(input, String8(param));
4393 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004394 }
Phil Burk00eeb322016-03-31 12:41:00 -07004395 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004396 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004397 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004398 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004399 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004400 }
4401
4402 if (input != 0) {
4403 addInput(input, desc);
4404 }
4405 } // endif input != 0
4406
Eric Laurentcf2c0212014-07-25 16:20:43 -07004407 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004408 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004409 profiles.removeAt(profile_index);
4410 profile_index--;
4411 } else {
4412 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004413 if (audio_device_is_digital(device)) {
4414 devDesc->importAudioPort(profile);
4415 }
Eric Laurentd4692962014-05-05 18:13:44 -07004416 ALOGV("checkInputsForDevice(): adding input %d", input);
4417 }
4418 } // end scan profiles
4419
4420 if (profiles.isEmpty()) {
4421 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4422 return BAD_VALUE;
4423 }
4424 } else {
4425 // Disconnect
4426 // check if one opened input is not needed any more after disconnecting one device
4427 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4428 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004429 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004430 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4431 mInputs.keyAt(input_index));
4432 inputs.add(mInputs.keyAt(input_index));
4433 }
4434 }
4435 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004436 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004437 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004438 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004439 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004440 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004441 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004442 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4443 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004444 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004445 }
4446 }
4447 }
4448 } // end disconnect
4449
4450 return NO_ERROR;
4451}
4452
4453
Eric Laurente0720872014-03-11 09:30:41 -07004454void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004455{
4456 ALOGV("closeOutput(%d)", output);
4457
Eric Laurentc75307b2015-03-17 15:29:32 -07004458 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004459 if (outputDesc == NULL) {
4460 ALOGW("closeOutput() unknown output %d", output);
4461 return;
4462 }
François Gaffie036e1e92015-03-19 10:16:24 +01004463 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004464
Eric Laurente552edb2014-03-10 17:42:56 -07004465 // look for duplicated outputs connected to the output being removed.
4466 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004467 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004468 if (dupOutputDesc->isDuplicated() &&
4469 (dupOutputDesc->mOutput1 == outputDesc ||
4470 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004471 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004472 if (dupOutputDesc->mOutput1 == outputDesc) {
4473 outputDesc2 = dupOutputDesc->mOutput2;
4474 } else {
4475 outputDesc2 = dupOutputDesc->mOutput1;
4476 }
4477 // As all active tracks on duplicated output will be deleted,
4478 // and as they were also referenced on the other output, the reference
4479 // count for their stream type must be adjusted accordingly on
4480 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004481 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004482 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004483 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004484 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004485 }
Eric Laurent733ce942017-12-07 12:18:25 -08004486 // stop() will be a no op if the output is still active but is needed in case all
4487 // active streams refcounts where cleared above
4488 if (wasActive) {
4489 outputDesc2->stop();
4490 }
Eric Laurente552edb2014-03-10 17:42:56 -07004491 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4492 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4493
4494 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004495 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004496 }
4497 }
4498
Eric Laurent05b90f82014-08-27 15:32:29 -07004499 nextAudioPortGeneration();
4500
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004501 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004502 if (index >= 0) {
4503 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004504 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004505 mAudioPatches.removeItemsAt(index);
4506 mpClientInterface->onAudioPatchListUpdate();
4507 }
4508
Eric Laurentfe231122017-11-17 17:48:06 -08004509 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004510
François Gaffie53615e22015-03-19 09:24:12 +01004511 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004512 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004513}
4514
4515void AudioPolicyManager::closeInput(audio_io_handle_t input)
4516{
4517 ALOGV("closeInput(%d)", input);
4518
4519 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4520 if (inputDesc == NULL) {
4521 ALOGW("closeInput() unknown input %d", input);
4522 return;
4523 }
4524
Eric Laurent6a94d692014-05-20 11:18:06 -07004525 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004526
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004527 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004528 if (index >= 0) {
4529 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004530 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004531 mAudioPatches.removeItemsAt(index);
4532 mpClientInterface->onAudioPatchListUpdate();
4533 }
4534
Eric Laurentfe231122017-11-17 17:48:06 -08004535 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004536 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004537}
4538
Eric Laurentc75307b2015-03-17 15:29:32 -07004539SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4540 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004541 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004542{
4543 SortedVector<audio_io_handle_t> outputs;
4544
4545 ALOGVV("getOutputsForDevice() device %04x", device);
4546 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004547 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004548 i, openOutputs.valueAt(i)->isDuplicated(),
4549 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004550 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4551 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4552 outputs.add(openOutputs.keyAt(i));
4553 }
4554 }
4555 return outputs;
4556}
4557
Mikhail Naganov37977152018-07-11 15:54:44 -07004558void AudioPolicyManager::checkForDeviceAndOutputChanges()
4559{
4560 checkForDeviceAndOutputChanges([](){ return false; });
4561}
4562
4563void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4564{
4565 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4566 // output is suspended before any tracks are moved to it
4567 checkA2dpSuspend();
4568 checkOutputForAllStrategies();
4569 if (onOutputsChecked()) checkA2dpSuspend();
4570 updateDevicesAndOutputs();
4571}
4572
Eric Laurente0720872014-03-11 09:30:41 -07004573void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004574{
4575 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4576 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4577 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4578 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4579
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004580 // also take into account external policy-related changes: add all outputs which are
4581 // associated with policies in the "before" and "after" output vectors
4582 ALOGVV("checkOutputForStrategy(): policy related outputs");
4583 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004584 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004585 if (desc != 0 && desc->mPolicyMix != NULL) {
4586 srcOutputs.add(desc->mIoHandle);
4587 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4588 }
4589 }
4590 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004591 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004592 if (desc != 0 && desc->mPolicyMix != NULL) {
4593 dstOutputs.add(desc->mIoHandle);
4594 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4595 }
4596 }
4597
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004598 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004599 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4600 // audio from invalidated tracks will be rendered when unmuting
4601 uint32_t maxLatency = 0;
4602 for (audio_io_handle_t srcOut : srcOutputs) {
4603 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4604 if (desc != 0 && maxLatency < desc->latency()) {
4605 maxLatency = desc->latency();
4606 }
4607 }
Eric Laurente552edb2014-03-10 17:42:56 -07004608 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4609 strategy, srcOutputs[0], dstOutputs[0]);
4610 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004611 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004612 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4613 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004614 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004615 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004616 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004617 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004618 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004619 if (source != 0){
4620 connectAudioSource(source);
4621 }
Eric Laurente552edb2014-03-10 17:42:56 -07004622 }
4623
4624 // Move effects associated to this strategy from previous output to new output
4625 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004626 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004627 }
4628 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004629 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004630 if (getStrategy((audio_stream_type_t)i) == strategy) {
4631 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004632 }
4633 }
4634 }
4635}
4636
Eric Laurente0720872014-03-11 09:30:41 -07004637void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004638{
François Gaffie2110e042015-03-24 08:41:51 +01004639 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004640 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004641 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004642 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004643 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004644 checkOutputForStrategy(STRATEGY_SONIFICATION);
4645 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004646 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004647 checkOutputForStrategy(STRATEGY_MEDIA);
4648 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004649 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004650}
4651
Eric Laurente0720872014-03-11 09:30:41 -07004652void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004653{
François Gaffie53615e22015-03-19 09:24:12 +01004654 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004655 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004656 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004657 return;
4658 }
4659
Eric Laurent3a4311c2014-03-17 12:00:47 -07004660 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004661 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4662 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4663 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004664
4665 // if suspended, restore A2DP output if:
4666 // ((SCO device is NOT connected) ||
4667 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4668 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004669 //
Eric Laurentf732e072016-08-03 19:30:28 -07004670 // if not suspended, suspend A2DP output if:
4671 // (SCO device is connected) &&
4672 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4673 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004674 //
4675 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004676 if (!isScoConnected ||
4677 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4678 AUDIO_POLICY_FORCE_BT_SCO) &&
4679 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4680 AUDIO_POLICY_FORCE_BT_SCO) &&
4681 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004682 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004683
4684 mpClientInterface->restoreOutput(a2dpOutput);
4685 mA2dpSuspended = false;
4686 }
4687 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004688 if (isScoConnected &&
4689 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4690 AUDIO_POLICY_FORCE_BT_SCO) ||
4691 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4692 AUDIO_POLICY_FORCE_BT_SCO) ||
4693 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004694 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004695
4696 mpClientInterface->suspendOutput(a2dpOutput);
4697 mA2dpSuspended = true;
4698 }
4699 }
4700}
4701
Eric Laurentc75307b2015-03-17 15:29:32 -07004702audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4703 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004704{
4705 audio_devices_t device = AUDIO_DEVICE_NONE;
4706
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004707 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 if (index >= 0) {
4709 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4710 if (patchDesc->mUid != mUidCached) {
4711 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004712 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004713 return outputDesc->device();
4714 }
4715 }
4716
Eric Laurentf3a5a602018-05-22 18:42:55 -07004717 // Check if an explicit routing request exists for an active stream on this output and
4718 // use it in priority before any other rule
4719 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4720 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4721 audio_devices_t forcedDevice =
4722 mOutputRoutes.getActiveDeviceForStream(
4723 (audio_stream_type_t)stream, mAvailableOutputDevices);
4724
4725 if (forcedDevice != AUDIO_DEVICE_NONE) {
4726 return forcedDevice;
4727 }
4728 }
4729 }
4730
Eric Laurente552edb2014-03-10 17:42:56 -07004731 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004732 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004733 // use device for strategy enforced audible
4734 // 2: we are in call or the strategy phone is active on the output:
4735 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004736 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004737 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004738 // 4: the strategy for enforced audible is active but not enforced on the output:
4739 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004740 // 5: the strategy accessibility is active on the output:
4741 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004742 // 6: the strategy "respectful" sonification is active on the output:
4743 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004744 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004745 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004746 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004747 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004748 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004749 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004750
4751 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4752 // with a refined rule considering mutually exclusive devices (using same backend)
4753 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004754 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004755 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004756 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4757 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004758 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004759 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004760 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004761 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004762 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4763 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004764 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4765 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004766 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004767 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004768 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004769 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004770 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004771 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004772 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004773 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004774 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004775 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004776 }
4777
Eric Laurent1c333e22014-05-20 10:48:17 -07004778 ALOGV("getNewOutputDevice() selected device %x", device);
4779 return device;
4780}
4781
Eric Laurentfb66dd92016-01-28 18:32:03 -08004782audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004783{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004784 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004785
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004786 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 if (index >= 0) {
4788 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4789 if (patchDesc->mUid != mUidCached) {
4790 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004791 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 return inputDesc->mDevice;
4793 }
4794 }
4795
Eric Laurentdc95a252018-04-12 12:46:56 -07004796 // If we are not in call and no client is active on this input, this methods returns
4797 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004798 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004799 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4800 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4801 }
4802 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004803 device = getDeviceAndMixForInputSource(source);
4804 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004805
Eric Laurente552edb2014-03-10 17:42:56 -07004806 return device;
4807}
4808
Eric Laurent794fde22016-03-11 09:50:45 -08004809bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4810 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004811 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004812}
4813
Eric Laurente0720872014-03-11 09:30:41 -07004814uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004815 return (uint32_t)getStrategy(stream);
4816}
4817
Eric Laurente0720872014-03-11 09:30:41 -07004818audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004819 // By checking the range of stream before calling getStrategy, we avoid
4820 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4821 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004822 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 return AUDIO_DEVICE_NONE;
4824 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004826 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4827 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004828 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 }
Eric Laurent794fde22016-03-11 09:50:45 -08004830 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004831 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004832 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004833 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4834 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004835 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004836 curDevices |= outputDesc->device();
4837 }
4838 }
4839 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004840 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004841
4842 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4843 and doesn't really need to.*/
4844 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4845 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4846 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4847 }
Eric Laurente552edb2014-03-10 17:42:56 -07004848 return devices;
4849}
4850
François Gaffie2110e042015-03-24 08:41:51 +01004851routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4852{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004853 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004854 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004855}
4856
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004857uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4858 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004859 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4860 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4861 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004862 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4863 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4864 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004865 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004866 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004867}
4868
Eric Laurente0720872014-03-11 09:30:41 -07004869void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004870 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004871 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004872 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4873 updateDevicesAndOutputs();
4874 break;
4875 default:
4876 break;
4877 }
4878}
4879
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004880uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004881
4882 // skip beacon mute management if a dedicated TTS output is available
4883 if (mTtsOutputAvailable) {
4884 return 0;
4885 }
4886
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004887 switch(event) {
4888 case STARTING_OUTPUT:
4889 mBeaconMuteRefCount++;
4890 break;
4891 case STOPPING_OUTPUT:
4892 if (mBeaconMuteRefCount > 0) {
4893 mBeaconMuteRefCount--;
4894 }
4895 break;
4896 case STARTING_BEACON:
4897 mBeaconPlayingRefCount++;
4898 break;
4899 case STOPPING_BEACON:
4900 if (mBeaconPlayingRefCount > 0) {
4901 mBeaconPlayingRefCount--;
4902 }
4903 break;
4904 }
4905
4906 if (mBeaconMuteRefCount > 0) {
4907 // any playback causes beacon to be muted
4908 return setBeaconMute(true);
4909 } else {
4910 // no other playback: unmute when beacon starts playing, mute when it stops
4911 return setBeaconMute(mBeaconPlayingRefCount == 0);
4912 }
4913}
4914
4915uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4916 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4917 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4918 // keep track of muted state to avoid repeating mute/unmute operations
4919 if (mBeaconMuted != mute) {
4920 // mute/unmute AUDIO_STREAM_TTS on all outputs
4921 ALOGV("\t muting %d", mute);
4922 uint32_t maxLatency = 0;
4923 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004924 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004925 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004926 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004927 0 /*delay*/, AUDIO_DEVICE_NONE);
4928 const uint32_t latency = desc->latency() * 2;
4929 if (latency > maxLatency) {
4930 maxLatency = latency;
4931 }
4932 }
4933 mBeaconMuted = mute;
4934 return maxLatency;
4935 }
4936 return 0;
4937}
4938
Eric Laurente0720872014-03-11 09:30:41 -07004939audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004940 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004941{
Eric Laurentf3a5a602018-05-22 18:42:55 -07004942 // Check if an explicit routing request exists for a stream type corresponding to the
4943 // specified strategy and use it in priority over default routing rules.
4944 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4945 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4946 audio_devices_t forcedDevice =
4947 mOutputRoutes.getActiveDeviceForStream(
4948 (audio_stream_type_t)stream, mAvailableOutputDevices);
4949 if (forcedDevice != AUDIO_DEVICE_NONE) {
4950 return forcedDevice;
4951 }
Paul McLeanaa981192015-03-21 09:55:15 -07004952 }
4953 }
4954
Eric Laurente552edb2014-03-10 17:42:56 -07004955 if (fromCache) {
4956 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4957 strategy, mDeviceForStrategy[strategy]);
4958 return mDeviceForStrategy[strategy];
4959 }
François Gaffie2110e042015-03-24 08:41:51 +01004960 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004961}
4962
Eric Laurente0720872014-03-11 09:30:41 -07004963void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004964{
4965 for (int i = 0; i < NUM_STRATEGIES; i++) {
4966 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4967 }
4968 mPreviousOutputs = mOutputs;
4969}
4970
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004971uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004972 audio_devices_t prevDevice,
4973 uint32_t delayMs)
4974{
4975 // mute/unmute strategies using an incompatible device combination
4976 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4977 // if unmuting, unmute only after the specified delay
4978 if (outputDesc->isDuplicated()) {
4979 return 0;
4980 }
4981
4982 uint32_t muteWaitMs = 0;
4983 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004985
4986 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4987 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004989 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4990 bool doMute = false;
4991
4992 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4993 doMute = true;
4994 outputDesc->mStrategyMutedByDevice[i] = true;
4995 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4996 doMute = true;
4997 outputDesc->mStrategyMutedByDevice[i] = false;
4998 }
Eric Laurent99401132014-05-07 19:48:15 -07004999 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005000 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005001 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005002 // skip output if it does not share any device with current output
5003 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5004 == AUDIO_DEVICE_NONE) {
5005 continue;
5006 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005007 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005008 mute ? "muting" : "unmuting", i, curDevice);
5009 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005010 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005011 if (mute) {
5012 // FIXME: should not need to double latency if volume could be applied
5013 // immediately by the audioflinger mixer. We must account for the delay
5014 // between now and the next time the audioflinger thread for this output
5015 // will process a buffer (which corresponds to one buffer size,
5016 // usually 1/2 or 1/4 of the latency).
5017 if (muteWaitMs < desc->latency() * 2) {
5018 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005019 }
5020 }
5021 }
5022 }
5023 }
5024 }
5025
Eric Laurent99401132014-05-07 19:48:15 -07005026 // temporary mute output if device selection changes to avoid volume bursts due to
5027 // different per device volumes
5028 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005029 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5030 // temporary mute duration is conservatively set to 4 times the reported latency
5031 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5032 if (muteWaitMs < tempMuteWaitMs) {
5033 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005034 }
Eric Laurentdc462862016-07-19 12:29:53 -07005035
Eric Laurent99401132014-05-07 19:48:15 -07005036 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005037 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005038 // make sure that we do not start the temporary mute period too early in case of
5039 // delayed device change
5040 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005041 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005042 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005043 }
5044 }
5045 }
5046
Eric Laurente552edb2014-03-10 17:42:56 -07005047 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5048 if (muteWaitMs > delayMs) {
5049 muteWaitMs -= delayMs;
5050 usleep(muteWaitMs * 1000);
5051 return muteWaitMs;
5052 }
5053 return 0;
5054}
5055
Eric Laurentc75307b2015-03-17 15:29:32 -07005056uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005057 audio_devices_t device,
5058 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005060 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005061 const char *address,
5062 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005063{
Eric Laurentc75307b2015-03-17 15:29:32 -07005064 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005065 AudioParameter param;
5066 uint32_t muteWaitMs;
5067
5068 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005069 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5070 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5071 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5072 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005073 return muteWaitMs;
5074 }
5075 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5076 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005077 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005078 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005079 return 0;
5080 }
5081
5082 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005083 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005084
5085 audio_devices_t prevDevice = outputDesc->mDevice;
5086
Paul McLeanaa981192015-03-21 09:55:15 -07005087 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005088
5089 if (device != AUDIO_DEVICE_NONE) {
5090 outputDesc->mDevice = device;
5091 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005092
5093 // if the outputs are not materially active, there is no need to mute.
5094 if (requiresMuteCheck) {
5095 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5096 } else {
5097 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5098 muteWaitMs = 0;
5099 }
Eric Laurente552edb2014-03-10 17:42:56 -07005100
5101 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005102 // the requested device is AUDIO_DEVICE_NONE
5103 // OR the requested device is the same as current device
5104 // AND force is not specified
5105 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005106 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005107 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5108 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005109 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005110 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005111 return muteWaitMs;
5112 }
5113
5114 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005115
Eric Laurente552edb2014-03-10 17:42:56 -07005116 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005117 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005118 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005120 DeviceVector deviceList;
5121 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005122 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005123 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005124 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5125 device, String8(address));
5126 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005127 }
5128
Eric Laurent1c333e22014-05-20 10:48:17 -07005129 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005130 PatchBuilder patchBuilder;
5131 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005132 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005133 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005134 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005135 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005136 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005137
5138 // inform all input as well
5139 for (size_t i = 0; i < mInputs.size(); i++) {
5140 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005141 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005142 AudioParameter inputCmd = AudioParameter();
5143 ALOGV("%s: inform input %d of device:%d", __func__,
5144 inputDescriptor->mIoHandle, device);
5145 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5146 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5147 inputCmd.toString(),
5148 delayMs);
5149 }
5150 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005151 }
Eric Laurente552edb2014-03-10 17:42:56 -07005152
5153 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005154 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005155
5156 return muteWaitMs;
5157}
5158
Eric Laurentc75307b2015-03-17 15:29:32 -07005159status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 int delayMs,
5161 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005162{
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 ssize_t index;
5164 if (patchHandle) {
5165 index = mAudioPatches.indexOfKey(*patchHandle);
5166 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005167 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 }
5169 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005170 return INVALID_OPERATION;
5171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005172 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5173 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005174 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005175 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 removeAudioPatch(patchDesc->mHandle);
5177 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005178 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005179 return status;
5180}
5181
5182status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5183 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 bool force,
5185 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005186{
5187 status_t status = NO_ERROR;
5188
Eric Laurent1f2f2232014-06-02 12:01:23 -07005189 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005190 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5191 inputDesc->mDevice = device;
5192
Mikhail Naganov708e0382018-05-30 09:53:04 -07005193 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005194 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005195 PatchBuilder patchBuilder;
5196 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005197 // AUDIO_SOURCE_HOTWORD is for internal use only:
5198 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005199 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5200 auto result = usecase;
5201 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5202 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5203 }
5204 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005205 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005206 addSource(deviceList.itemAt(0));
5207 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005208 }
5209 }
5210 return status;
5211}
5212
Eric Laurent6a94d692014-05-20 11:18:06 -07005213status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5214 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005215{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005216 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 ssize_t index;
5218 if (patchHandle) {
5219 index = mAudioPatches.indexOfKey(*patchHandle);
5220 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005221 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 }
5223 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005224 return INVALID_OPERATION;
5225 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5227 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005229 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 removeAudioPatch(patchDesc->mHandle);
5231 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005232 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005233 return status;
5234}
5235
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005236sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005237 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005238 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005239 audio_format_t& format,
5240 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005241 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005242{
5243 // Choose an input profile based on the requested capture parameters: select the first available
5244 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005245 //
5246 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5247 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005248
Glenn Kasten730b9262018-03-29 15:01:26 -07005249 sp<IOProfile> firstInexact;
5250 uint32_t updatedSamplingRate = 0;
5251 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5252 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005253 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005254 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005255 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005256 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005257 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005258 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005259 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005260 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005261 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005262 &channelMask /*updatedChannelMask*/,
5263 // FIXME ugly cast
5264 (audio_output_flags_t) flags,
5265 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005266 return profile;
5267 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005268 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5269 samplingRate,
5270 &updatedSamplingRate,
5271 format,
5272 &updatedFormat,
5273 channelMask,
5274 &updatedChannelMask,
5275 // FIXME ugly cast
5276 (audio_output_flags_t) flags,
5277 false /*exactMatchRequiredForInputFlags*/)) {
5278 firstInexact = profile;
5279 }
5280
Eric Laurente552edb2014-03-10 17:42:56 -07005281 }
5282 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005283 if (firstInexact != nullptr) {
5284 samplingRate = updatedSamplingRate;
5285 format = updatedFormat;
5286 channelMask = updatedChannelMask;
5287 return firstInexact;
5288 }
Eric Laurente552edb2014-03-10 17:42:56 -07005289 return NULL;
5290}
5291
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005292
5293audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005294 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005295{
François Gaffie036e1e92015-03-19 10:16:24 +01005296 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5297 audio_devices_t selectedDeviceFromMix =
5298 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005299
François Gaffie036e1e92015-03-19 10:16:24 +01005300 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5301 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005302 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005303 return getDeviceForInputSource(inputSource);
5304}
5305
5306audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5307{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005308 // Routing
5309 // Scan the whole RouteMap to see if we have an explicit route:
5310 // if the input source in the RouteMap is the same as the argument above,
5311 // and activity count is non-zero and the device in the route descriptor is available
5312 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005313 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5314 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005315 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005316 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005317 return route->mDeviceDescriptor->type();
5318 }
5319 }
5320
5321 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005322}
5323
Eric Laurente0720872014-03-11 09:30:41 -07005324float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005325 int index,
5326 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005328 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005329
5330 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5331 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5332 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5333 // the ringtone volume
5334 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5335 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5336 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5337 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5338 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5339 }
5340
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005341 // in-call: always cap volume by voice volume + some low headroom
5342 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005343 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005344 switch (stream) {
5345 case AUDIO_STREAM_SYSTEM:
5346 case AUDIO_STREAM_RING:
5347 case AUDIO_STREAM_MUSIC:
5348 case AUDIO_STREAM_ALARM:
5349 case AUDIO_STREAM_NOTIFICATION:
5350 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5351 case AUDIO_STREAM_DTMF:
5352 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005353 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005354 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005355 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005356 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005357 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005358 if (volumeDB > maxVoiceVolDb) {
5359 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5360 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5361 volumeDB = maxVoiceVolDb;
5362 }
5363 } break;
5364 default:
5365 break;
5366 }
5367 }
5368
Eric Laurente552edb2014-03-10 17:42:56 -07005369 // if a headset is connected, apply the following rules to ring tones and notifications
5370 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005371 // - always attenuate notifications volume by 6dB
5372 // - attenuate ring tones volume by 6dB unless music is not playing and
5373 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005374 // - if music is playing, always limit the volume to current music volume,
5375 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005376 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005377 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5378 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5379 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005380 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005381 AUDIO_DEVICE_OUT_USB_HEADSET |
5382 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005383 ((stream_strategy == STRATEGY_SONIFICATION)
5384 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005385 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005386 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005387 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005388 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005389 // when the phone is ringing we must consider that music could have been paused just before
5390 // by the music application and behave as if music was active if the last music track was
5391 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005392 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005393 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005394 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005395 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005396 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005397 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5398 musicDevice),
5399 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005400 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5401 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005402 if (volumeDB > minVolDB) {
5403 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005404 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005405 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005406 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5407 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5408 // on A2DP, also ensure notification volume is not too low compared to media when
5409 // intended to be played
5410 if ((volumeDB > -96.0f) &&
5411 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5412 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5413 stream, device,
5414 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5415 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5416 }
5417 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005418 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5419 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005420 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005421 }
5422 }
5423
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005424 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005425}
5426
Eric Laurent3839bc02018-07-10 18:33:34 -07005427int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5428 audio_stream_type_t srcStream,
5429 audio_stream_type_t dstStream)
5430{
5431 if (srcStream == dstStream) {
5432 return srcIndex;
5433 }
5434 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5435 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5436 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5437 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5438
5439 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5440}
5441
Eric Laurente0720872014-03-11 09:30:41 -07005442status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005443 int index,
5444 const sp<AudioOutputDescriptor>& outputDesc,
5445 audio_devices_t device,
5446 int delayMs,
5447 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005448{
Eric Laurente552edb2014-03-10 17:42:56 -07005449 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005450 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005451 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005452 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005453 return NO_ERROR;
5454 }
François Gaffie2110e042015-03-24 08:41:51 +01005455 audio_policy_forced_cfg_t forceUseForComm =
5456 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005457 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005458 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5459 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005461 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005462 return INVALID_OPERATION;
5463 }
5464
Eric Laurentc75307b2015-03-17 15:29:32 -07005465 if (device == AUDIO_DEVICE_NONE) {
5466 device = outputDesc->device();
5467 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005468
Eric Laurentffbc80f2015-03-18 18:30:19 -07005469 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005470 if (outputDesc->isFixedVolume(device) ||
5471 // Force VoIP volume to max for bluetooth SCO
5472 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5473 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005474 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005475 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005476
Eric Laurentffbc80f2015-03-18 18:30:19 -07005477 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005478
Eric Laurent3b73df72014-03-11 09:06:29 -07005479 if (stream == AUDIO_STREAM_VOICE_CALL ||
5480 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005481 float voiceVolume;
5482 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005483 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005484 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005485 } else {
5486 voiceVolume = 1.0;
5487 }
5488
Eric Laurent18fba842016-03-31 14:41:26 -07005489 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005490 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5491 mLastVoiceVolume = voiceVolume;
5492 }
5493 }
5494
5495 return NO_ERROR;
5496}
5497
Eric Laurentc75307b2015-03-17 15:29:32 -07005498void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5499 audio_devices_t device,
5500 int delayMs,
5501 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005502{
Eric Laurentc75307b2015-03-17 15:29:32 -07005503 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005504
Eric Laurent794fde22016-03-11 09:50:45 -08005505 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005506 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005507 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005508 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005509 device,
5510 delayMs,
5511 force);
5512 }
5513}
5514
Eric Laurente0720872014-03-11 09:30:41 -07005515void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005516 bool on,
5517 const sp<AudioOutputDescriptor>& outputDesc,
5518 int delayMs,
5519 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005520{
Eric Laurent72249d52015-06-08 11:12:15 -07005521 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5522 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005523 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005524 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005525 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005526 }
5527 }
5528}
5529
Eric Laurente0720872014-03-11 09:30:41 -07005530void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005531 bool on,
5532 const sp<AudioOutputDescriptor>& outputDesc,
5533 int delayMs,
5534 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
Eric Laurente552edb2014-03-10 17:42:56 -07005536 if (device == AUDIO_DEVICE_NONE) {
5537 device = outputDesc->device();
5538 }
5539
Eric Laurentc75307b2015-03-17 15:29:32 -07005540 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5541 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005542
5543 if (on) {
5544 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005545 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005546 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005547 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005548 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005549 }
5550 }
5551 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5552 outputDesc->mMuteCount[stream]++;
5553 } else {
5554 if (outputDesc->mMuteCount[stream] == 0) {
5555 ALOGV("setStreamMute() unmuting non muted stream!");
5556 return;
5557 }
5558 if (--outputDesc->mMuteCount[stream] == 0) {
5559 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005560 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005561 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005562 device,
5563 delayMs);
5564 }
5565 }
5566}
5567
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005568audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5569{
5570 // flags to stream type mapping
5571 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5572 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5573 }
5574 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5575 return AUDIO_STREAM_BLUETOOTH_SCO;
5576 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005577 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5578 return AUDIO_STREAM_TTS;
5579 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005580
5581 // usage to stream type mapping
5582 switch (attr->usage) {
5583 case AUDIO_USAGE_MEDIA:
5584 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005585 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005586 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5587 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005588 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5589 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005590 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5591 return AUDIO_STREAM_SYSTEM;
5592 case AUDIO_USAGE_VOICE_COMMUNICATION:
5593 return AUDIO_STREAM_VOICE_CALL;
5594
5595 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5596 return AUDIO_STREAM_DTMF;
5597
5598 case AUDIO_USAGE_ALARM:
5599 return AUDIO_STREAM_ALARM;
5600 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5601 return AUDIO_STREAM_RING;
5602
5603 case AUDIO_USAGE_NOTIFICATION:
5604 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5605 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5606 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5607 case AUDIO_USAGE_NOTIFICATION_EVENT:
5608 return AUDIO_STREAM_NOTIFICATION;
5609
5610 case AUDIO_USAGE_UNKNOWN:
5611 default:
5612 return AUDIO_STREAM_MUSIC;
5613 }
5614}
Eric Laurente83b55d2014-11-14 10:06:21 -08005615
François Gaffie53615e22015-03-19 09:24:12 +01005616bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5617{
Eric Laurente83b55d2014-11-14 10:06:21 -08005618 // has flags that map to a strategy?
5619 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5620 return true;
5621 }
5622
5623 // has known usage?
5624 switch (paa->usage) {
5625 case AUDIO_USAGE_UNKNOWN:
5626 case AUDIO_USAGE_MEDIA:
5627 case AUDIO_USAGE_VOICE_COMMUNICATION:
5628 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5629 case AUDIO_USAGE_ALARM:
5630 case AUDIO_USAGE_NOTIFICATION:
5631 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5632 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5633 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5634 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5635 case AUDIO_USAGE_NOTIFICATION_EVENT:
5636 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5637 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5638 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5639 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005640 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005641 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005642 break;
5643 default:
5644 return false;
5645 }
5646 return true;
5647}
5648
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005649bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005650 routing_strategy strategy, uint32_t inPastMs,
5651 nsecs_t sysTime) const
5652{
5653 if ((sysTime == 0) && (inPastMs != 0)) {
5654 sysTime = systemTime();
5655 }
Eric Laurent794fde22016-03-11 09:50:45 -08005656 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005657 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5658 (NUM_STRATEGIES == strategy)) &&
5659 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5660 return true;
5661 }
5662 }
5663 return false;
5664}
5665
Eric Laurent484e9272018-06-07 17:29:23 -07005666bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5667 routing_strategy strategy, uint32_t inPastMs,
5668 nsecs_t sysTime) const
5669{
5670 for (size_t i = 0; i < mOutputs.size(); i++) {
5671 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5672 if (outputDesc->sharesHwModuleWith(desc)
5673 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5674 return true;
5675 }
5676 }
5677 return false;
5678}
5679
François Gaffie2110e042015-03-24 08:41:51 +01005680audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5681{
5682 return mEngine->getForceUse(usage);
5683}
5684
5685bool AudioPolicyManager::isInCall()
5686{
5687 return isStateInCall(mEngine->getPhoneState());
5688}
5689
5690bool AudioPolicyManager::isStateInCall(int state)
5691{
5692 return is_state_in_call(state);
5693}
5694
Eric Laurentd60560a2015-04-10 11:31:20 -07005695void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5696{
5697 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5698 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5699 if (sourceDesc->mDevice->equals(deviceDesc)) {
5700 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5701 stopAudioSource(sourceDesc->getHandle());
5702 }
5703 }
5704
5705 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5706 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5707 bool release = false;
5708 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5709 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5710 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5711 source->ext.device.type == deviceDesc->type()) {
5712 release = true;
5713 }
5714 }
5715 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5716 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5717 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5718 sink->ext.device.type == deviceDesc->type()) {
5719 release = true;
5720 }
5721 }
5722 if (release) {
5723 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5724 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5725 }
5726 }
5727}
5728
Phil Burk09bc4612016-02-24 15:58:15 -08005729// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005730void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5731 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005732 // TODO Set this based on Config properties.
5733 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005734
5735 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5736 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005737 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005738
jiabin81772902018-04-02 17:52:27 -07005739 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5740 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5741 formats.clear();
5742 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5743 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005744 }
jiabin81772902018-04-02 17:52:27 -07005745 // Always enable IEC61937 when in MANUAL mode.
5746 formats.add(AUDIO_FORMAT_IEC61937);
5747 } else { // NEVER, AUTO or ALWAYS
5748 // Analyze original support for various formats.
5749 bool supportsAC3 = false;
5750 bool supportsOtherSurround = false;
5751 bool supportsIEC61937 = false;
5752 mSurroundFormats.clear();
5753 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5754 audio_format_t format = formats[formatIndex];
5755 switch (format) {
5756 case AUDIO_FORMAT_AC3:
5757 supportsAC3 = true;
5758 break;
5759 case AUDIO_FORMAT_E_AC3:
5760 case AUDIO_FORMAT_DTS:
5761 case AUDIO_FORMAT_DTS_HD:
5762 // If ALWAYS, remove all other surround formats here
5763 // since we will add them later.
5764 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5765 formats.removeAt(formatIndex);
5766 formatIndex--;
5767 }
5768 supportsOtherSurround = true;
5769 break;
5770 case AUDIO_FORMAT_IEC61937:
5771 supportsIEC61937 = true;
5772 break;
5773 default:
5774 break;
5775 }
5776 }
Phil Burk09bc4612016-02-24 15:58:15 -08005777
jiabin81772902018-04-02 17:52:27 -07005778 // Modify formats based on surround preferences.
5779 // If NEVER, remove support for surround formats.
5780 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5781 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5782 // Remove surround sound related formats.
5783 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5784 audio_format_t format = formats[formatIndex];
5785 switch(format) {
5786 case AUDIO_FORMAT_AC3:
5787 case AUDIO_FORMAT_E_AC3:
5788 case AUDIO_FORMAT_DTS:
5789 case AUDIO_FORMAT_DTS_HD:
5790 case AUDIO_FORMAT_IEC61937:
5791 formats.removeAt(formatIndex);
5792 break;
5793 default:
5794 formatIndex++; // keep it
5795 break;
5796 }
5797 }
5798 supportsAC3 = false;
5799 supportsOtherSurround = false;
5800 supportsIEC61937 = false;
5801 }
5802 } else { // AUTO or ALWAYS
5803 // Most TVs support AC3 even if they do not report it in the EDID.
5804 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5805 && !supportsAC3) {
5806 formats.add(AUDIO_FORMAT_AC3);
5807 supportsAC3 = true;
5808 }
5809
5810 // If ALWAYS, add support for raw surround formats if all are missing.
5811 // This assumes that if any of these formats are reported by the HAL
5812 // then the report is valid and should not be modified.
5813 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5814 formats.add(AUDIO_FORMAT_E_AC3);
5815 formats.add(AUDIO_FORMAT_DTS);
5816 formats.add(AUDIO_FORMAT_DTS_HD);
5817 supportsOtherSurround = true;
5818 }
5819
5820 // Add support for IEC61937 if any raw surround supported.
5821 // The HAL could do this but add it here, just in case.
5822 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5823 formats.add(AUDIO_FORMAT_IEC61937);
5824 supportsIEC61937 = true;
5825 }
5826
5827 // Add reported surround sound formats to enabled surround formats.
5828 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005829 audio_format_t format = formats[formatIndex];
5830 switch(format) {
5831 case AUDIO_FORMAT_AC3:
5832 case AUDIO_FORMAT_E_AC3:
5833 case AUDIO_FORMAT_DTS:
5834 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005835 case AUDIO_FORMAT_AAC_LC:
5836 case AUDIO_FORMAT_DOLBY_TRUEHD:
5837 case AUDIO_FORMAT_E_AC3_JOC:
5838 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005839 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005840 break;
5841 }
Phil Burk09bc4612016-02-24 15:58:15 -08005842 }
Phil Burk07ac1142016-03-25 13:39:29 -07005843 }
Phil Burk09bc4612016-02-24 15:58:15 -08005844 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005845}
5846
5847// Modify the list of channel masks supported.
5848void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5849 ChannelsVector &channelMasks = *channelMasksPtr;
5850 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5851 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5852
5853 // If NEVER, then remove support for channelMasks > stereo.
5854 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5855 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5856 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5857 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5858 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5859 channelMasks.removeAt(maskIndex);
5860 } else {
5861 maskIndex++;
5862 }
5863 }
jiabin81772902018-04-02 17:52:27 -07005864 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5865 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5866 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005867 bool supports5dot1 = false;
5868 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005869 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005870 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5871 supports5dot1 = true;
5872 break;
5873 }
5874 }
5875 // If not then add 5.1 support.
5876 if (!supports5dot1) {
5877 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5878 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5879 }
Phil Burk09bc4612016-02-24 15:58:15 -08005880 }
5881}
5882
Phil Burk00eeb322016-03-31 12:41:00 -07005883void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5884 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005885 AudioProfileVector &profiles)
5886{
5887 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005888
François Gaffie112b0af2015-11-19 16:13:25 +01005889 // Format MUST be checked first to update the list of AudioProfile
5890 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005891 reply = mpClientInterface->getParameters(
5892 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005893 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005894 AudioParameter repliedParameters(reply);
5895 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005896 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005897 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5898 return;
5899 }
Phil Burk09bc4612016-02-24 15:58:15 -08005900 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005901 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005902 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005903 }
Phil Burk09bc4612016-02-24 15:58:15 -08005904 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005905 }
François Gaffie112b0af2015-11-19 16:13:25 +01005906
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005907 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005908 ChannelsVector channelMasks;
5909 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005910 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005911 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005912
5913 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005914 reply = mpClientInterface->getParameters(
5915 ioHandle,
5916 requestedParameters.toString() + ";" +
5917 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005918 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005919 AudioParameter repliedParameters(reply);
5920 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005921 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005922 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005923 }
5924 }
5925 if (profiles.hasDynamicChannelsFor(format)) {
5926 reply = mpClientInterface->getParameters(ioHandle,
5927 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005928 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005929 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005930 AudioParameter repliedParameters(reply);
5931 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005932 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005933 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005934 if (device == AUDIO_DEVICE_OUT_HDMI) {
5935 filterSurroundChannelMasks(&channelMasks);
5936 }
François Gaffie112b0af2015-11-19 16:13:25 +01005937 }
5938 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005939 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005940 }
5941}
Eric Laurentd60560a2015-04-10 11:31:20 -07005942
Mikhail Naganovdc769682018-05-04 15:34:08 -07005943status_t AudioPolicyManager::installPatch(const char *caller,
5944 audio_patch_handle_t *patchHandle,
5945 AudioIODescriptorInterface *ioDescriptor,
5946 const struct audio_patch *patch,
5947 int delayMs)
5948{
5949 ssize_t index = mAudioPatches.indexOfKey(
5950 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5951 *patchHandle : ioDescriptor->getPatchHandle());
5952 sp<AudioPatch> patchDesc;
5953 status_t status = installPatch(
5954 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5955 if (status == NO_ERROR) {
5956 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5957 }
5958 return status;
5959}
5960
5961status_t AudioPolicyManager::installPatch(const char *caller,
5962 ssize_t index,
5963 audio_patch_handle_t *patchHandle,
5964 const struct audio_patch *patch,
5965 int delayMs,
5966 uid_t uid,
5967 sp<AudioPatch> *patchDescPtr)
5968{
5969 sp<AudioPatch> patchDesc;
5970 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5971 if (index >= 0) {
5972 patchDesc = mAudioPatches.valueAt(index);
5973 afPatchHandle = patchDesc->mAfPatchHandle;
5974 }
5975
5976 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5977 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5978 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5979 if (status == NO_ERROR) {
5980 if (index < 0) {
5981 patchDesc = new AudioPatch(patch, uid);
5982 addAudioPatch(patchDesc->mHandle, patchDesc);
5983 } else {
5984 patchDesc->mPatch = *patch;
5985 }
5986 patchDesc->mAfPatchHandle = afPatchHandle;
5987 if (patchHandle) {
5988 *patchHandle = patchDesc->mHandle;
5989 }
5990 nextAudioPortGeneration();
5991 mpClientInterface->onAudioPatchListUpdate();
5992 }
5993 if (patchDescPtr) *patchDescPtr = patchDesc;
5994 return status;
5995}
5996
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005997} // namespace android