blob: efc9753387cb65d27bd44009e7fb514d1f551c49 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070029#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
30 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010031
Eric Laurentd4692962014-05-05 18:13:44 -070032#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070033#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070034
François Gaffie2110e042015-03-24 08:41:51 +010035#include <AudioPolicyManagerInterface.h>
36#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070039#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080040#include <media/AudioPolicyHelper.h>
Mikhail Naganovdc769682018-05-04 15:34:08 -070041#include <media/PatchBuilder.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070042#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070043#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070044#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070045#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010048#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010049#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010050#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010051#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010053#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurentdc462862016-07-19 12:29:53 -070057//FIXME: workaround for truncated touch sounds
58// to be removed when the problem is handled by system UI
59#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070060
61// Largest difference in dB on earpiece in call between the voice volume and another
62// media / notification / system volume.
63constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
64
jiabin81772902018-04-02 17:52:27 -070065#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
66// Array of all surround formats.
67static const audio_format_t SURROUND_FORMATS[] = {
68 AUDIO_FORMAT_AC3,
69 AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_DTS,
71 AUDIO_FORMAT_DTS_HD,
72 AUDIO_FORMAT_AAC_LC,
73 AUDIO_FORMAT_DOLBY_TRUEHD,
74 AUDIO_FORMAT_E_AC3_JOC,
75};
76// Array of all AAC formats. When AAC is enabled by users, all AAC formats should be enabled.
77static const audio_format_t AAC_FORMATS[] = {
78 AUDIO_FORMAT_AAC_LC,
79 AUDIO_FORMAT_AAC_HE_V1,
80 AUDIO_FORMAT_AAC_HE_V2,
81 AUDIO_FORMAT_AAC_ELD,
82 AUDIO_FORMAT_AAC_XHE,
83};
84
Eric Laurente552edb2014-03-10 17:42:56 -070085// ----------------------------------------------------------------------------
86// AudioPolicyInterface implementation
87// ----------------------------------------------------------------------------
88
Eric Laurente0720872014-03-11 09:30:41 -070089status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080090 audio_policy_dev_state_t state,
91 const char *device_address,
92 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070093{
jiabina7b43792018-02-15 16:04:46 -080094 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
95 nextAudioPortGeneration();
96 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080097}
98
François Gaffie44481e72016-04-20 07:49:57 +020099void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
100 audio_policy_dev_state_t state,
101 const String8 &device_address)
102{
103 AudioParameter param(device_address);
104 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -0700105 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +0200106 param.addInt(key, device);
107 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
108}
109
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800111 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800112 const char *device_address,
113 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114{
Paul McLeane743a472015-01-28 11:07:31 -0800115 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800116 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700117
118 // connect/disconnect only 1 device at a time
119 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
120
François Gaffie53615e22015-03-19 09:24:12 +0100121 sp<DeviceDescriptor> devDesc =
122 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800123
Eric Laurente552edb2014-03-10 17:42:56 -0700124 // handle output devices
125 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700126 SortedVector <audio_io_handle_t> outputs;
127
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
129
Eric Laurente552edb2014-03-10 17:42:56 -0700130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700133 switch (state)
134 {
135 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700137 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700138 ALOGW("setDeviceConnectionState() device already connected: %x", device);
139 return INVALID_OPERATION;
140 }
141 ALOGV("setDeviceConnectionState() connecting device %x", device);
142
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700144 index = mAvailableOutputDevices.add(devDesc);
145 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100146 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700147 if (module == 0) {
148 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
149 device);
150 mAvailableOutputDevices.remove(devDesc);
151 return INVALID_OPERATION;
152 }
Paul McLeane743a472015-01-28 11:07:31 -0800153 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700154 } else {
155 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700156 }
157
François Gaffie44481e72016-04-20 07:49:57 +0200158 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
159 // parameters on newly connected devices (instead of opening the outputs...)
160 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
161
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200164
165 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
166 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700167 return INVALID_OPERATION;
168 }
François Gaffie2110e042015-03-24 08:41:51 +0100169 // Propagate device availability to Engine
170 mEngine->setDeviceConnectionState(devDesc, state);
171
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700172 // outputs should never be empty here
173 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
174 "checkOutputsForDevice() returned no outputs but status OK");
175 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
176 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800177
Eric Laurent3ae5f312015-02-03 17:12:08 -0800178 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700180 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700181 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700182 ALOGW("setDeviceConnectionState() device not connected: %x", device);
183 return INVALID_OPERATION;
184 }
185
Paul McLean5c477aa2014-08-20 16:47:57 -0700186 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
187
Paul McLeane743a472015-01-28 11:07:31 -0800188 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200189 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700193
Eric Laurenta1d525f2015-01-29 13:36:45 -0800194 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100195
196 // Propagate device availability to Engine
197 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700198 } break;
199
200 default:
201 ALOGE("setDeviceConnectionState() invalid state: %x", state);
202 return BAD_VALUE;
203 }
204
Mikhail Naganov37977152018-07-11 15:54:44 -0700205 checkForDeviceAndOutputChanges([&]() {
206 // outputs must be closed after checkOutputForAllStrategies() is executed
207 if (!outputs.isEmpty()) {
208 for (audio_io_handle_t output : outputs) {
209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
210 // close unused outputs after device disconnection or direct outputs that have been
211 // opened by checkOutputsForDevice() to query dynamic parameters
212 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
213 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
214 (desc->mDirectOpenCount == 0))) {
215 closeOutput(output);
216 }
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700218 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
219 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700220 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700221 return false;
222 });
Eric Laurente552edb2014-03-10 17:42:56 -0700223
Eric Laurent87ffa392015-05-22 10:32:38 -0700224 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700225 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
226 updateCallRouting(newDevice);
227 }
Eric Laurente552edb2014-03-10 17:42:56 -0700228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
230 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
231 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700232 // do not force device change on duplicated output because if device is 0, it will
233 // also force a device 0 for the two outputs it is duplicated to which may override
234 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700235 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100236 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700237 // always force when disconnecting (a non-duplicated device)
238 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700239 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700240 }
Eric Laurente552edb2014-03-10 17:42:56 -0700241 }
242
Eric Laurentd60560a2015-04-10 11:31:20 -0700243 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
244 cleanUpForDevice(devDesc);
245 }
246
Eric Laurent72aa32f2014-05-30 18:51:48 -0700247 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700248 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700249 } // end if is output device
250
Eric Laurente552edb2014-03-10 17:42:56 -0700251 // handle input devices
252 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700253 SortedVector <audio_io_handle_t> inputs;
254
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700256 switch (state)
257 {
258 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700259 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700260 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700261 ALOGW("setDeviceConnectionState() device already connected: %d", device);
262 return INVALID_OPERATION;
263 }
François Gaffie53615e22015-03-19 09:24:12 +0100264 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700265 if (module == NULL) {
266 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
267 device);
268 return INVALID_OPERATION;
269 }
François Gaffie44481e72016-04-20 07:49:57 +0200270
271 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
272 // parameters on newly connected devices (instead of opening the inputs...)
273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
274
Paul McLean9080a4c2015-06-18 08:24:02 -0700275 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200276 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
277 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700278 return INVALID_OPERATION;
279 }
280
Eric Laurent3a4311c2014-03-17 12:00:47 -0700281 index = mAvailableInputDevices.add(devDesc);
282 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800283 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700284 } else {
285 return NO_MEMORY;
286 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800287
François Gaffie2110e042015-03-24 08:41:51 +0100288 // Propagate device availability to Engine
289 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700291
292 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700293 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700295 ALOGW("setDeviceConnectionState() device not connected: %d", device);
296 return INVALID_OPERATION;
297 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700298
299 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
300
301 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200302 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700303
Paul McLean9080a4c2015-06-18 08:24:02 -0700304 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700306
François Gaffie2110e042015-03-24 08:41:51 +0100307 // Propagate device availability to Engine
308 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700309 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700310
311 default:
312 ALOGE("setDeviceConnectionState() invalid state: %x", state);
313 return BAD_VALUE;
314 }
315
Eric Laurentd4692962014-05-05 18:13:44 -0700316 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700317 // As the input device list can impact the output device selection, update
318 // getDeviceForStrategy() cache
319 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700320
Eric Laurent87ffa392015-05-22 10:32:38 -0700321 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
323 updateCallRouting(newDevice);
324 }
325
Eric Laurentd60560a2015-04-10 11:31:20 -0700326 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
327 cleanUpForDevice(devDesc);
328 }
329
Eric Laurentb52c1522014-05-20 11:27:36 -0700330 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700332 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700333
334 ALOGW("setDeviceConnectionState() invalid device: %x", device);
335 return BAD_VALUE;
336}
337
Eric Laurente0720872014-03-11 09:30:41 -0700338audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100339 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700340{
Eric Laurent634b7142016-04-20 13:48:02 -0700341 sp<DeviceDescriptor> devDesc =
342 mHwModules.getDeviceDescriptor(device, device_address, "",
343 (strlen(device_address) != 0)/*matchAddress*/);
344
345 if (devDesc == 0) {
346 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
347 device, device_address);
348 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
349 }
François Gaffie53615e22015-03-19 09:24:12 +0100350
Eric Laurent3a4311c2014-03-17 12:00:47 -0700351 DeviceVector *deviceVector;
352
Eric Laurente552edb2014-03-10 17:42:56 -0700353 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700354 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 deviceVector = &mAvailableInputDevices;
357 } else {
358 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
359 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
Eric Laurent634b7142016-04-20 13:48:02 -0700361
362 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
363 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800364}
365
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800366status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
367 const char *device_address,
368 const char *device_name)
369{
370 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700371 String8 reply;
372 AudioParameter param;
373 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374
375 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
376 device, device_address, device_name);
377
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800378 // connect/disconnect only 1 device at a time
379 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
380
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800381 // Check if the device is currently connected
382 sp<DeviceDescriptor> devDesc =
383 mHwModules.getDeviceDescriptor(device, device_address, device_name);
384 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
385 if (index < 0) {
386 // Nothing to do: device is not connected
387 return NO_ERROR;
388 }
389
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700390 // For offloaded A2DP, Hw modules may have the capability to
391 // configure codecs. Check if any of the loaded hw modules
392 // supports this.
393 // If supported, send a set parameter to configure A2DP codecs
394 // and return. No need to toggle device state.
395 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
396 reply = mpClientInterface->getParameters(
397 AUDIO_IO_HANDLE_NONE,
398 String8(AudioParameter::keyReconfigA2dpSupported));
399 AudioParameter repliedParameters(reply);
400 repliedParameters.getInt(
401 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
402 if (isReconfigA2dpSupported) {
403 const String8 key(AudioParameter::keyReconfigA2dp);
404 param.add(key, String8("true"));
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406 return NO_ERROR;
407 }
408 }
409
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800410 // Toggle the device state: UNAVAILABLE -> AVAILABLE
411 // This will force reading again the device configuration
412 status = setDeviceConnectionState(device,
413 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
414 device_address, device_name);
415 if (status != NO_ERROR) {
416 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
417 status);
418 return status;
419 }
420
421 status = setDeviceConnectionState(device,
422 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
423 device_address, device_name);
424 if (status != NO_ERROR) {
425 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
426 status);
427 return status;
428 }
429
430 return NO_ERROR;
431}
432
Eric Laurentdc462862016-07-19 12:29:53 -0700433uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700434{
435 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700436 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700437
Andy Hunga76c7de2016-12-13 19:14:31 -0800438 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700439 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700440 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800441 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
443
444 // release existing RX patch if any
445 if (mCallRxPatch != 0) {
446 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
447 mCallRxPatch.clear();
448 }
449 // release TX patch if any
450 if (mCallTxPatch != 0) {
451 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
452 mCallTxPatch.clear();
453 }
454
455 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
456 // via setOutputDevice() on primary output.
457 // Otherwise, create two audio patches for TX and RX path.
458 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700459 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 // If the TX device is also on the primary HW module, setOutputDevice() will take care
461 // of it due to legacy implementation. If not, create a patch.
462 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
463 == AUDIO_DEVICE_NONE) {
464 createTxPatch = true;
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468 createTxPatch = true;
469 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700470 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800471 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
472 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 return muteWaitMs;
475}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700476
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800477sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
478 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700480
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 sp<DeviceDescriptor> txSourceDeviceDesc;
482 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700483 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
484 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800485 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700486 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
487 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800488 }
489
490 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
491 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
492 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
493 // request to reuse existing output stream if one is already opened to reach the target device
494 if (output != AUDIO_IO_HANDLE_NONE) {
495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
496 ALOG_ASSERT(!outputDesc->isDuplicated(),
497 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700498 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800499 }
500
501 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 // terminate active capture if on the same HW module as the call TX source device
503 // FIXME: would be better to refine to only inputs whose profile connects to the
504 // call TX device but this information is not in the audio patch and logic here must be
505 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800506 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800507 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
508 AudioSessionCollection activeSessions =
509 activeDesc->getAudioSessions(true /*activeOnly*/);
510 for (size_t j = 0; j < activeSessions.size(); j++) {
511 audio_session_t activeSession = activeSessions.keyAt(j);
512 stopInput(activeDesc->mIoHandle, activeSession);
513 releaseInput(activeDesc->mIoHandle, activeSession);
514 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700515 }
516 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 }
Eric Laurentdc462862016-07-19 12:29:53 -0700518
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800519 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520 status_t status = mpClientInterface->createAudioPatch(
521 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800522 ALOGW_IF(status != NO_ERROR,
523 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
524 sp<AudioPatch> audioPatch;
525 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700526 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 audioPatch->mAfPatchHandle = afPatchHandle;
528 audioPatch->mUid = mUidCached;
529 }
530 return audioPatch;
531}
532
Mikhail Naganovdc769682018-05-04 15:34:08 -0700533sp<DeviceDescriptor> AudioPolicyManager::findDevice(
534 const DeviceVector& devices, audio_devices_t device) {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700535 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800536 ALOG_ASSERT(!deviceList.isEmpty(),
537 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700538 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700539}
540
Eric Laurente0720872014-03-11 09:30:41 -0700541void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700542{
543 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100544 // store previous phone state for management of sonification strategy below
545 int oldState = mEngine->getPhoneState();
546
547 if (mEngine->setPhoneState(state) != NO_ERROR) {
548 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700549 return;
550 }
François Gaffie2110e042015-03-24 08:41:51 +0100551 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700552 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700553 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700554 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800555 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700556 }
557
François Gaffie2110e042015-03-24 08:41:51 +0100558 /**
559 * Switching to or from incall state or switching between telephony and VoIP lead to force
560 * routing command.
561 */
562 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
563 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700564
565 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700566 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700567
Eric Laurente552edb2014-03-10 17:42:56 -0700568 int delayMs = 0;
569 if (isStateInCall(state)) {
570 nsecs_t sysTime = systemTime();
571 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700573 // mute media and sonification strategies and delay device switch by the largest
574 // latency of any output where either strategy is active.
575 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100576 if ((isStrategyActive(desc, STRATEGY_MEDIA,
577 SONIFICATION_HEADSET_MUSIC_DELAY,
578 sysTime) ||
579 isStrategyActive(desc, STRATEGY_SONIFICATION,
580 SONIFICATION_HEADSET_MUSIC_DELAY,
581 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 (delayMs < (int)desc->latency()*2)) {
583 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700584 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 setStrategyMute(STRATEGY_MEDIA, true, desc);
586 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700587 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
589 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700590 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
591 }
592 }
593
Eric Laurent87ffa392015-05-22 10:32:38 -0700594 if (hasPrimaryOutput()) {
595 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
596 // the device returned is not necessarily reachable via this output
597 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
598 // force routing command to audio hardware when ending call
599 // even if no device change is needed
600 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
601 rxDevice = mPrimaryOutput->device();
602 }
Eric Laurente552edb2014-03-10 17:42:56 -0700603
Eric Laurent87ffa392015-05-22 10:32:38 -0700604 if (state == AUDIO_MODE_IN_CALL) {
605 updateCallRouting(rxDevice, delayMs);
606 } else if (oldState == AUDIO_MODE_IN_CALL) {
607 if (mCallRxPatch != 0) {
608 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
609 mCallRxPatch.clear();
610 }
611 if (mCallTxPatch != 0) {
612 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
613 mCallTxPatch.clear();
614 }
615 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
616 } else {
617 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700618 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700620
621 // reevaluate routing on all outputs in case tracks have been started during the call
622 for (size_t i = 0; i < mOutputs.size(); i++) {
623 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
624 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
625 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800626 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700627 }
628 }
629
Eric Laurente552edb2014-03-10 17:42:56 -0700630 if (isStateInCall(state)) {
631 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700632 // force reevaluating accessibility routing when call starts
633 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 }
635
636 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 if (state == AUDIO_MODE_RINGTONE &&
638 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700639 mLimitRingtoneVolume = true;
640 } else {
641 mLimitRingtoneVolume = false;
642 }
643}
644
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700645audio_mode_t AudioPolicyManager::getPhoneState() {
646 return mEngine->getPhoneState();
647}
648
Eric Laurente0720872014-03-11 09:30:41 -0700649void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700650 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700651{
François Gaffie2110e042015-03-24 08:41:51 +0100652 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700653 if (config == mEngine->getForceUse(usage)) {
654 return;
655 }
Eric Laurente552edb2014-03-10 17:42:56 -0700656
François Gaffie2110e042015-03-24 08:41:51 +0100657 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
658 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
659 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700660 }
François Gaffie2110e042015-03-24 08:41:51 +0100661 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
662 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
663 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700664
665 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700666 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800667
Eric Laurentdc462862016-07-19 12:29:53 -0700668 //FIXME: workaround for truncated touch sounds
669 // to be removed when the problem is handled by system UI
670 uint32_t delayMs = 0;
671 uint32_t waitMs = 0;
672 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
673 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
674 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700676 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700677 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678 }
Eric Laurente552edb2014-03-10 17:42:56 -0700679 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700680 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
681 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
682 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700683 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
684 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700685 }
Eric Laurente552edb2014-03-10 17:42:56 -0700686 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700687 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
689 }
690
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800691 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800692 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700693 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800694 if (activeDesc->mProfile->getSupportedDevices().types() &
695 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
696 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700697 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800698 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700699 }
Eric Laurente552edb2014-03-10 17:42:56 -0700700 }
Eric Laurente552edb2014-03-10 17:42:56 -0700701}
702
Eric Laurente0720872014-03-11 09:30:41 -0700703void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700704{
705 ALOGV("setSystemProperty() property %s, value %s", property, value);
706}
707
708// Find a direct output profile compatible with the parameters passed, even if the input flags do
709// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800710sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700711 audio_devices_t device,
712 uint32_t samplingRate,
713 audio_format_t format,
714 audio_channel_mask_t channelMask,
715 audio_output_flags_t flags)
716{
Eric Laurent861a6282015-05-18 15:40:16 -0700717 // only retain flags that will drive the direct output profile selection
718 // if explicitly requested
719 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700720 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
721 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700722 flags =
723 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
724
725 sp<IOProfile> profile;
726
Mikhail Naganovd4120142017-12-06 15:49:22 -0800727 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800728 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700730 samplingRate, NULL /*updatedSamplingRate*/,
731 format, NULL /*updatedFormat*/,
732 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700733 flags)) {
734 continue;
735 }
736 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 continue;
739 }
740 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100741 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700742 continue;
743 }
744 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100745 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700746 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700747 }
Eric Laurente552edb2014-03-10 17:42:56 -0700748 }
749 }
Eric Laurent861a6282015-05-18 15:40:16 -0700750 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700751}
752
Eric Laurentf4e63452017-11-06 19:31:46 +0000753audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700754{
Eric Laurent3b73df72014-03-11 09:06:29 -0700755 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700756 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800757
758 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
759 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
760 // format, flags, etc. This may result in some discrepancy for functions that utilize
761 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
762 // and AudioSystem::getOutputSamplingRate().
763
Eric Laurentf4e63452017-11-06 19:31:46 +0000764 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
765 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700766
Eric Laurentf4e63452017-11-06 19:31:46 +0000767 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
768 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769}
770
Eric Laurente83b55d2014-11-14 10:06:21 -0800771status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
772 audio_io_handle_t *output,
773 audio_session_t session,
774 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700775 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800776 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200777 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700778 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800779 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780{
Eric Laurente83b55d2014-11-14 10:06:21 -0800781 audio_attributes_t attributes;
782 if (attr != NULL) {
783 if (!isValidAttributes(attr)) {
784 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
785 attr->usage, attr->content_type, attr->flags,
786 attr->tags);
787 return BAD_VALUE;
788 }
789 attributes = *attr;
790 } else {
791 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
792 ALOGE("getOutputForAttr(): invalid stream type");
793 return BAD_VALUE;
794 }
795 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700796 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800797
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700798 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
799 " session %d selectedDeviceId %d",
800 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700801 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700802
Scott Randolph7b1fd232018-06-18 15:33:03 -0700803 // TODO: check for existing client for this port ID
804 if (*portId == AUDIO_PORT_HANDLE_NONE) {
805 *portId = AudioPort::getNextUniqueId();
806 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700807
Scott Randolph7b1fd232018-06-18 15:33:03 -0700808 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700809 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700810 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800811 deviceDesc = mAvailableOutputDevices.getDeviceFromId(*selectedDeviceId);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700812 } else {
813 // If no explict route, is there a matching dynamic policy that applies?
814 sp<SwAudioOutputDescriptor> desc;
815 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
816 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
817 if (!audio_has_proportional_frames(config->format)) {
818 return BAD_VALUE;
819 }
820 *stream = streamTypefromAttributesInt(&attributes);
821 *output = desc->mIoHandle;
822 ALOGV("getOutputForAttr() returns output %d", *output);
823 return NO_ERROR;
824 }
825
826 // Virtual sources must always be dynamicaly or explicitly routed
827 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
828 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
829 return BAD_VALUE;
830 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700831 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700832
833 // Virtual sources must always be dynamicaly or explicitly routed
834 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
835 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
836 return BAD_VALUE;
837 }
838
839 *stream = streamTypefromAttributesInt(&attributes);
840
841 // TODO: Should this happen only if an explicit route is active?
842 // the previous code structure meant that this would always happen which
843 // would appear to result in adding a null deviceDesc when not using an
844 // explicit route. Is that the intended and necessary behavior?
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700845 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700846
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700848 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700849
Eric Laurente83b55d2014-11-14 10:06:21 -0800850 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200851 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700852 }
853
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800854 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
855 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200856 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857
Andy Hungc88b0642018-04-27 15:42:35 -0700858 *output = getOutputForDevice(device, session, *stream, config, flags);
Eric Laurente83b55d2014-11-14 10:06:21 -0800859 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700860 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800861 return INVALID_OPERATION;
862 }
Paul McLeanaa981192015-03-21 09:55:15 -0700863
Mikhail Naganov708e0382018-05-30 09:53:04 -0700864 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700865 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
866 : AUDIO_PORT_HANDLE_NONE;
867
868 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
869
Eric Laurente83b55d2014-11-14 10:06:21 -0800870 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871}
872
873audio_io_handle_t AudioPolicyManager::getOutputForDevice(
874 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800875 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700876 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800877 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200878 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700879{
Andy Hungc88b0642018-04-27 15:42:35 -0700880 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700881 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700882
Eric Laurente552edb2014-03-10 17:42:56 -0700883 // open a direct output if required by specified parameters
884 //force direct flag if offload flag is set: offloading implies a direct output stream
885 // and all common behaviors are driven by checking only the direct flag
886 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200887 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
888 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
Nadav Bar766fb022018-01-07 12:18:03 +0200890 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
891 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700892 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800893 // only allow deep buffering for music stream type
894 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200895 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700896 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200897 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700898 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
899 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200900 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800901 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700902 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200903 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700904 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Eric Laurentfe231122017-11-17 17:48:06 -0800905 audio_is_linear_pcm(config->format)) {
Nadav Bar766fb022018-01-07 12:18:03 +0200906 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700907 AUDIO_OUTPUT_FLAG_DIRECT);
908 ALOGV("Set VoIP and Direct output flags for PCM format");
Nadav Bar766fb022018-01-07 12:18:03 +0200909 } else if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
910 stream == AUDIO_STREAM_MUSIC &&
911 audio_is_linear_pcm(config->format) &&
912 isInCall()) {
913 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700914 }
Eric Laurente552edb2014-03-10 17:42:56 -0700915
Nadav Bar766fb022018-01-07 12:18:03 +0200916
Eric Laurentb732cf52014-09-24 19:08:21 -0700917 sp<IOProfile> profile;
918
919 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700920 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200921 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800922 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
923 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700924 goto non_direct_output;
925 }
926
Andy Hung2ddee192015-12-18 17:34:44 -0800927 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
928 // This prevents creating an offloaded track and tearing it down immediately after start
929 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700930 // FIXME: We should check the audio session here but we do not have it in this context.
931 // This may prevent offloading in rare situations where effects are left active by apps
932 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700933
Nadav Bar766fb022018-01-07 12:18:03 +0200934 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800935 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700936 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800937 config->sample_rate,
938 config->format,
939 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200940 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942
Eric Laurent1c333e22014-05-20 10:48:17 -0700943 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700944 // exclusive outputs for MMAP and Offload are enforced by different session ids.
945 for (size_t i = 0; i < mOutputs.size(); i++) {
946 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
947 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
948 // reuse direct output if currently open by the same client
949 // and configured with same parameters
950 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700951 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700952 (config->channel_mask == desc->mChannelMask) &&
953 (session == desc->mDirectClientSession)) {
954 desc->mDirectOpenCount++;
955 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
956 mOutputs.keyAt(i), session);
957 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700958 }
959 }
960 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800961
962 if (!profile->canOpenNewIo()) {
963 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700964 }
Eric Laurent861a6282015-05-18 15:40:16 -0700965
Eric Laurent3974e3b2017-12-07 17:58:43 -0800966 sp<SwAudioOutputDescriptor> outputDesc =
967 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800968
Mikhail Naganov708e0382018-05-30 09:53:04 -0700969 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800970 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
971 : String8("");
972
Nadav Bar766fb022018-01-07 12:18:03 +0200973 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -0700974
975 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700976 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -0800977 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -0700978 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -0800979 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
980 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
981 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
982 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
983 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700984 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -0800985 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -0700986 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800987 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -0800988 if (audio_is_linear_pcm(config->format) &&
989 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800990 goto non_direct_output;
991 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700992 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700993 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700994 outputDesc->mRefCount[stream] = 0;
995 outputDesc->mStopTime[stream] = 0;
996 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -0800997 outputDesc->mDirectClientSession = session;
998
Eric Laurente552edb2014-03-10 17:42:56 -0700999 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001000 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001001 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001002 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001003 return output;
1004 }
1005
Eric Laurentb732cf52014-09-24 19:08:21 -07001006non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001007
1008 // A request for HW A/V sync cannot fallback to a mixed output because time
1009 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001010 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001011 return AUDIO_IO_HANDLE_NONE;
1012 }
1013
Eric Laurente552edb2014-03-10 17:42:56 -07001014 // ignoring channel mask due to downmix capability in mixer
1015
1016 // open a non direct output
1017
1018 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001019 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001020 // get which output is suitable for the specified stream. The actual
1021 // routing change will happen when startOutput() will be called
1022 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1023
Eric Laurent8838a382014-09-08 16:44:28 -07001024 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001025 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1026 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001027 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001028 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001029 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001030 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001031
Eric Laurente552edb2014-03-10 17:42:56 -07001032 return output;
1033}
1034
Eric Laurente0720872014-03-11 09:30:41 -07001035audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001036 audio_output_flags_t flags,
1037 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001038{
1039 // select one output among several that provide a path to a particular device or set of
1040 // devices (the list was previously build by getOutputsForDevice()).
1041 // The priority is as follows:
1042 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001043 // 2: the output with the bit depth the closest to the requested one
1044 // 3: the primary output
1045 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001046
1047 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001048 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
1050 if (outputs.size() == 1) {
1051 return outputs[0];
1052 }
1053
1054 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001055 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1056 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1057 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001058 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1059 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001060
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001061 for (audio_io_handle_t output : outputs) {
1062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001063 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001064 // if a valid format is specified, skip output if not compatible
1065 if (format != AUDIO_FORMAT_INVALID) {
1066 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Andy Hung5659ed52018-04-30 10:31:26 -07001067 if (format != outputDesc->mFormat) {
Eric Laurent8838a382014-09-08 16:44:28 -07001068 continue;
1069 }
1070 } else if (!audio_is_linear_pcm(format)) {
1071 continue;
1072 }
Eric Laurente6930022016-02-11 10:20:40 -08001073 if (AudioPort::isBetterFormatMatch(
1074 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001075 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001076 bestFormat = outputDesc->mFormat;
1077 }
Eric Laurent8838a382014-09-08 16:44:28 -07001078 }
1079
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001080 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001081 if (commonFlags >= maxCommonFlags) {
1082 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001083 if (format != AUDIO_FORMAT_INVALID
1084 && AudioPort::isBetterFormatMatch(
1085 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001086 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001087 bestFormatForFlags = outputDesc->mFormat;
1088 }
1089 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001090 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001091 maxCommonFlags = commonFlags;
1092 bestFormatForFlags = outputDesc->mFormat;
1093 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001094 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001096 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001097 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001098 }
1099 }
1100 }
1101
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001102 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001103 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001104 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001105 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001106 return outputForFormat;
1107 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001108 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001109 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001110 }
1111
1112 return outputs[0];
1113}
1114
Eric Laurente0720872014-03-11 09:30:41 -07001115status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001116 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001117 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001118{
Paul McLeanaa981192015-03-21 09:55:15 -07001119 ALOGV("startOutput() output %d, stream %d, session %d",
1120 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001121 ssize_t index = mOutputs.indexOfKey(output);
1122 if (index < 0) {
1123 ALOGW("startOutput() unknown output %d", output);
1124 return BAD_VALUE;
1125 }
1126
Eric Laurentc75307b2015-03-17 15:29:32 -07001127 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1128
Eric Laurent733ce942017-12-07 12:18:25 -08001129 status_t status = outputDesc->start();
1130 if (status != NO_ERROR) {
1131 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001132 }
1133
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001134 // Routing?
1135 mOutputRoutes.incRouteActivity(session);
1136
Eric Laurentc75307b2015-03-17 15:29:32 -07001137 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001138 AudioMix *policyMix = NULL;
1139 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001140 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001141 policyMix = outputDesc->mPolicyMix;
1142 address = policyMix->mDeviceAddress.string();
1143 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1144 newDevice = policyMix->mDeviceType;
1145 } else {
1146 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1147 }
Eric Laurent2157f5b2018-04-25 18:33:02 -07001148 } else if (mOutputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent493404d2015-04-21 15:07:36 -07001149 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurentf3a5a602018-05-22 18:42:55 -07001150 if (newDevice != outputDesc->device()) {
1151 checkStrategyRoute(getStrategy(stream), output);
1152 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001153 } else {
1154 newDevice = AUDIO_DEVICE_NONE;
1155 }
1156
1157 uint32_t delayMs = 0;
1158
Eric Laurent733ce942017-12-07 12:18:25 -08001159 status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001160
1161 if (status != NO_ERROR) {
1162 mOutputRoutes.decRouteActivity(session);
Eric Laurent733ce942017-12-07 12:18:25 -08001163 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001164 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001165 }
1166 // Automatically enable the remote submix input when output is started on a re routing mix
1167 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001168 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1169 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001170 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1171 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001172 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 "remote-submix");
1174 }
1175
1176 if (delayMs != 0) {
1177 usleep(delayMs * 1000);
1178 }
1179
1180 return status;
1181}
1182
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001183status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 audio_stream_type_t stream,
1185 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001186 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001187 uint32_t *delayMs)
1188{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001189 // cannot start playback of STREAM_TTS if any other output is being used
1190 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001191
1192 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001193 if (stream == AUDIO_STREAM_TTS) {
1194 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001195 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001196 return INVALID_OPERATION;
1197 } else {
1198 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1199 }
1200 } else {
1201 // some playback other than beacon starts
1202 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1203 }
1204
Eric Laurent77305a62016-07-25 16:39:22 -07001205 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001206 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001207 bool force = !outputDesc->isActive() &&
1208 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001209
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001210 // requiresMuteCheck is false when we can bypass mute strategy.
1211 // It covers a common case when there is no materially active audio
1212 // and muting would result in unnecessary delay and dropped audio.
1213 const uint32_t outputLatencyMs = outputDesc->latency();
1214 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1215
Eric Laurente552edb2014-03-10 17:42:56 -07001216 // increment usage count for this stream on the requested output:
1217 // NOTE that the usage count is the same for duplicated output and hardware output which is
1218 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1219 outputDesc->changeRefCount(stream, 1);
1220
Eric Laurent36829f92017-04-07 19:04:42 -07001221 if (stream == AUDIO_STREAM_MUSIC) {
1222 selectOutputForMusicEffects();
1223 }
1224
Eric Laurent493404d2015-04-21 15:07:36 -07001225 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001226 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001227 if (device == AUDIO_DEVICE_NONE) {
1228 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001229 }
Eric Laurent36829f92017-04-07 19:04:42 -07001230
Eric Laurente552edb2014-03-10 17:42:56 -07001231 routing_strategy strategy = getStrategy(stream);
1232 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001233 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1234 (beaconMuteLatency > 0);
1235 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001236 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001237 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001238 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001239 // An output has a shared device if
1240 // - managed by the same hw module
1241 // - supports the currently selected device
1242 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1243 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1244
Eric Laurent77305a62016-07-25 16:39:22 -07001245 // force a device change if any other output is:
1246 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001247 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001248 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001249 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001250 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001251 // change the device currently selected by the other output.
1252 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001253 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001254 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001255 force = true;
1256 }
1257 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001258 // a notification so that audio focus effect can propagate, or that a mute/unmute
1259 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001260 const uint32_t latencyMs = desc->latency();
1261 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1262
1263 if (shouldWait && isActive && (waitMs < latencyMs)) {
1264 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001265 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001266
1267 // Require mute check if another output is on a shared device
1268 // and currently active to have proper drain and avoid pops.
1269 // Note restoring AudioTracks onto this output needs to invoke
1270 // a volume ramp if there is no mute.
1271 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001272 }
1273 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001274
1275 const uint32_t muteWaitMs =
1276 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001277
Eric Laurente552edb2014-03-10 17:42:56 -07001278 // apply volume rules for current stream and device if necessary
1279 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001280 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001281 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001282 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001283
1284 // update the outputs if starting an output with a stream that can affect notification
1285 // routing
1286 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001287
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001288 // force reevaluating accessibility routing when ringtone or alarm starts
1289 if (strategy == STRATEGY_SONIFICATION) {
1290 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1291 }
Eric Laurentdc462862016-07-19 12:29:53 -07001292
1293 if (waitMs > muteWaitMs) {
1294 *delayMs = waitMs - muteWaitMs;
1295 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001296
1297 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1298 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1299 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1300 // change occurs after the MixerThread starts and causes a stream volume
1301 // glitch.
1302 //
1303 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001304 }
Eric Laurentdc462862016-07-19 12:29:53 -07001305
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001306 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1307 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1308 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1309 }
1310
Tomoharu Kasaharaa81f0982018-01-18 20:55:02 +09001311 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1312 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1313 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1314 }
1315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 return NO_ERROR;
1317}
1318
1319
Eric Laurente0720872014-03-11 09:30:41 -07001320status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001321 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001322 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001323{
1324 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1325 ssize_t index = mOutputs.indexOfKey(output);
1326 if (index < 0) {
1327 ALOGW("stopOutput() unknown output %d", output);
1328 return BAD_VALUE;
1329 }
1330
Eric Laurentc75307b2015-03-17 15:29:32 -07001331 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001332
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 if (outputDesc->mRefCount[stream] == 1) {
1334 // Automatically disable the remote submix input when output is stopped on a
1335 // re routing mix of type MIX_TYPE_RECORDERS
1336 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1337 outputDesc->mPolicyMix != NULL &&
1338 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1339 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1340 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001341 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001342 "remote-submix");
1343 }
1344 }
1345
1346 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001347 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001348 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 int activityCount = mOutputRoutes.decRouteActivity(session);
1350 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1351
1352 if (forceDeviceUpdate) {
1353 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1354 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001355 }
1356
Eric Laurent3974e3b2017-12-07 17:58:43 -08001357 status_t status = stopSource(outputDesc, stream, forceDeviceUpdate);
1358
Eric Laurent733ce942017-12-07 12:18:25 -08001359 if (status == NO_ERROR ) {
1360 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001361 }
1362 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001363}
1364
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001365status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001366 audio_stream_type_t stream,
1367 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001368{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001369 // always handle stream stop, check which stream type is stopping
1370 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1371
Eric Laurente552edb2014-03-10 17:42:56 -07001372 if (outputDesc->mRefCount[stream] > 0) {
1373 // decrement usage count of this stream on the output
1374 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001375
Eric Laurente552edb2014-03-10 17:42:56 -07001376 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001377 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001378 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001379 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001380 // delay the device switch by twice the latency because stopOutput() is executed when
1381 // the track stop() command is received and at that time the audio track buffer can
1382 // still contain data that needs to be drained. The latency only covers the audio HAL
1383 // and kernel buffers. Also the latency does not always include additional delay in the
1384 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001385 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001386
1387 // force restoring the device selection on other active outputs if it differs from the
1388 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001389 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001390 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001391 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001392 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001393 desc->isActive() &&
1394 outputDesc->sharesHwModuleWith(desc) &&
1395 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001396 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1397 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001398
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001400 newDevice2,
1401 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001402 delayMs);
1403 // re-apply device specific volume if not done by setOutputDevice()
1404 if (!force) {
1405 applyStreamVolumes(desc, newDevice2, delayMs);
1406 }
Eric Laurente552edb2014-03-10 17:42:56 -07001407 }
1408 }
1409 // update the outputs if stopping one with a stream that can affect notification routing
1410 handleNotificationRoutingForStream(stream);
1411 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001412
1413 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1414 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1415 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1416 }
1417
Eric Laurent36829f92017-04-07 19:04:42 -07001418 if (stream == AUDIO_STREAM_MUSIC) {
1419 selectOutputForMusicEffects();
1420 }
Eric Laurente552edb2014-03-10 17:42:56 -07001421 return NO_ERROR;
1422 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001423 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001424 return INVALID_OPERATION;
1425 }
1426}
1427
Eric Laurente83b55d2014-11-14 10:06:21 -08001428void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001429 audio_stream_type_t stream __unused,
1430 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001431{
1432 ALOGV("releaseOutput() %d", output);
1433 ssize_t index = mOutputs.indexOfKey(output);
1434 if (index < 0) {
1435 ALOGW("releaseOutput() releasing unknown output %d", output);
1436 return;
1437 }
1438
Paul McLeanaa981192015-03-21 09:55:15 -07001439 // Routing
1440 mOutputRoutes.removeRoute(session);
1441
Eric Laurentc75307b2015-03-17 15:29:32 -07001442 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001443 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001444 if (desc->mDirectOpenCount <= 0) {
1445 ALOGW("releaseOutput() invalid open count %d for output %d",
1446 desc->mDirectOpenCount, output);
1447 return;
1448 }
1449 if (--desc->mDirectOpenCount == 0) {
1450 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001451 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001452 }
1453 }
1454}
1455
1456
Eric Laurentcaf7f482014-11-25 17:50:47 -08001457status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1458 audio_io_handle_t *input,
1459 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001460 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001461 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001462 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001463 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001464 input_type_t *inputType,
1465 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001466{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001467 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001468 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001469 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001470
Eric Laurentad2e7b92017-09-14 20:06:42 -07001471 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001472 // handle legacy remote submix case where the address was not always specified
1473 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001474 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001475 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001476 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001477 DeviceVector inputDevices;
Eric Laurent20b9ef02016-12-05 11:03:16 -08001478
Eric Laurentfe231122017-11-17 17:48:06 -08001479 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1480 inputSource = AUDIO_SOURCE_MIC;
1481 }
1482
Paul McLean466dc8e2015-04-17 13:15:36 -06001483 // Explicit routing?
1484 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001485 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001486 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001487 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001488 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001489
Eric Laurentad2e7b92017-09-14 20:06:42 -07001490 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1491 // possible
1492 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1493 *input != AUDIO_IO_HANDLE_NONE) {
1494 ssize_t index = mInputs.indexOfKey(*input);
1495 if (index < 0) {
1496 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1497 status = BAD_VALUE;
1498 goto error;
1499 }
1500 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1501 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1502 if (audioSession == 0) {
1503 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1504 status = BAD_VALUE;
1505 goto error;
1506 }
1507 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1508 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001509 // corresponds to a new client and is only permitted from the same UID.
1510 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurentad2e7b92017-09-14 20:06:42 -07001511 if (audioSession->openCount() == 1) {
1512 audioSession->setUid(uid);
1513 } else if (audioSession->uid() != uid) {
Eric Laurent331679c2018-04-16 17:03:16 -07001514 if (!audioSession->isSilenced()) {
1515 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1516 uid, session, audioSession->uid());
1517 status = INVALID_OPERATION;
1518 goto error;
1519 }
1520 audioSession->setUid(uid);
1521 audioSession->setSilenced(false);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001522 }
1523 audioSession->changeOpenCount(1);
1524 *inputType = API_INPUT_LEGACY;
1525 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1526 *portId = AudioPort::getNextUniqueId();
1527 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07001528 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(inputDesc->mDevice);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001529 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1530 : AUDIO_PORT_HANDLE_NONE;
1531 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1532
1533 return NO_ERROR;
1534 }
1535
1536 *input = AUDIO_IO_HANDLE_NONE;
1537 *inputType = API_INPUT_INVALID;
1538
Eric Laurentad2e7b92017-09-14 20:06:42 -07001539 halInputSource = inputSource;
1540
1541 // TODO: check for existing client for this port ID
1542 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1543 *portId = AudioPort::getNextUniqueId();
1544 }
1545
1546 audio_devices_t device;
1547
Eric Laurentc447ded2015-01-06 08:47:05 -08001548 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001549 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001550 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1551 if (status != NO_ERROR) {
1552 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001553 }
1554 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001555 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1556 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001557 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001558 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001559 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001560 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001561 status = BAD_VALUE;
1562 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001563 }
Eric Laurentc722f302014-12-10 11:21:49 -08001564 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001565 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001566 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1567 // there is an external policy, but this input is attached to a mix of recorders,
1568 // meaning it receives audio injected into the framework, so the recorder doesn't
1569 // know about it and is therefore considered "legacy"
1570 *inputType = API_INPUT_LEGACY;
1571 } else {
1572 // recording a mix of players defined by an external policy, we're rerouting for
1573 // an external policy
1574 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1575 }
Eric Laurentc722f302014-12-10 11:21:49 -08001576 } else if (audio_is_remote_submix_device(device)) {
1577 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001578 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001579 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1580 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001581 } else {
1582 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001583 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001584
Eric Laurent599c7582015-12-07 18:05:55 -08001585 }
1586
1587 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001588 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001589 policyMix);
1590 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001591 status = INVALID_OPERATION;
1592 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001593 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001594
Mikhail Naganov708e0382018-05-30 09:53:04 -07001595 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001596 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1597 : AUDIO_PORT_HANDLE_NONE;
1598
1599 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1600 *input, *inputType, *selectedDeviceId);
1601
Eric Laurent599c7582015-12-07 18:05:55 -08001602 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001603
1604error:
1605 mInputRoutes.removeRoute(session);
1606 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001607}
1608
1609
1610audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1611 String8 address,
1612 audio_session_t session,
1613 uid_t uid,
1614 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001615 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001616 audio_input_flags_t flags,
1617 AudioMix *policyMix)
1618{
1619 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1620 audio_source_t halInputSource = inputSource;
1621 bool isSoundTrigger = false;
1622
1623 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1624 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1625 if (index >= 0) {
1626 input = mSoundTriggerSessions.valueFor(session);
1627 isSoundTrigger = true;
1628 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1629 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1630 } else {
1631 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001632 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001633 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001634 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001635 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001636 }
1637
Andy Hungf129b032015-04-07 13:45:50 -07001638 // find a compatible input profile (not necessarily identical in parameters)
1639 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001640 // sampling rate and flags may be updated by getInputProfile
1641 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1642 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001643 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001644 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001645 audio_input_flags_t profileFlags = flags;
1646 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001647 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001648 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001649 profileSamplingRate, profileFormat, profileChannelMask,
1650 profileFlags);
1651 if (profile != 0) {
1652 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001653 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1654 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001655 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1656 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1657 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001658 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001659 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1660 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001661 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001662 }
Eric Laurente552edb2014-03-10 17:42:56 -07001663 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001664 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001665 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001666 if (samplingRate == 0) {
1667 samplingRate = profileSamplingRate;
1668 }
Eric Laurente552edb2014-03-10 17:42:56 -07001669
Eric Laurent322b4d22015-04-03 15:57:54 -07001670 if (profile->getModuleHandle() == 0) {
1671 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001672 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001673 }
1674
Eric Laurent599c7582015-12-07 18:05:55 -08001675 sp<AudioSession> audioSession = new AudioSession(session,
Eric Laurentfe231122017-11-17 17:48:06 -08001676 inputSource,
1677 config->format,
1678 samplingRate,
1679 config->channel_mask,
1680 flags,
1681 uid,
Eric Laurenta18dced2018-07-20 15:14:54 -07001682 isSoundTrigger);
Eric Laurent599c7582015-12-07 18:05:55 -08001683
Eric Laurent74708e72017-04-07 17:13:42 -07001684// FIXME: disable concurrent capture until UI is ready
1685#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001686 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001687 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001688 for (size_t i = 0; i < mInputs.size(); i++) {
1689 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001690 // reuse input if:
1691 // - it shares the same profile
1692 // AND
1693 // - it is not a reroute submix input
1694 // AND
1695 // - it is: not used for sound trigger
1696 // OR
1697 // used for sound trigger and all clients use the same session ID
1698 //
1699 if ((profile == desc->mProfile) &&
1700 (isSoundTrigger == desc->isSoundTrigger()) &&
1701 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001702
1703 sp<AudioSession> as = desc->getAudioSession(session);
1704 if (as != 0) {
1705 // do not allow unmatching properties on same session
1706 if (as->matches(audioSession)) {
1707 as->changeOpenCount(1);
1708 } else {
1709 ALOGW("getInputForDevice() record with different attributes"
1710 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001711 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001712 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001713 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001714 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001715 }
Eric Laurentbb948092017-01-23 18:33:30 -08001716
Eric Laurent555530a2017-02-07 18:17:24 -08001717 // Reuse the already opened input stream on this profile if:
1718 // - the new capture source is background OR
1719 // - the path requested configurations match OR
1720 // - the new source priority is less than the highest source priority on this input
1721 // If the input stream cannot be reused, close it before opening a new stream
1722 // on the same profile for the new client so that the requested path configuration
1723 // can be selected.
1724 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001725 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfe231122017-11-17 17:48:06 -08001726 desc->mChannelMask != config->channel_mask ||
1727 !audio_formats_match(desc->mFormat, config->format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001728 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001729 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001730 reusedInputDesc = desc;
1731 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001732 } else {
1733 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001734 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1735 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001736 }
Eric Laurent599c7582015-12-07 18:05:55 -08001737 }
1738 }
Eric Laurent599c7582015-12-07 18:05:55 -08001739
Eric Laurent555530a2017-02-07 18:17:24 -08001740 if (reusedInputDesc != 0) {
1741 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1742 for (size_t j = 0; j < sessions.size(); j++) {
1743 audio_session_t currentSession = sessions.keyAt(j);
1744 stopInput(reusedInputDesc->mIoHandle, currentSession);
1745 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1746 }
1747 }
Eric Laurent74708e72017-04-07 17:13:42 -07001748#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001749
Eric Laurent3974e3b2017-12-07 17:58:43 -08001750 if (!profile->canOpenNewIo()) {
1751 return AUDIO_IO_HANDLE_NONE;
1752 }
1753
Eric Laurentfe231122017-11-17 17:48:06 -08001754 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001755
Eric Laurentfe231122017-11-17 17:48:06 -08001756 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1757 lConfig.sample_rate = profileSamplingRate;
1758 lConfig.channel_mask = profileChannelMask;
1759 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001760
Eric Laurent53b810e2017-12-10 17:25:10 -08001761 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001762 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001763 // the inputs vector must be of size >= 1, but we don't want to crash here
1764 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1765 }
1766
Eric Laurentfe231122017-11-17 17:48:06 -08001767 status_t status = inputDesc->open(&lConfig, device, address,
1768 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001769
1770 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001771 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001772 (profileSamplingRate != lConfig.sample_rate) ||
1773 !audio_formats_match(profileFormat, lConfig.format) ||
1774 (profileChannelMask != lConfig.channel_mask)) {
1775 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001776 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001777 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001778 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001779 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001780 }
Eric Laurent599c7582015-12-07 18:05:55 -08001781 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001782 }
1783
Eric Laurentc722f302014-12-10 11:21:49 -08001784 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001785 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001786
Eric Laurent599c7582015-12-07 18:05:55 -08001787 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001788 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001789
Eric Laurent599c7582015-12-07 18:05:55 -08001790 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001791}
1792
Eric Laurentbb948092017-01-23 18:33:30 -08001793//static
1794bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1795{
1796 return (source == AUDIO_SOURCE_HOTWORD) ||
1797 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1798 (source == AUDIO_SOURCE_FM_TUNER);
1799}
1800
Eric Laurentfb66dd92016-01-28 18:32:03 -08001801bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1802 const sp<AudioSession>& audioSession)
1803{
1804 // Do not allow capture if an active voice call is using a software patch and
1805 // the call TX source device is on the same HW module.
1806 // FIXME: would be better to refine to only inputs whose profile connects to the
1807 // call TX device but this information is not in the audio patch
1808 if (mCallTxPatch != 0 &&
1809 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1810 return false;
1811 }
1812
1813 // starting concurrent capture is enabled if:
1814 // 1) capturing for re-routing
1815 // 2) capturing for HOTWORD source
1816 // 3) capturing for FM TUNER source
1817 // 3) All other active captures are either for re-routing or HOTWORD
1818
1819 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001820 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001821 return true;
1822 }
1823
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001824 for (const auto& activeInput : mInputs.getActiveInputs()) {
Eric Laurentbb948092017-01-23 18:33:30 -08001825 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001826 !is_virtual_input_device(activeInput->mDevice)) {
1827 return false;
1828 }
1829 }
1830
1831 return true;
1832}
1833
Chris Thornton2b864642017-06-27 21:26:07 -07001834// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1835bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1836 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1837 bool soundTriggerSupportsConcurrentCapture = false;
1838 unsigned int numModules = 0;
1839 struct sound_trigger_module_descriptor* nModules = NULL;
1840
1841 status_t status = SoundTrigger::listModules(nModules, &numModules);
1842 if (status == NO_ERROR && numModules != 0) {
1843 nModules = (struct sound_trigger_module_descriptor*) calloc(
1844 numModules, sizeof(struct sound_trigger_module_descriptor));
1845 if (nModules == NULL) {
1846 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1847 // ram the next time this function is called.
1848 ALOGE("Failed to allocate buffer for module descriptors");
1849 return false;
1850 }
1851
1852 status = SoundTrigger::listModules(nModules, &numModules);
1853 if (status == NO_ERROR) {
1854 soundTriggerSupportsConcurrentCapture = true;
1855 for (size_t i = 0; i < numModules; ++i) {
1856 soundTriggerSupportsConcurrentCapture &=
1857 nModules[i].properties.concurrent_capture;
1858 }
1859 }
1860 free(nModules);
1861 }
1862 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1863 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1864 }
1865 return mSoundTriggerSupportsConcurrentCapture;
1866}
1867
Eric Laurentfb66dd92016-01-28 18:32:03 -08001868
Eric Laurent4dc68062014-07-28 17:26:49 -07001869status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001870 audio_session_t session,
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001871 bool silenced,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001872 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001873{
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001874
1875 ALOGV("AudioPolicyManager::startInput(input:%d, session:%d, silenced:%d, concurrency:%d)",
1876 input, session, silenced, *concurrency);
1877
Eric Laurentfb66dd92016-01-28 18:32:03 -08001878 *concurrency = API_INPUT_CONCURRENCY_NONE;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001879
Eric Laurente552edb2014-03-10 17:42:56 -07001880 ssize_t index = mInputs.indexOfKey(input);
1881 if (index < 0) {
1882 ALOGW("startInput() unknown input %d", input);
1883 return BAD_VALUE;
1884 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001885 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001886
Eric Laurent599c7582015-12-07 18:05:55 -08001887 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1888 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001889 ALOGW("startInput() unknown session %d on input %d", session, input);
1890 return BAD_VALUE;
1891 }
1892
Eric Laurent74708e72017-04-07 17:13:42 -07001893// FIXME: disable concurrent capture until UI is ready
1894#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001895 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1896 ALOGW("startInput(%d) failed: other input already started", input);
1897 return INVALID_OPERATION;
1898 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001899
Eric Laurentfb66dd92016-01-28 18:32:03 -08001900 if (isInCall()) {
1901 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1902 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001903 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001904 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001905 }
Eric Laurent74708e72017-04-07 17:13:42 -07001906#else
1907 if (!is_virtual_input_device(inputDesc->mDevice)) {
1908 if (mCallTxPatch != 0 &&
1909 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1910 ALOGW("startInput(%d) failed: call in progress", input);
Ray Essick84e84a52018-05-03 18:45:07 -07001911 *concurrency |= API_INPUT_CONCURRENCY_CALL;
Eric Laurent74708e72017-04-07 17:13:42 -07001912 return INVALID_OPERATION;
1913 }
1914
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001915 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001916
Svet Ganovf4ddfef2018-01-16 07:37:58 -08001917 // If a UID is idle and records silence and another not silenced recording starts
1918 // from another UID (idle or active) we stop the current idle UID recording in
1919 // favor of the new one - "There can be only one" TM
1920 if (!silenced) {
1921 for (const auto& activeDesc : activeInputs) {
1922 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1923 activeDesc->getId() == inputDesc->getId()) {
1924 continue;
1925 }
1926
1927 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(
1928 true /*activeOnly*/);
1929 sp<AudioSession> activeSession = activeSessions.valueAt(0);
1930 if (activeSession->isSilenced()) {
1931 audio_io_handle_t activeInput = activeDesc->mIoHandle;
1932 audio_session_t activeSessionId = activeSession->session();
1933 stopInput(activeInput, activeSessionId);
1934 releaseInput(activeInput, activeSessionId);
1935 ALOGV("startInput(%d) stopping silenced input %d", input, activeInput);
1936 activeInputs = mInputs.getActiveInputs();
1937 }
1938 }
1939 }
1940
1941 for (const auto& activeDesc : activeInputs) {
Eric Laurentcb4dae22017-07-01 19:39:32 -07001942 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1943 activeDesc->getId() == inputDesc->getId()) {
1944 continue;
1945 }
1946
Eric Laurent74708e72017-04-07 17:13:42 -07001947 audio_source_t activeSource = activeDesc->inputSource(true);
1948 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1949 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1950 if (activeDesc->hasPreemptedSession(session)) {
1951 ALOGW("startInput(%d) failed for HOTWORD: "
1952 "other input %d already started for HOTWORD",
1953 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001954 *concurrency |= API_INPUT_CONCURRENCY_HOTWORD;
Eric Laurent74708e72017-04-07 17:13:42 -07001955 return INVALID_OPERATION;
1956 }
1957 } else {
1958 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1959 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001960 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001961 return INVALID_OPERATION;
1962 }
1963 } else {
1964 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1965 ALOGW("startInput(%d) failed: other input %d already started",
1966 input, activeDesc->mIoHandle);
Ray Essick84e84a52018-05-03 18:45:07 -07001967 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurent74708e72017-04-07 17:13:42 -07001968 return INVALID_OPERATION;
1969 }
1970 }
1971 }
1972
Chris Thornton2b864642017-06-27 21:26:07 -07001973 // We only need to check if the sound trigger session supports concurrent capture if the
1974 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1975 // that's running.
1976 const bool allowConcurrentWithSoundTrigger =
1977 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1978
Eric Laurent74708e72017-04-07 17:13:42 -07001979 // if capture is allowed, preempt currently active HOTWORD captures
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001980 for (const auto& activeDesc : activeInputs) {
Chris Thornton2b864642017-06-27 21:26:07 -07001981 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1982 continue;
1983 }
1984
Eric Laurent74708e72017-04-07 17:13:42 -07001985 audio_source_t activeSource = activeDesc->inputSource(true);
1986 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1987 AudioSessionCollection activeSessions =
1988 activeDesc->getAudioSessions(true /*activeOnly*/);
1989 audio_session_t activeSession = activeSessions.keyAt(0);
1990 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1991 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
Ray Essick84e84a52018-05-03 18:45:07 -07001992 *concurrency |= API_INPUT_CONCURRENCY_PREEMPT;
Eric Laurent74708e72017-04-07 17:13:42 -07001993 sessions.add(activeSession);
1994 inputDesc->setPreemptedSessions(sessions);
1995 stopInput(activeHandle, activeSession);
1996 releaseInput(activeHandle, activeSession);
1997 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1998 input, activeDesc->mIoHandle);
1999 }
2000 }
2001 }
2002#endif
Eric Laurente552edb2014-03-10 17:42:56 -07002003
Svet Ganovf4ddfef2018-01-16 07:37:58 -08002004 // Make sure we start with the correct silence state
2005 audioSession->setSilenced(silenced);
2006
Eric Laurent313d1e72016-01-29 09:56:57 -08002007 // increment activity count before calling getNewInputDevice() below as only active sessions
2008 // are considered for device selection
Eric Laurenta18dced2018-07-20 15:14:54 -07002009 inputDesc->changeRefCount(session, 1);
Eric Laurent313d1e72016-01-29 09:56:57 -08002010
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002011 // Routing?
2012 mInputRoutes.incRouteActivity(session);
2013
Eric Laurent2157f5b2018-04-25 18:33:02 -07002014 if (audioSession->activeCount() == 1 || mInputRoutes.getAndClearRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002015 // indicate active capture to sound trigger service if starting capture from a mic on
2016 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002017 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002018 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002019
Eric Laurent733ce942017-12-07 12:18:25 -08002020 status_t status = inputDesc->start();
2021 if (status != NO_ERROR) {
2022 mInputRoutes.decRouteActivity(session);
Eric Laurenta18dced2018-07-20 15:14:54 -07002023 inputDesc->changeRefCount(session, -1);
Eric Laurent733ce942017-12-07 12:18:25 -08002024 return status;
2025 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002026
Eric Laurent733ce942017-12-07 12:18:25 -08002027 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002028 // if input maps to a dynamic policy with an activity listener, notify of state change
2029 if ((inputDesc->mPolicyMix != NULL)
2030 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2031 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2032 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002033 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002034
Eric Laurentf7c50102016-09-30 15:19:43 -07002035 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2036 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002037 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002038 SoundTrigger::setCaptureState(true);
2039 }
2040
2041 // automatically enable the remote submix output when input is started if not
2042 // used by a policy mix of type MIX_TYPE_RECORDERS
2043 // For remote submix (a virtual device), we open only one input per capture request.
2044 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2045 String8 address = String8("");
2046 if (inputDesc->mPolicyMix == NULL) {
2047 address = String8("0");
2048 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2049 address = inputDesc->mPolicyMix->mDeviceAddress;
2050 }
2051 if (address != "") {
2052 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2053 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2054 address, "remote-submix");
2055 }
Eric Laurentc722f302014-12-10 11:21:49 -08002056 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002057 }
Eric Laurente552edb2014-03-10 17:42:56 -07002058 }
2059
Eric Laurent599c7582015-12-07 18:05:55 -08002060 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002061
Eric Laurente552edb2014-03-10 17:42:56 -07002062 return NO_ERROR;
2063}
2064
Eric Laurent4dc68062014-07-28 17:26:49 -07002065status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2066 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002067{
2068 ALOGV("stopInput() input %d", input);
2069 ssize_t index = mInputs.indexOfKey(input);
2070 if (index < 0) {
2071 ALOGW("stopInput() unknown input %d", input);
2072 return BAD_VALUE;
2073 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002074 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002075
Eric Laurent599c7582015-12-07 18:05:55 -08002076 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002077 if (index < 0) {
2078 ALOGW("stopInput() unknown session %d on input %d", session, input);
2079 return BAD_VALUE;
2080 }
2081
Eric Laurent599c7582015-12-07 18:05:55 -08002082 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002083 ALOGW("stopInput() input %d already stopped", input);
2084 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002085 }
2086
Eric Laurenta18dced2018-07-20 15:14:54 -07002087 inputDesc->changeRefCount(session, -1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002088
2089 // Routing?
2090 mInputRoutes.decRouteActivity(session);
2091
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002092 if (audioSession->activeCount() == 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08002093 inputDesc->stop();
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002094 if (inputDesc->isActive()) {
2095 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2096 } else {
2097 // if input maps to a dynamic policy with an activity listener, notify of state change
2098 if ((inputDesc->mPolicyMix != NULL)
2099 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2100 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2101 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002102 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002103
2104 // automatically disable the remote submix output when input is stopped if not
2105 // used by a policy mix of type MIX_TYPE_RECORDERS
2106 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2107 String8 address = String8("");
2108 if (inputDesc->mPolicyMix == NULL) {
2109 address = String8("0");
2110 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2111 address = inputDesc->mPolicyMix->mDeviceAddress;
2112 }
2113 if (address != "") {
2114 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2115 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2116 address, "remote-submix");
2117 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002118 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002119
Eric Laurentf7c50102016-09-30 15:19:43 -07002120 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002121 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002122
Eric Laurentf7c50102016-09-30 15:19:43 -07002123 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2124 // primary HW module
2125 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2126 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2127 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002128 SoundTrigger::setCaptureState(false);
2129 }
2130 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002131 }
Eric Laurente552edb2014-03-10 17:42:56 -07002132 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002133 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002134}
2135
Eric Laurent4dc68062014-07-28 17:26:49 -07002136void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2137 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002138{
2139 ALOGV("releaseInput() %d", input);
2140 ssize_t index = mInputs.indexOfKey(input);
2141 if (index < 0) {
2142 ALOGW("releaseInput() releasing unknown input %d", input);
2143 return;
2144 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002145
2146 // Routing
2147 mInputRoutes.removeRoute(session);
2148
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002149 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2150 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002151
Eric Laurent599c7582015-12-07 18:05:55 -08002152 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002153 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002154 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2155 return;
2156 }
Eric Laurent599c7582015-12-07 18:05:55 -08002157
2158 if (audioSession->openCount() == 0) {
2159 ALOGW("releaseInput() invalid open count %d on session %d",
2160 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002161 return;
2162 }
Eric Laurent599c7582015-12-07 18:05:55 -08002163
2164 if (audioSession->changeOpenCount(-1) == 0) {
2165 inputDesc->removeAudioSession(session);
2166 }
2167
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002168 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002169 ALOGV("releaseInput() exit > 0");
2170 return;
2171 }
2172
Eric Laurent05b90f82014-08-27 15:32:29 -07002173 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002174 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002175 ALOGV("releaseInput() exit");
2176}
2177
Eric Laurentd4692962014-05-05 18:13:44 -07002178void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002179 bool patchRemoved = false;
2180
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002181 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002182 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002183 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002184 if (patch_index >= 0) {
2185 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002186 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002187 mAudioPatches.removeItemsAt(patch_index);
2188 patchRemoved = true;
2189 }
Eric Laurentfe231122017-11-17 17:48:06 -08002190 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002191 }
jiabin829a00b2018-04-04 16:28:32 -07002192 mInputRoutes.clear();
Eric Laurentd4692962014-05-05 18:13:44 -07002193 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002194 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002195 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002196
2197 if (patchRemoved) {
2198 mpClientInterface->onAudioPatchListUpdate();
2199 }
Eric Laurentd4692962014-05-05 18:13:44 -07002200}
2201
Eric Laurente0720872014-03-11 09:30:41 -07002202void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002203 int indexMin,
2204 int indexMax)
2205{
2206 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002207 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002208
2209 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002210 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2211 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002212 continue;
2213 }
2214 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002215 }
Eric Laurente552edb2014-03-10 17:42:56 -07002216}
2217
Eric Laurente0720872014-03-11 09:30:41 -07002218status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002219 int index,
2220 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002221{
2222
Nadav Bar7c605f62017-12-25 00:01:52 +02002223 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2224 // app that has MODIFY_PHONE_STATE permission.
2225 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2226 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002227 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002228 return BAD_VALUE;
2229 }
2230 if (!audio_is_output_device(device)) {
2231 return BAD_VALUE;
2232 }
2233
2234 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002235 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002236
Eric Laurent1fd372e2016-04-06 14:23:53 -07002237 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002238 stream, device, index);
2239
Eric Laurent28d09f02016-03-08 10:43:05 -08002240 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002241 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2242 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002243 continue;
2244 }
2245 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2246 }
Eric Laurente552edb2014-03-10 17:42:56 -07002247
Eric Laurent1fd372e2016-04-06 14:23:53 -07002248 // update volume on all outputs and streams matching the following:
2249 // - The requested stream (or a stream matching for volume control) is active on the output
2250 // - The device (or devices) selected by the strategy corresponding to this stream includes
2251 // the requested device
2252 // - For non default requested device, currently selected device on the output is either the
2253 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002254 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2255 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002256 status_t status = NO_ERROR;
2257 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002258 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2259 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002260 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002261 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002262 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002263 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002264 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 continue;
2266 }
Eric Laurent794fde22016-03-11 09:50:45 -08002267 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002268 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2269 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002270 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2271 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002272 continue;
2273 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002274 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002275 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002276 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002277 applyVolume = (curDevice & curStreamDevice) != 0;
2278 } else {
2279 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002280 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002281 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002282 // rescale index before applying to curStream as ranges may be different for
2283 // stream and curStream
2284 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002285 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002286 //FIXME: workaround for truncated touch sounds
2287 // delayed volume change for system stream to be removed when the problem is
2288 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002289 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002290 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002291 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002292 if (volStatus != NO_ERROR) {
2293 status = volStatus;
2294 }
2295 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002296 }
Eric Laurente552edb2014-03-10 17:42:56 -07002297 }
2298 return status;
2299}
2300
Eric Laurente0720872014-03-11 09:30:41 -07002301status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002302 int *index,
2303 audio_devices_t device)
2304{
2305 if (index == NULL) {
2306 return BAD_VALUE;
2307 }
2308 if (!audio_is_output_device(device)) {
2309 return BAD_VALUE;
2310 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002311 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002312 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002313 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002314 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2315 }
François Gaffiedfd74092015-03-19 12:10:59 +01002316 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002317
François Gaffied1ab2bd2015-12-02 18:20:06 +01002318 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002319 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2320 return NO_ERROR;
2321}
2322
Eric Laurent36829f92017-04-07 19:04:42 -07002323audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002324{
2325 // select one output among several suitable for global effects.
2326 // The priority is as follows:
2327 // 1: An offloaded output. If the effect ends up not being offloadable,
2328 // AudioFlinger will invalidate the track and the offloaded output
2329 // will be closed causing the effect to be moved to a PCM output.
2330 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002331 // 3: The primary output
2332 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002333
Eric Laurent3b73df72014-03-11 09:06:29 -07002334 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002335 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002336 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002337
Eric Laurent36829f92017-04-07 19:04:42 -07002338 if (outputs.size() == 0) {
2339 return AUDIO_IO_HANDLE_NONE;
2340 }
Eric Laurente552edb2014-03-10 17:42:56 -07002341
Eric Laurent36829f92017-04-07 19:04:42 -07002342 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2343 bool activeOnly = true;
2344
2345 while (output == AUDIO_IO_HANDLE_NONE) {
2346 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2347 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2348 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2349
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002350 for (audio_io_handle_t output : outputs) {
2351 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002352 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2353 continue;
2354 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002355 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2356 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002357 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002358 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002359 }
2360 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002361 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002362 }
2363 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002364 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002365 }
2366 }
2367 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2368 output = outputOffloaded;
2369 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2370 output = outputDeepBuffer;
2371 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2372 output = outputPrimary;
2373 } else {
2374 output = outputs[0];
2375 }
2376 activeOnly = false;
2377 }
2378
2379 if (output != mMusicEffectOutput) {
2380 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2381 mMusicEffectOutput = output;
2382 }
2383
2384 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002385 return output;
2386}
2387
Eric Laurent36829f92017-04-07 19:04:42 -07002388audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2389{
2390 return selectOutputForMusicEffects();
2391}
2392
Eric Laurente0720872014-03-11 09:30:41 -07002393status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002394 audio_io_handle_t io,
2395 uint32_t strategy,
2396 int session,
2397 int id)
2398{
2399 ssize_t index = mOutputs.indexOfKey(io);
2400 if (index < 0) {
2401 index = mInputs.indexOfKey(io);
2402 if (index < 0) {
2403 ALOGW("registerEffect() unknown io %d", io);
2404 return INVALID_OPERATION;
2405 }
2406 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002407 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002408}
2409
Eric Laurentc75307b2015-03-17 15:29:32 -07002410bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2411{
Eric Laurent28d09f02016-03-08 10:43:05 -08002412 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002413 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2414 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002415 continue;
2416 }
2417 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2418 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002419 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002420}
2421
2422bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2423{
2424 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2425}
2426
Eric Laurente0720872014-03-11 09:30:41 -07002427bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002428{
2429 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002430 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002431 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002432 return true;
2433 }
2434 }
2435 return false;
2436}
2437
Eric Laurent275e8e92014-11-30 15:14:47 -08002438// Register a list of custom mixes with their attributes and format.
2439// When a mix is registered, corresponding input and output profiles are
2440// added to the remote submix hw module. The profile contains only the
2441// parameters (sampling rate, format...) specified by the mix.
2442// The corresponding input remote submix device is also connected.
2443//
2444// When a remote submix device is connected, the address is checked to select the
2445// appropriate profile and the corresponding input or output stream is opened.
2446//
2447// When capture starts, getInputForAttr() will:
2448// - 1 look for a mix matching the address passed in attribtutes tags if any
2449// - 2 if none found, getDeviceForInputSource() will:
2450// - 2.1 look for a mix matching the attributes source
2451// - 2.2 if none found, default to device selection by policy rules
2452// At this time, the corresponding output remote submix device is also connected
2453// and active playback use cases can be transferred to this mix if needed when reconnecting
2454// after AudioTracks are invalidated
2455//
2456// When playback starts, getOutputForAttr() will:
2457// - 1 look for a mix matching the address passed in attribtutes tags if any
2458// - 2 if none found, look for a mix matching the attributes usage
2459// - 3 if none found, default to device and output selection by policy rules.
2460
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002461status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002462{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002463 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2464 status_t res = NO_ERROR;
2465
2466 sp<HwModule> rSubmixModule;
2467 // examine each mix's route type
2468 for (size_t i = 0; i < mixes.size(); i++) {
2469 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2470 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2471 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002472 break;
2473 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002474 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002475 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002477 rSubmixModule = mHwModules.getModuleFromName(
2478 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2479 if (rSubmixModule == 0) {
2480 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2481 i);
2482 res = INVALID_OPERATION;
2483 break;
2484 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002486
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002487 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002488
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002489 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002490 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002491 res = INVALID_OPERATION;
2492 break;
2493 }
2494 audio_config_t outputConfig = mixes[i].mFormat;
2495 audio_config_t inputConfig = mixes[i].mFormat;
2496 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2497 // stereo and let audio flinger do the channel conversion if needed.
2498 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2499 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2500 rSubmixModule->addOutputProfile(address, &outputConfig,
2501 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2502 rSubmixModule->addInputProfile(address, &inputConfig,
2503 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002504
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2506 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2507 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2508 address.string(), "remote-submix");
2509 } else {
2510 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2511 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2512 address.string(), "remote-submix");
2513 }
2514 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002515 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002516 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002517 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2518 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002519
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002520 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002521 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2522 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2523 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2524 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2525 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2526 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002527 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2528 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2530 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002531 } else {
2532 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002533 }
2534 break;
2535 }
2536 }
2537
2538 if (res != NO_ERROR) {
2539 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002540 i, device, address.string());
2541 res = INVALID_OPERATION;
2542 break;
2543 } else if (!foundOutput) {
2544 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2545 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002546 res = INVALID_OPERATION;
2547 break;
2548 }
Eric Laurentc722f302014-12-10 11:21:49 -08002549 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002550 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 if (res != NO_ERROR) {
2552 unregisterPolicyMixes(mixes);
2553 }
2554 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002555}
2556
2557status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2558{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002559 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002560 status_t res = NO_ERROR;
2561 sp<HwModule> rSubmixModule;
2562 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002563 for (const auto& mix : mixes) {
2564 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002565
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002566 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002567 rSubmixModule = mHwModules.getModuleFromName(
2568 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2569 if (rSubmixModule == 0) {
2570 res = INVALID_OPERATION;
2571 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002572 }
2573 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002574
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002575 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002576
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002577 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2578 res = INVALID_OPERATION;
2579 continue;
2580 }
2581
2582 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2584 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2585 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2586 address.string(), "remote-submix");
2587 }
2588 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2589 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2590 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2591 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2592 address.string(), "remote-submix");
2593 }
2594 rSubmixModule->removeOutputProfile(address);
2595 rSubmixModule->removeInputProfile(address);
2596
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002597 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2598 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002599 res = INVALID_OPERATION;
2600 continue;
2601 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002602 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002603 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002604 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002605}
2606
Eric Laurente552edb2014-03-10 17:42:56 -07002607
Eric Laurente0720872014-03-11 09:30:41 -07002608status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002609{
Eric Laurente552edb2014-03-10 17:42:56 -07002610 String8 result;
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002611 result.appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2612 result.appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002613 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002614 std::string stateLiteral;
2615 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002616 result.appendFormat(" Phone state: %s\n", stateLiteral.c_str());
2617 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2618 "communications", "media", "record", "dock", "system",
2619 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2620 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2621 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
2622 result.appendFormat(" Force use for %s: %d\n",
2623 forceUses[i], mEngine->getForceUse(i));
2624 }
2625 result.appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2626 result.appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2627 result.appendFormat(" Config source: %s\n", getConfig().getSource().c_str());
François Gaffie2110e042015-03-24 08:41:51 +01002628 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002629
François Gaffie112b0af2015-11-19 16:13:25 +01002630 mAvailableOutputDevices.dump(fd, String8("Available output"));
2631 mAvailableInputDevices.dump(fd, String8("Available input"));
Mikhail Naganovd4120142017-12-06 15:49:22 -08002632 mHwModulesAll.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002633 mOutputs.dump(fd);
2634 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002635 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002636 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002637 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002638 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002639
2640 return NO_ERROR;
2641}
2642
2643// This function checks for the parameters which can be offloaded.
2644// This can be enhanced depending on the capability of the DSP and policy
2645// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002646bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002647{
2648 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002649 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002650 offloadInfo.sample_rate, offloadInfo.channel_mask,
2651 offloadInfo.format,
2652 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2653 offloadInfo.has_video);
2654
Andy Hung2ddee192015-12-18 17:34:44 -08002655 if (mMasterMono) {
2656 return false; // no offloading if mono is set.
2657 }
2658
Eric Laurente552edb2014-03-10 17:42:56 -07002659 // Check if offload has been disabled
2660 char propValue[PROPERTY_VALUE_MAX];
2661 if (property_get("audio.offload.disable", propValue, "0")) {
2662 if (atoi(propValue) != 0) {
2663 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2664 return false;
2665 }
2666 }
2667
2668 // Check if stream type is music, then only allow offload as of now.
2669 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2670 {
2671 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2672 return false;
2673 }
2674
2675 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002676 const bool allowOffloadWithVideo =
2677 property_get_bool("audio.offload.video", false /* default_value */);
2678 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002679 ALOGV("isOffloadSupported: has_video == true, returning false");
2680 return false;
2681 }
2682
2683 //If duration is less than minimum value defined in property, return false
2684 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2685 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2686 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2687 return false;
2688 }
2689 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2690 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2691 return false;
2692 }
2693
2694 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2695 // creating an offloaded track and tearing it down immediately after start when audioflinger
2696 // detects there is an active non offloadable effect.
2697 // FIXME: We should check the audio session here but we do not have it in this context.
2698 // This may prevent offloading in rare situations where effects are left active by apps
2699 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002700 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002701 return false;
2702 }
2703
2704 // See if there is a profile to support this.
2705 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002706 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002707 offloadInfo.sample_rate,
2708 offloadInfo.format,
2709 offloadInfo.channel_mask,
2710 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002711 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2712 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002713}
2714
Eric Laurent6a94d692014-05-20 11:18:06 -07002715status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2716 audio_port_type_t type,
2717 unsigned int *num_ports,
2718 struct audio_port *ports,
2719 unsigned int *generation)
2720{
2721 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2722 generation == NULL) {
2723 return BAD_VALUE;
2724 }
2725 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2726 if (ports == NULL) {
2727 *num_ports = 0;
2728 }
2729
2730 size_t portsWritten = 0;
2731 size_t portsMax = *num_ports;
2732 *num_ports = 0;
2733 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002734 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2735 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002736 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002737 for (const auto& dev : mAvailableOutputDevices) {
2738 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002739 continue;
2740 }
2741 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002742 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002743 }
2744 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002745 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002746 }
2747 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002748 for (const auto& dev : mAvailableInputDevices) {
2749 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002750 continue;
2751 }
2752 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002753 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002754 }
2755 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002756 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 }
2758 }
2759 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2760 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2761 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2762 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2763 }
2764 *num_ports += mInputs.size();
2765 }
2766 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002767 size_t numOutputs = 0;
2768 for (size_t i = 0; i < mOutputs.size(); i++) {
2769 if (!mOutputs[i]->isDuplicated()) {
2770 numOutputs++;
2771 if (portsWritten < portsMax) {
2772 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2773 }
2774 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002775 }
Eric Laurent84c70242014-06-23 08:46:27 -07002776 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002777 }
2778 }
2779 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002780 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002781 return NO_ERROR;
2782}
2783
Eric Laurent99fcae42018-05-17 16:59:18 -07002784status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002785{
Eric Laurent99fcae42018-05-17 16:59:18 -07002786 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2787 return BAD_VALUE;
2788 }
2789 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2790 if (dev != 0) {
2791 dev->toAudioPort(port);
2792 return NO_ERROR;
2793 }
2794 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2795 if (dev != 0) {
2796 dev->toAudioPort(port);
2797 return NO_ERROR;
2798 }
2799 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2800 if (out != 0) {
2801 out->toAudioPort(port);
2802 return NO_ERROR;
2803 }
2804 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2805 if (in != 0) {
2806 in->toAudioPort(port);
2807 return NO_ERROR;
2808 }
2809 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002810}
2811
Eric Laurent6a94d692014-05-20 11:18:06 -07002812status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2813 audio_patch_handle_t *handle,
2814 uid_t uid)
2815{
2816 ALOGV("createAudioPatch()");
2817
2818 if (handle == NULL || patch == NULL) {
2819 return BAD_VALUE;
2820 }
2821 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2822
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002823 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002824 return BAD_VALUE;
2825 }
2826 // only one source per audio patch supported for now
2827 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 return INVALID_OPERATION;
2829 }
Eric Laurent874c42872014-08-08 15:13:39 -07002830
2831 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002832 return INVALID_OPERATION;
2833 }
Eric Laurent874c42872014-08-08 15:13:39 -07002834 for (size_t i = 0; i < patch->num_sinks; i++) {
2835 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2836 return INVALID_OPERATION;
2837 }
2838 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002839
2840 sp<AudioPatch> patchDesc;
2841 ssize_t index = mAudioPatches.indexOfKey(*handle);
2842
Eric Laurent6a94d692014-05-20 11:18:06 -07002843 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2844 patch->sources[0].role,
2845 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002846#if LOG_NDEBUG == 0
2847 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002848 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002849 patch->sinks[i].role,
2850 patch->sinks[i].type);
2851 }
2852#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002853
2854 if (index >= 0) {
2855 patchDesc = mAudioPatches.valueAt(index);
2856 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2857 mUidCached, patchDesc->mUid, uid);
2858 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2859 return INVALID_OPERATION;
2860 }
2861 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002862 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 }
2864
2865 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002866 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002867 if (outputDesc == NULL) {
2868 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2869 return BAD_VALUE;
2870 }
Eric Laurent84c70242014-06-23 08:46:27 -07002871 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2872 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002873 if (patchDesc != 0) {
2874 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2875 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2876 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2877 return BAD_VALUE;
2878 }
2879 }
Eric Laurent874c42872014-08-08 15:13:39 -07002880 DeviceVector devices;
2881 for (size_t i = 0; i < patch->num_sinks; i++) {
2882 // Only support mix to devices connection
2883 // TODO add support for mix to mix connection
2884 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2885 ALOGV("createAudioPatch() source mix but sink is not a device");
2886 return INVALID_OPERATION;
2887 }
2888 sp<DeviceDescriptor> devDesc =
2889 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2890 if (devDesc == 0) {
2891 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2892 return BAD_VALUE;
2893 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002894
François Gaffie53615e22015-03-19 09:24:12 +01002895 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002896 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002897 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002898 NULL, // updatedSamplingRate
2899 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002900 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002901 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002902 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002903 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002904 ALOGV("createAudioPatch() profile not supported for device %08x",
2905 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002906 return INVALID_OPERATION;
2907 }
2908 devices.add(devDesc);
2909 }
2910 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002911 return INVALID_OPERATION;
2912 }
Eric Laurent874c42872014-08-08 15:13:39 -07002913
Eric Laurent6a94d692014-05-20 11:18:06 -07002914 // TODO: reconfigure output format and channels here
2915 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002916 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002917 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002918 index = mAudioPatches.indexOfKey(*handle);
2919 if (index >= 0) {
2920 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2921 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2922 }
2923 patchDesc = mAudioPatches.valueAt(index);
2924 patchDesc->mUid = uid;
2925 ALOGV("createAudioPatch() success");
2926 } else {
2927 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2928 return INVALID_OPERATION;
2929 }
2930 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2931 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2932 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002933 // only one sink supported when connecting an input device to a mix
2934 if (patch->num_sinks > 1) {
2935 return INVALID_OPERATION;
2936 }
François Gaffie53615e22015-03-19 09:24:12 +01002937 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002938 if (inputDesc == NULL) {
2939 return BAD_VALUE;
2940 }
2941 if (patchDesc != 0) {
2942 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2943 return BAD_VALUE;
2944 }
2945 }
2946 sp<DeviceDescriptor> devDesc =
2947 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2948 if (devDesc == 0) {
2949 return BAD_VALUE;
2950 }
2951
François Gaffie53615e22015-03-19 09:24:12 +01002952 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002953 devDesc->mAddress,
2954 patch->sinks[0].sample_rate,
2955 NULL, /*updatedSampleRate*/
2956 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002957 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002958 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002959 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002960 // FIXME for the parameter type,
2961 // and the NONE
2962 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002963 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 return INVALID_OPERATION;
2965 }
2966 // TODO: reconfigure output format and channels here
2967 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002968 devDesc->type(), inputDesc->mIoHandle);
2969 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002970 index = mAudioPatches.indexOfKey(*handle);
2971 if (index >= 0) {
2972 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2973 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2974 }
2975 patchDesc = mAudioPatches.valueAt(index);
2976 patchDesc->mUid = uid;
2977 ALOGV("createAudioPatch() success");
2978 } else {
2979 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2980 return INVALID_OPERATION;
2981 }
2982 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2983 // device to device connection
2984 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002985 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002986 return BAD_VALUE;
2987 }
2988 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002989 sp<DeviceDescriptor> srcDeviceDesc =
2990 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002991 if (srcDeviceDesc == 0) {
2992 return BAD_VALUE;
2993 }
Eric Laurent874c42872014-08-08 15:13:39 -07002994
Eric Laurent6a94d692014-05-20 11:18:06 -07002995 //update source and sink with our own data as the data passed in the patch may
2996 // be incomplete.
2997 struct audio_patch newPatch = *patch;
2998 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002999
Eric Laurent874c42872014-08-08 15:13:39 -07003000 for (size_t i = 0; i < patch->num_sinks; i++) {
3001 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3002 ALOGV("createAudioPatch() source device but one sink is not a device");
3003 return INVALID_OPERATION;
3004 }
3005
3006 sp<DeviceDescriptor> sinkDeviceDesc =
3007 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3008 if (sinkDeviceDesc == 0) {
3009 return BAD_VALUE;
3010 }
3011 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3012
Eric Laurent3bcf8592015-04-03 12:13:24 -07003013 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003014 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003015 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003016 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003017 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003018 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003019 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003020 return INVALID_OPERATION;
3021 }
Eric Laurent874c42872014-08-08 15:13:39 -07003022 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003023 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003024 // if the sink device is reachable via an opened output stream, request to go via
3025 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003026 audio_io_handle_t output = selectOutput(outputs,
3027 AUDIO_OUTPUT_FLAG_NONE,
3028 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003029 if (output != AUDIO_IO_HANDLE_NONE) {
3030 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3031 if (outputDesc->isDuplicated()) {
3032 return INVALID_OPERATION;
3033 }
3034 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003035 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003036 newPatch.num_sources = 2;
3037 }
Eric Laurent83b88082014-06-20 18:31:16 -07003038 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003039 }
3040 // TODO: check from routing capabilities in config file and other conflicting patches
3041
Mikhail Naganovdc769682018-05-04 15:34:08 -07003042 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3043 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3045 status);
3046 return INVALID_OPERATION;
3047 }
3048 } else {
3049 return BAD_VALUE;
3050 }
3051 } else {
3052 return BAD_VALUE;
3053 }
3054 return NO_ERROR;
3055}
3056
3057status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3058 uid_t uid)
3059{
3060 ALOGV("releaseAudioPatch() patch %d", handle);
3061
3062 ssize_t index = mAudioPatches.indexOfKey(handle);
3063
3064 if (index < 0) {
3065 return BAD_VALUE;
3066 }
3067 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3068 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3069 mUidCached, patchDesc->mUid, uid);
3070 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3071 return INVALID_OPERATION;
3072 }
3073
3074 struct audio_patch *patch = &patchDesc->mPatch;
3075 patchDesc->mUid = mUidCached;
3076 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003077 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003078 if (outputDesc == NULL) {
3079 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3080 return BAD_VALUE;
3081 }
3082
Eric Laurentc75307b2015-03-17 15:29:32 -07003083 setOutputDevice(outputDesc,
3084 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003085 true,
3086 0,
3087 NULL);
3088 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3089 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003090 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003091 if (inputDesc == NULL) {
3092 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3093 return BAD_VALUE;
3094 }
3095 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003096 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003097 true,
3098 NULL);
3099 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003100 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3101 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3102 status, patchDesc->mAfPatchHandle);
3103 removeAudioPatch(patchDesc->mHandle);
3104 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003105 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003106 } else {
3107 return BAD_VALUE;
3108 }
3109 } else {
3110 return BAD_VALUE;
3111 }
3112 return NO_ERROR;
3113}
3114
3115status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3116 struct audio_patch *patches,
3117 unsigned int *generation)
3118{
François Gaffie53615e22015-03-19 09:24:12 +01003119 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003120 return BAD_VALUE;
3121 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003122 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003123 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003124}
3125
Eric Laurente1715a42014-05-20 11:30:42 -07003126status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003127{
Eric Laurente1715a42014-05-20 11:30:42 -07003128 ALOGV("setAudioPortConfig()");
3129
3130 if (config == NULL) {
3131 return BAD_VALUE;
3132 }
3133 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3134 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003135 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3136 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003137 }
3138
Eric Laurenta121f902014-06-03 13:32:54 -07003139 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003140 if (config->type == AUDIO_PORT_TYPE_MIX) {
3141 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003142 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003143 if (outputDesc == NULL) {
3144 return BAD_VALUE;
3145 }
Eric Laurent84c70242014-06-23 08:46:27 -07003146 ALOG_ASSERT(!outputDesc->isDuplicated(),
3147 "setAudioPortConfig() called on duplicated output %d",
3148 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003149 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003150 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003151 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003152 if (inputDesc == NULL) {
3153 return BAD_VALUE;
3154 }
Eric Laurenta121f902014-06-03 13:32:54 -07003155 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003156 } else {
3157 return BAD_VALUE;
3158 }
3159 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3160 sp<DeviceDescriptor> deviceDesc;
3161 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3162 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3163 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3164 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3165 } else {
3166 return BAD_VALUE;
3167 }
3168 if (deviceDesc == NULL) {
3169 return BAD_VALUE;
3170 }
Eric Laurenta121f902014-06-03 13:32:54 -07003171 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003172 } else {
3173 return BAD_VALUE;
3174 }
3175
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003176 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003177 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3178 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003179 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003180 audioPortConfig->toAudioPortConfig(&newConfig, config);
3181 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003182 }
Eric Laurenta121f902014-06-03 13:32:54 -07003183 if (status != NO_ERROR) {
3184 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003185 }
Eric Laurente1715a42014-05-20 11:30:42 -07003186
3187 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003188}
3189
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003190void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3191{
Eric Laurentd60560a2015-04-10 11:31:20 -07003192 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003193 clearAudioPatches(uid);
3194 clearSessionRoutes(uid);
3195}
3196
Eric Laurent6a94d692014-05-20 11:18:06 -07003197void AudioPolicyManager::clearAudioPatches(uid_t uid)
3198{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003199 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003200 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3201 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003202 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003203 }
3204 }
3205}
3206
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003207void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3208 audio_io_handle_t ouptutToSkip)
3209{
3210 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3211 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3212 for (size_t j = 0; j < mOutputs.size(); j++) {
3213 if (mOutputs.keyAt(j) == ouptutToSkip) {
3214 continue;
3215 }
3216 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3217 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3218 continue;
3219 }
3220 // If the default device for this strategy is on another output mix,
3221 // invalidate all tracks in this strategy to force re connection.
3222 // Otherwise select new device on the output mix.
3223 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003224 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003225 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3226 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3227 }
3228 }
3229 } else {
3230 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3231 setOutputDevice(outputDesc, newDevice, false);
3232 }
3233 }
3234}
3235
3236void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3237{
3238 // remove output routes associated with this uid
3239 SortedVector<routing_strategy> affectedStrategies;
3240 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3241 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3242 if (route->mUid == uid) {
3243 mOutputRoutes.removeItemsAt(i);
3244 if (route->mDeviceDescriptor != 0) {
3245 affectedStrategies.add(getStrategy(route->mStreamType));
3246 }
3247 }
3248 }
3249 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003250 for (const auto& strategy : affectedStrategies) {
3251 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003252 }
3253
3254 // remove input routes associated with this uid
3255 SortedVector<audio_source_t> affectedSources;
3256 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3257 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3258 if (route->mUid == uid) {
3259 mInputRoutes.removeItemsAt(i);
3260 if (route->mDeviceDescriptor != 0) {
3261 affectedSources.add(route->mSource);
3262 }
3263 }
3264 }
3265 // reroute inputs if necessary
3266 SortedVector<audio_io_handle_t> inputsToClose;
3267 for (size_t i = 0; i < mInputs.size(); i++) {
3268 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003269 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003270 inputsToClose.add(inputDesc->mIoHandle);
3271 }
3272 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003273 for (const auto& input : inputsToClose) {
3274 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003275 }
3276}
3277
Eric Laurentd60560a2015-04-10 11:31:20 -07003278void AudioPolicyManager::clearAudioSources(uid_t uid)
3279{
3280 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3281 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3282 if (sourceDesc->mUid == uid) {
3283 stopAudioSource(mAudioSources.keyAt(i));
3284 }
3285 }
3286}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003287
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003288status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3289 audio_io_handle_t *ioHandle,
3290 audio_devices_t *device)
3291{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003292 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3293 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003294 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003295
François Gaffiedf372692015-03-19 10:43:27 +01003296 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003297}
3298
Eric Laurentd60560a2015-04-10 11:31:20 -07003299status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3300 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003301 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003302 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003303{
Eric Laurentd60560a2015-04-10 11:31:20 -07003304 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3305 if (source == NULL || attributes == NULL || handle == NULL) {
3306 return BAD_VALUE;
3307 }
3308
Glenn Kasten559d4392016-03-29 13:42:57 -07003309 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003310
3311 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3312 source->type != AUDIO_PORT_TYPE_DEVICE) {
3313 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3314 return INVALID_OPERATION;
3315 }
3316
3317 sp<DeviceDescriptor> srcDeviceDesc =
3318 mAvailableInputDevices.getDevice(source->ext.device.type,
3319 String8(source->ext.device.address));
3320 if (srcDeviceDesc == 0) {
3321 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3322 return BAD_VALUE;
3323 }
3324 sp<AudioSourceDescriptor> sourceDesc =
3325 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3326
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003327 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003328 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3329 sourceDesc->mPatchDesc = patchDesc;
3330
3331 status_t status = connectAudioSource(sourceDesc);
3332 if (status == NO_ERROR) {
3333 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3334 *handle = sourceDesc->getHandle();
3335 }
3336 return status;
3337}
3338
3339status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3340{
3341 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3342
3343 // make sure we only have one patch per source.
3344 disconnectAudioSource(sourceDesc);
3345
3346 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003347 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003348 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3349
3350 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3351 sp<DeviceDescriptor> sinkDeviceDesc =
3352 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3353
3354 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003355
3356 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3357 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003358 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003359 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3360 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3361 // create patch between src device and output device
3362 // create Hwoutput and add to mHwOutputs
3363 } else {
3364 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3365 audio_io_handle_t output =
3366 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3367 if (output == AUDIO_IO_HANDLE_NONE) {
3368 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3369 return INVALID_OPERATION;
3370 }
3371 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3372 if (outputDesc->isDuplicated()) {
3373 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3374 return INVALID_OPERATION;
3375 }
Eric Laurent733ce942017-12-07 12:18:25 -08003376 status_t status = outputDesc->start();
3377 if (status != NO_ERROR) {
3378 return status;
3379 }
3380
Eric Laurentd60560a2015-04-10 11:31:20 -07003381 // create a special patch with no sink and two sources:
3382 // - the second source indicates to PatchPanel through which output mix this patch should
3383 // be connected as well as the stream type for volume control
3384 // - the sink is defined by whatever output device is currently selected for the output
3385 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003386 PatchBuilder patchBuilder;
3387 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3388 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003389 &afPatchHandle,
3390 0);
3391 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3392 status, afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003393 sourceDesc->mPatchDesc->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003394 if (status != NO_ERROR) {
3395 ALOGW("%s patch panel could not connect device patch, error %d",
3396 __FUNCTION__, status);
3397 return INVALID_OPERATION;
3398 }
3399 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003400 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003401
3402 if (status != NO_ERROR) {
3403 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3404 return status;
3405 }
3406 sourceDesc->mSwOutput = outputDesc;
3407 if (delayMs != 0) {
3408 usleep(delayMs * 1000);
3409 }
3410 }
3411
3412 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3413 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3414
3415 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003416}
3417
Glenn Kasten559d4392016-03-29 13:42:57 -07003418status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003419{
Eric Laurentd60560a2015-04-10 11:31:20 -07003420 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3421 ALOGV("%s handle %d", __FUNCTION__, handle);
3422 if (sourceDesc == 0) {
3423 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3424 return BAD_VALUE;
3425 }
3426 status_t status = disconnectAudioSource(sourceDesc);
3427
3428 mAudioSources.removeItem(handle);
3429 return status;
3430}
3431
Andy Hung2ddee192015-12-18 17:34:44 -08003432status_t AudioPolicyManager::setMasterMono(bool mono)
3433{
3434 if (mMasterMono == mono) {
3435 return NO_ERROR;
3436 }
3437 mMasterMono = mono;
3438 // if enabling mono we close all offloaded devices, which will invalidate the
3439 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3440 // for recreating the new AudioTrack as non-offloaded PCM.
3441 //
3442 // If disabling mono, we leave all tracks as is: we don't know which clients
3443 // and tracks are able to be recreated as offloaded. The next "song" should
3444 // play back offloaded.
3445 if (mMasterMono) {
3446 Vector<audio_io_handle_t> offloaded;
3447 for (size_t i = 0; i < mOutputs.size(); ++i) {
3448 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3449 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3450 offloaded.push(desc->mIoHandle);
3451 }
3452 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003453 for (const auto& handle : offloaded) {
3454 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003455 }
3456 }
3457 // update master mono for all remaining outputs
3458 for (size_t i = 0; i < mOutputs.size(); ++i) {
3459 updateMono(mOutputs.keyAt(i));
3460 }
3461 return NO_ERROR;
3462}
3463
3464status_t AudioPolicyManager::getMasterMono(bool *mono)
3465{
3466 *mono = mMasterMono;
3467 return NO_ERROR;
3468}
3469
Eric Laurentac9cef52017-06-09 15:46:26 -07003470float AudioPolicyManager::getStreamVolumeDB(
3471 audio_stream_type_t stream, int index, audio_devices_t device)
3472{
3473 return computeVolume(stream, index, device);
3474}
3475
jiabin81772902018-04-02 17:52:27 -07003476status_t AudioPolicyManager::getSupportedFormats(audio_io_handle_t ioHandle,
3477 FormatVector& formats) {
3478 if (ioHandle == AUDIO_IO_HANDLE_NONE) {
3479 return BAD_VALUE;
3480 }
3481 String8 reply;
3482 reply = mpClientInterface->getParameters(
3483 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
3484 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
3485 AudioParameter repliedParameters(reply);
3486 if (repliedParameters.get(
3487 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
3488 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
3489 return BAD_VALUE;
3490 }
3491 for (auto format : formatsFromString(reply.string())) {
3492 // Only AUDIO_FORMAT_AAC_LC will be used in Settings UI for all AAC formats.
3493 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3494 if (format == AAC_FORMATS[i]) {
3495 format = AUDIO_FORMAT_AAC_LC;
3496 break;
3497 }
3498 }
3499 bool exist = false;
3500 for (size_t i = 0; i < formats.size(); i++) {
3501 if (format == formats[i]) {
3502 exist = true;
3503 break;
3504 }
3505 }
3506 bool isSurroundFormat = false;
3507 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3508 if (SURROUND_FORMATS[i] == format) {
3509 isSurroundFormat = true;
3510 break;
3511 }
3512 }
3513 if (!exist && isSurroundFormat) {
3514 formats.add(format);
3515 }
3516 }
3517 return NO_ERROR;
3518}
3519
3520status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3521 audio_format_t *surroundFormats,
3522 bool *surroundFormatsEnabled,
3523 bool reported)
3524{
3525 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3526 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3527 return BAD_VALUE;
3528 }
3529 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
3530 *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
3531
3532 // Only return value if there is HDMI output.
3533 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3534 return INVALID_OPERATION;
3535 }
3536
3537 size_t formatsWritten = 0;
3538 size_t formatsMax = *numSurroundFormats;
3539 *numSurroundFormats = 0;
3540 FormatVector formats;
3541 if (reported) {
3542 // Only get surround formats which are reported by device.
3543 // First list already open outputs that can be routed to this device
3544 audio_devices_t device = AUDIO_DEVICE_OUT_HDMI;
3545 SortedVector<audio_io_handle_t> outputs;
3546 bool reportedFormatFound = false;
3547 status_t status;
3548 sp<SwAudioOutputDescriptor> desc;
3549 for (size_t i = 0; i < mOutputs.size(); i++) {
3550 desc = mOutputs.valueAt(i);
3551 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
3552 outputs.add(mOutputs.keyAt(i));
3553 }
3554 }
3555 // Open an output to query dynamic parameters.
Mikhail Naganov708e0382018-05-30 09:53:04 -07003556 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003557 AUDIO_DEVICE_OUT_HDMI);
3558 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3559 String8 address = hdmiOutputDevices[i]->mAddress;
3560 for (const auto& hwModule : mHwModules) {
3561 for (size_t i = 0; i < hwModule->getOutputProfiles().size(); i++) {
3562 sp<IOProfile> profile = hwModule->getOutputProfiles()[i];
3563 if (profile->supportDevice(AUDIO_DEVICE_OUT_HDMI) &&
3564 profile->supportDeviceAddress(address)) {
3565 size_t j;
3566 for (j = 0; j < outputs.size(); j++) {
3567 desc = mOutputs.valueFor(outputs.itemAt(j));
3568 if (!desc->isDuplicated() && desc->mProfile == profile) {
3569 break;
3570 }
3571 }
3572 if (j != outputs.size()) {
3573 status = getSupportedFormats(outputs.itemAt(j), formats);
3574 reportedFormatFound |= (status == NO_ERROR);
3575 continue;
3576 }
3577
3578 if (!profile->canOpenNewIo()) {
3579 ALOGW("Max Output number %u already opened for this profile %s",
3580 profile->maxOpenCount, profile->getTagName().c_str());
3581 continue;
3582 }
3583
3584 ALOGV("opening output for device %08x with params %s profile %p name %s",
3585 device, address.string(), profile.get(), profile->getName().string());
3586 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
3587 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3588 status_t status = desc->open(nullptr, device, address,
3589 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE,
3590 &output);
3591
3592 if (status == NO_ERROR) {
3593 status = getSupportedFormats(output, formats);
3594 reportedFormatFound |= (status == NO_ERROR);
3595 desc->close();
3596 output = AUDIO_IO_HANDLE_NONE;
3597 }
3598 }
3599 }
3600 }
3601 }
3602
3603 if (!reportedFormatFound) {
3604 return UNKNOWN_ERROR;
3605 }
3606 } else {
3607 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3608 formats.add(SURROUND_FORMATS[i]);
3609 }
3610 }
3611 for (size_t i = 0; i < formats.size(); i++) {
3612 if (formatsWritten < formatsMax) {
3613 surroundFormats[formatsWritten] = formats[i];
3614 bool formatEnabled = false;
3615 if (formats[i] == AUDIO_FORMAT_AAC_LC) {
3616 for (size_t j = 0; j < ARRAY_SIZE(AAC_FORMATS); j++) {
3617 formatEnabled =
3618 mSurroundFormats.find(AAC_FORMATS[i]) != mSurroundFormats.end();
3619 break;
3620 }
3621 } else {
3622 formatEnabled = mSurroundFormats.find(formats[i]) != mSurroundFormats.end();
3623 }
3624 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3625 }
3626 (*numSurroundFormats)++;
3627 }
3628 return NO_ERROR;
3629}
3630
3631status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3632{
3633 // Check if audio format is a surround formats.
3634 bool isSurroundFormat = false;
3635 for (size_t i = 0; i < ARRAY_SIZE(SURROUND_FORMATS); i++) {
3636 if (audioFormat == SURROUND_FORMATS[i]) {
3637 isSurroundFormat = true;
3638 break;
3639 }
3640 }
3641 if (!isSurroundFormat) {
3642 return BAD_VALUE;
3643 }
3644
3645 // Should only be called when MANUAL.
3646 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3647 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3648 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3649 return INVALID_OPERATION;
3650 }
3651
3652 if ((mSurroundFormats.find(audioFormat) != mSurroundFormats.end() && enabled)
3653 || (mSurroundFormats.find(audioFormat) == mSurroundFormats.end() && !enabled)) {
3654 return NO_ERROR;
3655 }
3656
3657 // The operation is valid only when there is HDMI output available.
3658 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3659 return INVALID_OPERATION;
3660 }
3661
3662 if (enabled) {
3663 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3664 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3665 mSurroundFormats.insert(AAC_FORMATS[i]);
3666 }
3667 } else {
3668 mSurroundFormats.insert(audioFormat);
3669 }
3670 } else {
3671 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3672 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3673 mSurroundFormats.erase(AAC_FORMATS[i]);
3674 }
3675 } else {
3676 mSurroundFormats.erase(audioFormat);
3677 }
3678 }
3679
3680 sp<SwAudioOutputDescriptor> outputDesc;
3681 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003682 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003683 AUDIO_DEVICE_OUT_HDMI);
3684 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3685 // Simulate reconnection to update enabled surround sound formats.
3686 String8 address = hdmiOutputDevices[i]->mAddress;
3687 String8 name = hdmiOutputDevices[i]->getName();
3688 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3689 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3690 address.c_str(),
3691 name.c_str());
3692 if (status != NO_ERROR) {
3693 continue;
3694 }
3695 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3696 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3697 address.c_str(),
3698 name.c_str());
3699 profileUpdated |= (status == NO_ERROR);
3700 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003701 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003702 AUDIO_DEVICE_IN_HDMI);
3703 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3704 // Simulate reconnection to update enabled surround sound formats.
3705 String8 address = hdmiInputDevices[i]->mAddress;
3706 String8 name = hdmiInputDevices[i]->getName();
3707 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3708 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3709 address.c_str(),
3710 name.c_str());
3711 if (status != NO_ERROR) {
3712 continue;
3713 }
3714 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3715 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3716 address.c_str(),
3717 name.c_str());
3718 profileUpdated |= (status == NO_ERROR);
3719 }
3720
3721 // Undo the surround formats change due to no audio profiles updated.
3722 if (!profileUpdated) {
3723 if (enabled) {
3724 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3725 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3726 mSurroundFormats.erase(AAC_FORMATS[i]);
3727 }
3728 } else {
3729 mSurroundFormats.erase(audioFormat);
3730 }
3731 } else {
3732 if (audioFormat == AUDIO_FORMAT_AAC_LC) {
3733 for (size_t i = 0; i < ARRAY_SIZE(AAC_FORMATS); i++) {
3734 mSurroundFormats.insert(AAC_FORMATS[i]);
3735 }
3736 } else {
3737 mSurroundFormats.insert(audioFormat);
3738 }
3739 }
3740 }
3741
3742 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3743}
3744
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003745void AudioPolicyManager::setRecordSilenced(uid_t uid, bool silenced)
3746{
3747 ALOGV("AudioPolicyManager:setRecordSilenced(uid:%d, silenced:%d)", uid, silenced);
3748
3749 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
3750 for (size_t i = 0; i < activeInputs.size(); i++) {
3751 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
3752 AudioSessionCollection activeSessions = activeDesc->getAudioSessions(true);
3753 for (size_t j = 0; j < activeSessions.size(); j++) {
3754 sp<AudioSession> activeSession = activeSessions.valueAt(j);
3755 if (activeSession->uid() == uid) {
3756 activeSession->setSilenced(silenced);
3757 }
3758 }
3759 }
3760}
3761
Eric Laurentd60560a2015-04-10 11:31:20 -07003762status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3763{
3764 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3765
3766 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3767 if (patchDesc == 0) {
3768 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3769 sourceDesc->mPatchDesc->mHandle);
3770 return BAD_VALUE;
3771 }
3772 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3773
Eric Laurent28d09f02016-03-08 10:43:05 -08003774 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003775 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3776 if (swOutputDesc != 0) {
Eric Laurent733ce942017-12-07 12:18:25 -08003777 status_t status = stopSource(swOutputDesc, stream, false);
3778 if (status == NO_ERROR) {
3779 swOutputDesc->stop();
3780 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003781 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3782 } else {
3783 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3784 if (hwOutputDesc != 0) {
3785 // release patch between src device and output device
3786 // close Hwoutput and remove from mHwOutputs
3787 } else {
3788 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3789 }
3790 }
3791 return NO_ERROR;
3792}
3793
3794sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3795 audio_io_handle_t output, routing_strategy strategy)
3796{
3797 sp<AudioSourceDescriptor> source;
3798 for (size_t i = 0; i < mAudioSources.size(); i++) {
3799 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3800 routing_strategy sourceStrategy =
3801 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3802 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3803 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3804 source = sourceDesc;
3805 break;
3806 }
3807 }
3808 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003809}
3810
Eric Laurente552edb2014-03-10 17:42:56 -07003811// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003812// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003813// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003814uint32_t AudioPolicyManager::nextAudioPortGeneration()
3815{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003816 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003817}
3818
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003819#ifdef USE_XML_AUDIO_POLICY_CONF
3820// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3821static const char *kConfigLocationList[] =
3822 {"/odm/etc", "/vendor/etc", "/system/etc"};
3823static const int kConfigLocationListSize =
3824 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3825
3826static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3827 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003828 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003829 status_t ret;
3830
Petri Gyntherf497f292018-04-17 18:46:10 -07003831 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3832 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3833 // A2DP offload supported but disabled: try to use special XML file
3834 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3835 }
3836 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3837
3838 for (const char* fileName : fileNames) {
3839 for (int i = 0; i < kConfigLocationListSize; i++) {
3840 PolicySerializer serializer;
3841 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3842 "%s/%s", kConfigLocationList[i], fileName);
3843 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3844 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003845 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003846 return ret;
3847 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003848 }
3849 }
3850 return ret;
3851}
3852#endif
3853
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003854AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3855 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003856 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003857 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003858 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003859 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003860 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003861#ifdef USE_XML_AUDIO_POLICY_CONF
3862 mVolumeCurves(new VolumeCurvesCollection()),
3863 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003864 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003865#else
3866 mVolumeCurves(new StreamDescriptorCollection()),
3867 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
3868 mDefaultOutputDevice),
3869#endif
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003870 mAudioPortGeneration(1),
3871 mBeaconMuteRefCount(0),
3872 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003873 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003874 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003875 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003876 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3877 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003878{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003879}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003880
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003881AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3882 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3883{
3884 loadConfig();
3885 initialize();
3886}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003887
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003888void AudioPolicyManager::loadConfig() {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003889#ifdef USE_XML_AUDIO_POLICY_CONF
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003890 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003891#else
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003892 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, getConfig()) != NO_ERROR)
3893 && (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, getConfig()) != NO_ERROR)) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003894#endif
3895 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003896 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003897 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003898}
3899
3900status_t AudioPolicyManager::initialize() {
3901 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003902
3903 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003904 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3905 if (!engineInstance) {
3906 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003907 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003908 }
3909 // Retrieve the Policy Manager Interface
3910 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3911 if (mEngine == NULL) {
3912 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003913 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003914 }
3915 mEngine->setObserver(this);
3916 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003917 if (status != NO_ERROR) {
3918 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3919 return status;
3920 }
François Gaffie2110e042015-03-24 08:41:51 +01003921
Eric Laurent3a4311c2014-03-17 12:00:47 -07003922 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003923 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3925 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003926 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003927 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003928 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3929 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003930 continue;
3931 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003932 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003933 // open all output streams needed to access attached devices
3934 // except for direct output streams that are only opened when they are actually
3935 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003936 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003937 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003938 if (!outProfile->canOpenNewIo()) {
3939 ALOGE("Invalid Output profile max open count %u for profile %s",
3940 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3941 continue;
3942 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003943 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003944 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003945 continue;
3946 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003947 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003948 mTtsOutputAvailable = true;
3949 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003950
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003951 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003952 continue;
3953 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003954 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003955 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3956 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003957 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003958 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003959 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003960 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003961 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003962 if ((profileType & outputDeviceTypes) == 0) {
3963 continue;
3964 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003965 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3966 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003967 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003968 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3969 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003970 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3971 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003972 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003973 status_t status = outputDesc->open(nullptr, profileType, address,
3974 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003975
3976 if (status != NO_ERROR) {
3977 ALOGW("Cannot open output stream for device %08x on hw module %s",
3978 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003979 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003980 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003981 for (const auto& dev : supportedDevices) {
3982 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003983 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003984 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003985 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003986 }
3987 }
3988 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003989 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003990 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 }
3992 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003993 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003994 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003995 true,
3996 0,
3997 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003998 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003999 }
Eric Laurente552edb2014-03-10 17:42:56 -07004000 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004001 // open input streams needed to access attached devices to validate
4002 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004003 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004004 if (!inProfile->canOpenNewIo()) {
4005 ALOGE("Invalid Input profile max open count %u for profile %s",
4006 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4007 continue;
4008 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004009 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004010 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004011 continue;
4012 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004013 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07004014 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004015 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
4016
Eric Laurentd78f1532014-09-16 16:38:20 -07004017 if ((profileType & inputDeviceTypes) == 0) {
4018 continue;
4019 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004020 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004021 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004022
Mikhail Naganov708e0382018-05-30 09:53:04 -07004023 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08004024 // the inputs vector must be of size >= 1, but we don't want to crash here
4025 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
4026 : String8("");
4027 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
4028 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
4029
Eric Laurentd78f1532014-09-16 16:38:20 -07004030 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004031 status_t status = inputDesc->open(nullptr,
4032 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08004033 address,
Eric Laurentfe231122017-11-17 17:48:06 -08004034 AUDIO_SOURCE_MIC,
4035 AUDIO_INPUT_FLAG_NONE,
4036 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07004037
4038 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004039 for (const auto& dev : inProfile->getSupportedDevices()) {
4040 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07004041 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07004042 if (index >= 0) {
4043 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
4044 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004045 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07004046 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07004047 }
Eric Laurentd78f1532014-09-16 16:38:20 -07004048 }
4049 }
Eric Laurentfe231122017-11-17 17:48:06 -08004050 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07004051 } else {
4052 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08004053 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08004054 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004056 }
4057 }
4058 // make sure all attached devices have been allocated a unique ID
4059 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004060 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004061 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004062 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
4063 continue;
4064 }
François Gaffie2110e042015-03-24 08:41:51 +01004065 // The device is now validated and can be appended to the available devices of the engine
4066 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
4067 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004068 i++;
4069 }
4070 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08004071 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01004072 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004073 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
4074 continue;
4075 }
François Gaffie2110e042015-03-24 08:41:51 +01004076 // The device is now validated and can be appended to the available devices of the engine
4077 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
4078 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004079 i++;
4080 }
4081 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004082 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01004083 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004084 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004085 }
jiabin9ff780e2018-03-19 18:19:52 -07004086 // If microphones address is empty, set it according to device type
4087 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4088 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
4089 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4090 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
4091 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4092 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
4093 }
4094 }
4095 }
Eric Laurente552edb2014-03-10 17:42:56 -07004096
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004097 if (mPrimaryOutput == 0) {
4098 ALOGE("Failed to open primary output");
4099 status = NO_INIT;
4100 }
Eric Laurente552edb2014-03-10 17:42:56 -07004101
4102 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004103 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004104}
4105
Eric Laurente0720872014-03-11 09:30:41 -07004106AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004107{
Eric Laurente552edb2014-03-10 17:42:56 -07004108 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004109 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004110 }
4111 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004112 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004113 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004114 mAvailableOutputDevices.clear();
4115 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004116 mOutputs.clear();
4117 mInputs.clear();
4118 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004119 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07004120 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004121}
4122
Eric Laurente0720872014-03-11 09:30:41 -07004123status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004124{
Eric Laurent87ffa392015-05-22 10:32:38 -07004125 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004126}
4127
Eric Laurente552edb2014-03-10 17:42:56 -07004128// ---
4129
Eric Laurent98e38192018-02-15 18:31:53 -08004130void AudioPolicyManager::addOutput(audio_io_handle_t output,
4131 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004132{
Eric Laurent1c333e22014-05-20 10:48:17 -07004133 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004134 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004135 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004136 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004138}
4139
François Gaffie53615e22015-03-19 09:24:12 +01004140void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4141{
4142 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004143 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004144}
4145
Eric Laurent98e38192018-02-15 18:31:53 -08004146void AudioPolicyManager::addInput(audio_io_handle_t input,
4147 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004148{
Eric Laurent1c333e22014-05-20 10:48:17 -07004149 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004150 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004151}
Eric Laurente552edb2014-03-10 17:42:56 -07004152
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004153void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004154 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004155 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004156 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004157 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004158 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004159 if (devDesc != 0) {
4160 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4161 desc->mIoHandle, address.string());
4162 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004163 }
4164}
4165
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004166status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004167 audio_policy_dev_state_t state,
4168 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004169 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004170{
François Gaffie53615e22015-03-19 09:24:12 +01004171 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004172 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004173
4174 if (audio_device_is_digital(device)) {
4175 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004176 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004177 }
Eric Laurente552edb2014-03-10 17:42:56 -07004178
Eric Laurent3b73df72014-03-11 09:06:29 -07004179 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004180 // first list already open outputs that can be routed to this device
4181 for (size_t i = 0; i < mOutputs.size(); i++) {
4182 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004183 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004184 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004185 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4186 outputs.add(mOutputs.keyAt(i));
4187 } else {
4188 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004189 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004190 }
Eric Laurente552edb2014-03-10 17:42:56 -07004191 }
4192 }
4193 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004194 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004195 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004196 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4197 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004198 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004199 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004200 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004201 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004202 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4203 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004204 }
Eric Laurente552edb2014-03-10 17:42:56 -07004205 }
4206 }
4207 }
4208
Eric Laurent7b279bb2015-12-14 10:18:23 -08004209 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004210
Eric Laurente552edb2014-03-10 17:42:56 -07004211 if (profiles.isEmpty() && outputs.isEmpty()) {
4212 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4213 return BAD_VALUE;
4214 }
4215
4216 // open outputs for matching profiles if needed. Direct outputs are also opened to
4217 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4218 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004219 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004220
4221 // nothing to do if one output is already opened for this profile
4222 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004223 for (j = 0; j < outputs.size(); j++) {
4224 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004225 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004226 // matching profile: save the sample rates, format and channel masks supported
4227 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004228 if (audio_device_is_digital(device)) {
4229 devDesc->importAudioPort(profile);
4230 }
Eric Laurente552edb2014-03-10 17:42:56 -07004231 break;
4232 }
4233 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004234 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 continue;
4236 }
4237
Eric Laurent3974e3b2017-12-07 17:58:43 -08004238 if (!profile->canOpenNewIo()) {
4239 ALOGW("Max Output number %u already opened for this profile %s",
4240 profile->maxOpenCount, profile->getTagName().c_str());
4241 continue;
4242 }
4243
Eric Laurent83efe1c2017-07-09 16:51:08 -07004244 ALOGV("opening output for device %08x with params %s profile %p name %s",
4245 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004246 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004247 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004248 status_t status = desc->open(nullptr, device, address,
4249 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004250
Eric Laurentfe231122017-11-17 17:48:06 -08004251 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004252 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004253 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004254 char *param = audio_device_address_to_parameter(device, address);
4255 mpClientInterface->setParameters(output, String8(param));
4256 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004257 }
Phil Burk00eeb322016-03-31 12:41:00 -07004258 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004259 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004260 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004261 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004262 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004263 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004264 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004265 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004266 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4267 profile->pickAudioProfile(
4268 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 config.offload_info.sample_rate = config.sample_rate;
4270 config.offload_info.channel_mask = config.channel_mask;
4271 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004272
4273 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4274 AUDIO_OUTPUT_FLAG_NONE, &output);
4275 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004276 output = AUDIO_IO_HANDLE_NONE;
4277 }
Eric Laurentd4692962014-05-05 18:13:44 -07004278 }
4279
Eric Laurentcf2c0212014-07-25 16:20:43 -07004280 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004281 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004282 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004283 sp<AudioPolicyMix> policyMix;
4284 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004285 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4286 address.string());
4287 }
François Gaffie036e1e92015-03-19 10:16:24 +01004288 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004289 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004290
Eric Laurent87ffa392015-05-22 10:32:38 -07004291 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4292 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004293 // no duplicated output for direct outputs and
4294 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004295 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004296
Eric Laurentd4692962014-05-05 18:13:44 -07004297 //TODO: configure audio effect output stage here
4298
4299 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004300 sp<SwAudioOutputDescriptor> dupOutputDesc =
4301 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4302 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4303 &duplicatedOutput);
4304 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004305 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004306 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004307 } else {
4308 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004309 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004310 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004311 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004313 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004314 }
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004317 } else {
4318 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004319 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004320 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004321 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004322 profiles.removeAt(profile_index);
4323 profile_index--;
4324 } else {
4325 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004326 // Load digital format info only for digital devices
4327 if (audio_device_is_digital(device)) {
4328 devDesc->importAudioPort(profile);
4329 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004330
François Gaffie53615e22015-03-19 09:24:12 +01004331 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004332 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4333 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004334 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004335 NULL/*patch handle*/, address.string());
4336 }
Eric Laurente552edb2014-03-10 17:42:56 -07004337 ALOGV("checkOutputsForDevice(): adding output %d", output);
4338 }
4339 }
4340
4341 if (profiles.isEmpty()) {
4342 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4343 return BAD_VALUE;
4344 }
Eric Laurentd4692962014-05-05 18:13:44 -07004345 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004346 // check if one opened output is not needed any more after disconnecting one device
4347 for (size_t i = 0; i < mOutputs.size(); i++) {
4348 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004349 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004350 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004351 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004352 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004353 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004354 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004355 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4356 mOutputs.keyAt(i));
4357 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004358 }
Eric Laurente552edb2014-03-10 17:42:56 -07004359 }
4360 }
Eric Laurentd4692962014-05-05 18:13:44 -07004361 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004362 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004363 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4364 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004365 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004366 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004367 "clearing direct output profile %zu on module %s",
4368 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004369 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004370 }
4371 }
4372 }
4373 }
4374 return NO_ERROR;
4375}
4376
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004377status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004378 audio_policy_dev_state_t state,
4379 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004380 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004381{
Paul McLean9080a4c2015-06-18 08:24:02 -07004382 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004383 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004384
4385 if (audio_device_is_digital(device)) {
4386 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004387 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004388 }
4389
Eric Laurentd4692962014-05-05 18:13:44 -07004390 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4391 // first list already open inputs that can be routed to this device
4392 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4393 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004394 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004395 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4396 inputs.add(mInputs.keyAt(input_index));
4397 }
4398 }
4399
4400 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004401 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004402 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004403 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004404 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004405 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004406 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004407
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004408 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004409 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004410 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004411 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004412 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4413 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004414 }
Eric Laurentd4692962014-05-05 18:13:44 -07004415 }
4416 }
4417 }
4418
4419 if (profiles.isEmpty() && inputs.isEmpty()) {
4420 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4421 return BAD_VALUE;
4422 }
4423
4424 // open inputs for matching profiles if needed. Direct inputs are also opened to
4425 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4426 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4427
Eric Laurent1c333e22014-05-20 10:48:17 -07004428 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004429
Eric Laurentd4692962014-05-05 18:13:44 -07004430 // nothing to do if one input is already opened for this profile
4431 size_t input_index;
4432 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4433 desc = mInputs.valueAt(input_index);
4434 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004435 if (audio_device_is_digital(device)) {
4436 devDesc->importAudioPort(profile);
4437 }
Eric Laurentd4692962014-05-05 18:13:44 -07004438 break;
4439 }
4440 }
4441 if (input_index != mInputs.size()) {
4442 continue;
4443 }
4444
Eric Laurent3974e3b2017-12-07 17:58:43 -08004445 if (!profile->canOpenNewIo()) {
4446 ALOGW("Max Input number %u already opened for this profile %s",
4447 profile->maxOpenCount, profile->getTagName().c_str());
4448 continue;
4449 }
4450
Eric Laurentfe231122017-11-17 17:48:06 -08004451 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004452 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004453 status_t status = desc->open(nullptr,
4454 device,
4455 address,
4456 AUDIO_SOURCE_MIC,
4457 AUDIO_INPUT_FLAG_NONE,
4458 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004459
Eric Laurentcf2c0212014-07-25 16:20:43 -07004460 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004461 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004462 char *param = audio_device_address_to_parameter(device, address);
4463 mpClientInterface->setParameters(input, String8(param));
4464 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004465 }
Phil Burk00eeb322016-03-31 12:41:00 -07004466 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004467 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004468 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004469 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004470 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004471 }
4472
4473 if (input != 0) {
4474 addInput(input, desc);
4475 }
4476 } // endif input != 0
4477
Eric Laurentcf2c0212014-07-25 16:20:43 -07004478 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004479 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004480 profiles.removeAt(profile_index);
4481 profile_index--;
4482 } else {
4483 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004484 if (audio_device_is_digital(device)) {
4485 devDesc->importAudioPort(profile);
4486 }
Eric Laurentd4692962014-05-05 18:13:44 -07004487 ALOGV("checkInputsForDevice(): adding input %d", input);
4488 }
4489 } // end scan profiles
4490
4491 if (profiles.isEmpty()) {
4492 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4493 return BAD_VALUE;
4494 }
4495 } else {
4496 // Disconnect
4497 // check if one opened input is not needed any more after disconnecting one device
4498 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4499 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004500 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004501 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4502 mInputs.keyAt(input_index));
4503 inputs.add(mInputs.keyAt(input_index));
4504 }
4505 }
4506 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004507 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004508 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004509 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004510 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004511 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004512 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004513 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4514 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004515 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004516 }
4517 }
4518 }
4519 } // end disconnect
4520
4521 return NO_ERROR;
4522}
4523
4524
Eric Laurente0720872014-03-11 09:30:41 -07004525void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004526{
4527 ALOGV("closeOutput(%d)", output);
4528
Eric Laurentc75307b2015-03-17 15:29:32 -07004529 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004530 if (outputDesc == NULL) {
4531 ALOGW("closeOutput() unknown output %d", output);
4532 return;
4533 }
François Gaffie036e1e92015-03-19 10:16:24 +01004534 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004535
Eric Laurente552edb2014-03-10 17:42:56 -07004536 // look for duplicated outputs connected to the output being removed.
4537 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004538 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004539 if (dupOutputDesc->isDuplicated() &&
4540 (dupOutputDesc->mOutput1 == outputDesc ||
4541 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004542 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004543 if (dupOutputDesc->mOutput1 == outputDesc) {
4544 outputDesc2 = dupOutputDesc->mOutput2;
4545 } else {
4546 outputDesc2 = dupOutputDesc->mOutput1;
4547 }
4548 // As all active tracks on duplicated output will be deleted,
4549 // and as they were also referenced on the other output, the reference
4550 // count for their stream type must be adjusted accordingly on
4551 // the other output.
Eric Laurent733ce942017-12-07 12:18:25 -08004552 bool wasActive = outputDesc2->isActive();
Eric Laurent3b73df72014-03-11 09:06:29 -07004553 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004554 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004555 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004556 }
Eric Laurent733ce942017-12-07 12:18:25 -08004557 // stop() will be a no op if the output is still active but is needed in case all
4558 // active streams refcounts where cleared above
4559 if (wasActive) {
4560 outputDesc2->stop();
4561 }
Eric Laurente552edb2014-03-10 17:42:56 -07004562 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4563 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4564
4565 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004566 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004567 }
4568 }
4569
Eric Laurent05b90f82014-08-27 15:32:29 -07004570 nextAudioPortGeneration();
4571
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004572 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004573 if (index >= 0) {
4574 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004575 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004576 mAudioPatches.removeItemsAt(index);
4577 mpClientInterface->onAudioPatchListUpdate();
4578 }
4579
Eric Laurentfe231122017-11-17 17:48:06 -08004580 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004581
François Gaffie53615e22015-03-19 09:24:12 +01004582 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004583 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004584}
4585
4586void AudioPolicyManager::closeInput(audio_io_handle_t input)
4587{
4588 ALOGV("closeInput(%d)", input);
4589
4590 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4591 if (inputDesc == NULL) {
4592 ALOGW("closeInput() unknown input %d", input);
4593 return;
4594 }
4595
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004597
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004598 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004599 if (index >= 0) {
4600 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004601 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004602 mAudioPatches.removeItemsAt(index);
4603 mpClientInterface->onAudioPatchListUpdate();
4604 }
4605
Eric Laurentfe231122017-11-17 17:48:06 -08004606 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004607 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004608}
4609
Eric Laurentc75307b2015-03-17 15:29:32 -07004610SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4611 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004612 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004613{
4614 SortedVector<audio_io_handle_t> outputs;
4615
4616 ALOGVV("getOutputsForDevice() device %04x", device);
4617 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004618 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004619 i, openOutputs.valueAt(i)->isDuplicated(),
4620 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004621 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4622 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4623 outputs.add(openOutputs.keyAt(i));
4624 }
4625 }
4626 return outputs;
4627}
4628
Eric Laurente0720872014-03-11 09:30:41 -07004629bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004630 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004631{
4632 if (outputs1.size() != outputs2.size()) {
4633 return false;
4634 }
4635 for (size_t i = 0; i < outputs1.size(); i++) {
4636 if (outputs1[i] != outputs2[i]) {
4637 return false;
4638 }
4639 }
4640 return true;
4641}
4642
Mikhail Naganov37977152018-07-11 15:54:44 -07004643void AudioPolicyManager::checkForDeviceAndOutputChanges()
4644{
4645 checkForDeviceAndOutputChanges([](){ return false; });
4646}
4647
4648void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4649{
4650 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4651 // output is suspended before any tracks are moved to it
4652 checkA2dpSuspend();
4653 checkOutputForAllStrategies();
4654 if (onOutputsChecked()) checkA2dpSuspend();
4655 updateDevicesAndOutputs();
4656}
4657
Eric Laurente0720872014-03-11 09:30:41 -07004658void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004659{
4660 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4661 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4662 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4663 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4664
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004665 // also take into account external policy-related changes: add all outputs which are
4666 // associated with policies in the "before" and "after" output vectors
4667 ALOGVV("checkOutputForStrategy(): policy related outputs");
4668 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004669 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004670 if (desc != 0 && desc->mPolicyMix != NULL) {
4671 srcOutputs.add(desc->mIoHandle);
4672 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4673 }
4674 }
4675 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004676 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004677 if (desc != 0 && desc->mPolicyMix != NULL) {
4678 dstOutputs.add(desc->mIoHandle);
4679 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4680 }
4681 }
4682
Eric Laurente552edb2014-03-10 17:42:56 -07004683 if (!vectorsEqual(srcOutputs,dstOutputs)) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004684 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4685 // audio from invalidated tracks will be rendered when unmuting
4686 uint32_t maxLatency = 0;
4687 for (audio_io_handle_t srcOut : srcOutputs) {
4688 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4689 if (desc != 0 && maxLatency < desc->latency()) {
4690 maxLatency = desc->latency();
4691 }
4692 }
Eric Laurente552edb2014-03-10 17:42:56 -07004693 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4694 strategy, srcOutputs[0], dstOutputs[0]);
4695 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004696 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004697 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4698 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004699 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004700 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004701 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004702 sp<AudioSourceDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004703 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004704 if (source != 0){
4705 connectAudioSource(source);
4706 }
Eric Laurente552edb2014-03-10 17:42:56 -07004707 }
4708
4709 // Move effects associated to this strategy from previous output to new output
4710 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004711 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004714 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004715 if (getStrategy((audio_stream_type_t)i) == strategy) {
4716 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004717 }
4718 }
4719 }
4720}
4721
Eric Laurente0720872014-03-11 09:30:41 -07004722void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004723{
François Gaffie2110e042015-03-24 08:41:51 +01004724 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004725 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004726 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004727 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004728 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004729 checkOutputForStrategy(STRATEGY_SONIFICATION);
4730 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004731 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004732 checkOutputForStrategy(STRATEGY_MEDIA);
4733 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004734 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004735}
4736
Eric Laurente0720872014-03-11 09:30:41 -07004737void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004738{
François Gaffie53615e22015-03-19 09:24:12 +01004739 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004740 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004741 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004742 return;
4743 }
4744
Eric Laurent3a4311c2014-03-17 12:00:47 -07004745 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004746 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4747 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4748 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004749
4750 // if suspended, restore A2DP output if:
4751 // ((SCO device is NOT connected) ||
4752 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4753 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004754 //
Eric Laurentf732e072016-08-03 19:30:28 -07004755 // if not suspended, suspend A2DP output if:
4756 // (SCO device is connected) &&
4757 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4758 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004759 //
4760 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004761 if (!isScoConnected ||
4762 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4763 AUDIO_POLICY_FORCE_BT_SCO) &&
4764 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4765 AUDIO_POLICY_FORCE_BT_SCO) &&
4766 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004767 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004768
4769 mpClientInterface->restoreOutput(a2dpOutput);
4770 mA2dpSuspended = false;
4771 }
4772 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004773 if (isScoConnected &&
4774 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4775 AUDIO_POLICY_FORCE_BT_SCO) ||
4776 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4777 AUDIO_POLICY_FORCE_BT_SCO) ||
4778 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004779 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780
4781 mpClientInterface->suspendOutput(a2dpOutput);
4782 mA2dpSuspended = true;
4783 }
4784 }
4785}
4786
Eric Laurentc75307b2015-03-17 15:29:32 -07004787audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4788 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004789{
4790 audio_devices_t device = AUDIO_DEVICE_NONE;
4791
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004792 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 if (index >= 0) {
4794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4795 if (patchDesc->mUid != mUidCached) {
4796 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004797 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004798 return outputDesc->device();
4799 }
4800 }
4801
Eric Laurentf3a5a602018-05-22 18:42:55 -07004802 // Check if an explicit routing request exists for an active stream on this output and
4803 // use it in priority before any other rule
4804 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
4805 if (outputDesc->isStreamActive((audio_stream_type_t)stream)) {
4806 audio_devices_t forcedDevice =
4807 mOutputRoutes.getActiveDeviceForStream(
4808 (audio_stream_type_t)stream, mAvailableOutputDevices);
4809
4810 if (forcedDevice != AUDIO_DEVICE_NONE) {
4811 return forcedDevice;
4812 }
4813 }
4814 }
4815
Eric Laurente552edb2014-03-10 17:42:56 -07004816 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004817 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004818 // use device for strategy enforced audible
4819 // 2: we are in call or the strategy phone is active on the output:
4820 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004821 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004822 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004823 // 4: the strategy for enforced audible is active but not enforced on the output:
4824 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004825 // 5: the strategy accessibility is active on the output:
4826 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004827 // 6: the strategy "respectful" sonification is active on the output:
4828 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004829 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004830 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004831 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004832 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004833 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004834 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004835
4836 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4837 // with a refined rule considering mutually exclusive devices (using same backend)
4838 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004839 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004840 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4842 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004843 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004844 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004845 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004846 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004847 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4848 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004849 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4850 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004851 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004852 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004853 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004854 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004855 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004856 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004857 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004858 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004859 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004860 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004861 }
4862
Eric Laurent1c333e22014-05-20 10:48:17 -07004863 ALOGV("getNewOutputDevice() selected device %x", device);
4864 return device;
4865}
4866
Eric Laurentfb66dd92016-01-28 18:32:03 -08004867audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004868{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004869 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004870
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004871 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 if (index >= 0) {
4873 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4874 if (patchDesc->mUid != mUidCached) {
4875 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004876 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 return inputDesc->mDevice;
4878 }
4879 }
4880
Eric Laurentdc95a252018-04-12 12:46:56 -07004881 // If we are not in call and no client is active on this input, this methods returns
4882 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurentfb66dd92016-01-28 18:32:03 -08004883 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
Eric Laurentdc95a252018-04-12 12:46:56 -07004884 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4885 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4886 }
4887 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004888 device = getDeviceAndMixForInputSource(source);
4889 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004890
Eric Laurente552edb2014-03-10 17:42:56 -07004891 return device;
4892}
4893
Eric Laurent794fde22016-03-11 09:50:45 -08004894bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4895 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004896 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004897}
4898
Eric Laurente0720872014-03-11 09:30:41 -07004899uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004900 return (uint32_t)getStrategy(stream);
4901}
4902
Eric Laurente0720872014-03-11 09:30:41 -07004903audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004904 // By checking the range of stream before calling getStrategy, we avoid
4905 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4906 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004907 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 return AUDIO_DEVICE_NONE;
4909 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004910 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004911 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4912 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004913 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 }
Eric Laurent794fde22016-03-11 09:50:45 -08004915 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004916 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004917 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004918 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4919 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004920 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004921 curDevices |= outputDesc->device();
4922 }
4923 }
4924 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004925 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004926
4927 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4928 and doesn't really need to.*/
4929 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4930 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4931 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4932 }
Eric Laurente552edb2014-03-10 17:42:56 -07004933 return devices;
4934}
4935
François Gaffie2110e042015-03-24 08:41:51 +01004936routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4937{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004938 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004939 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004940}
4941
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004942uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4943 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004944 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4945 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4946 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004947 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4948 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4949 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004950 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004951 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004952}
4953
Eric Laurente0720872014-03-11 09:30:41 -07004954void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004955 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004956 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004957 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4958 updateDevicesAndOutputs();
4959 break;
4960 default:
4961 break;
4962 }
4963}
4964
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004965uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004966
4967 // skip beacon mute management if a dedicated TTS output is available
4968 if (mTtsOutputAvailable) {
4969 return 0;
4970 }
4971
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004972 switch(event) {
4973 case STARTING_OUTPUT:
4974 mBeaconMuteRefCount++;
4975 break;
4976 case STOPPING_OUTPUT:
4977 if (mBeaconMuteRefCount > 0) {
4978 mBeaconMuteRefCount--;
4979 }
4980 break;
4981 case STARTING_BEACON:
4982 mBeaconPlayingRefCount++;
4983 break;
4984 case STOPPING_BEACON:
4985 if (mBeaconPlayingRefCount > 0) {
4986 mBeaconPlayingRefCount--;
4987 }
4988 break;
4989 }
4990
4991 if (mBeaconMuteRefCount > 0) {
4992 // any playback causes beacon to be muted
4993 return setBeaconMute(true);
4994 } else {
4995 // no other playback: unmute when beacon starts playing, mute when it stops
4996 return setBeaconMute(mBeaconPlayingRefCount == 0);
4997 }
4998}
4999
5000uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5001 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5002 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5003 // keep track of muted state to avoid repeating mute/unmute operations
5004 if (mBeaconMuted != mute) {
5005 // mute/unmute AUDIO_STREAM_TTS on all outputs
5006 ALOGV("\t muting %d", mute);
5007 uint32_t maxLatency = 0;
5008 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005009 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005010 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005011 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005012 0 /*delay*/, AUDIO_DEVICE_NONE);
5013 const uint32_t latency = desc->latency() * 2;
5014 if (latency > maxLatency) {
5015 maxLatency = latency;
5016 }
5017 }
5018 mBeaconMuted = mute;
5019 return maxLatency;
5020 }
5021 return 0;
5022}
5023
Eric Laurente0720872014-03-11 09:30:41 -07005024audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01005025 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005026{
Eric Laurentf3a5a602018-05-22 18:42:55 -07005027 // Check if an explicit routing request exists for a stream type corresponding to the
5028 // specified strategy and use it in priority over default routing rules.
5029 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
5030 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5031 audio_devices_t forcedDevice =
5032 mOutputRoutes.getActiveDeviceForStream(
5033 (audio_stream_type_t)stream, mAvailableOutputDevices);
5034 if (forcedDevice != AUDIO_DEVICE_NONE) {
5035 return forcedDevice;
5036 }
Paul McLeanaa981192015-03-21 09:55:15 -07005037 }
5038 }
5039
Eric Laurente552edb2014-03-10 17:42:56 -07005040 if (fromCache) {
5041 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
5042 strategy, mDeviceForStrategy[strategy]);
5043 return mDeviceForStrategy[strategy];
5044 }
François Gaffie2110e042015-03-24 08:41:51 +01005045 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07005046}
5047
Eric Laurente0720872014-03-11 09:30:41 -07005048void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005049{
5050 for (int i = 0; i < NUM_STRATEGIES; i++) {
5051 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5052 }
5053 mPreviousOutputs = mOutputs;
5054}
5055
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005056uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005057 audio_devices_t prevDevice,
5058 uint32_t delayMs)
5059{
5060 // mute/unmute strategies using an incompatible device combination
5061 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5062 // if unmuting, unmute only after the specified delay
5063 if (outputDesc->isDuplicated()) {
5064 return 0;
5065 }
5066
5067 uint32_t muteWaitMs = 0;
5068 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07005069 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005070
5071 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
5072 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07005073 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07005074 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
5075 bool doMute = false;
5076
5077 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5078 doMute = true;
5079 outputDesc->mStrategyMutedByDevice[i] = true;
5080 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5081 doMute = true;
5082 outputDesc->mStrategyMutedByDevice[i] = false;
5083 }
Eric Laurent99401132014-05-07 19:48:15 -07005084 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005085 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005086 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005087 // skip output if it does not share any device with current output
5088 if ((desc->supportedDevices() & outputDesc->supportedDevices())
5089 == AUDIO_DEVICE_NONE) {
5090 continue;
5091 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005092 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07005093 mute ? "muting" : "unmuting", i, curDevice);
5094 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005095 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005096 if (mute) {
5097 // FIXME: should not need to double latency if volume could be applied
5098 // immediately by the audioflinger mixer. We must account for the delay
5099 // between now and the next time the audioflinger thread for this output
5100 // will process a buffer (which corresponds to one buffer size,
5101 // usually 1/2 or 1/4 of the latency).
5102 if (muteWaitMs < desc->latency() * 2) {
5103 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005104 }
5105 }
5106 }
5107 }
5108 }
5109 }
5110
Eric Laurent99401132014-05-07 19:48:15 -07005111 // temporary mute output if device selection changes to avoid volume bursts due to
5112 // different per device volumes
5113 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005114 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5115 // temporary mute duration is conservatively set to 4 times the reported latency
5116 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5117 if (muteWaitMs < tempMuteWaitMs) {
5118 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005119 }
Eric Laurentdc462862016-07-19 12:29:53 -07005120
Eric Laurent99401132014-05-07 19:48:15 -07005121 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005122 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005123 // make sure that we do not start the temporary mute period too early in case of
5124 // delayed device change
5125 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005126 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005127 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005128 }
5129 }
5130 }
5131
Eric Laurente552edb2014-03-10 17:42:56 -07005132 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5133 if (muteWaitMs > delayMs) {
5134 muteWaitMs -= delayMs;
5135 usleep(muteWaitMs * 1000);
5136 return muteWaitMs;
5137 }
5138 return 0;
5139}
5140
Eric Laurentc75307b2015-03-17 15:29:32 -07005141uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005142 audio_devices_t device,
5143 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005144 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005145 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005146 const char *address,
5147 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005148{
Eric Laurentc75307b2015-03-17 15:29:32 -07005149 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005150 AudioParameter param;
5151 uint32_t muteWaitMs;
5152
5153 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005154 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5155 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5156 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5157 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005158 return muteWaitMs;
5159 }
5160 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5161 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005163 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005164 return 0;
5165 }
5166
5167 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005169
5170 audio_devices_t prevDevice = outputDesc->mDevice;
5171
Paul McLeanaa981192015-03-21 09:55:15 -07005172 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005173
5174 if (device != AUDIO_DEVICE_NONE) {
5175 outputDesc->mDevice = device;
5176 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005177
5178 // if the outputs are not materially active, there is no need to mute.
5179 if (requiresMuteCheck) {
5180 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5181 } else {
5182 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5183 muteWaitMs = 0;
5184 }
Eric Laurente552edb2014-03-10 17:42:56 -07005185
5186 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005187 // the requested device is AUDIO_DEVICE_NONE
5188 // OR the requested device is the same as current device
5189 // AND force is not specified
5190 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005191 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005192 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5193 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005194 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005195 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005196 return muteWaitMs;
5197 }
5198
5199 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005200
Eric Laurente552edb2014-03-10 17:42:56 -07005201 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005202 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005203 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005205 DeviceVector deviceList;
5206 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005207 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005208 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005209 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5210 device, String8(address));
5211 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005212 }
5213
Eric Laurent1c333e22014-05-20 10:48:17 -07005214 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005215 PatchBuilder patchBuilder;
5216 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005217 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005218 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005219 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005220 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005221 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005222
5223 // inform all input as well
5224 for (size_t i = 0; i < mInputs.size(); i++) {
5225 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005226 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005227 AudioParameter inputCmd = AudioParameter();
5228 ALOGV("%s: inform input %d of device:%d", __func__,
5229 inputDescriptor->mIoHandle, device);
5230 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5231 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5232 inputCmd.toString(),
5233 delayMs);
5234 }
5235 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005236 }
Eric Laurente552edb2014-03-10 17:42:56 -07005237
5238 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005239 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005240
5241 return muteWaitMs;
5242}
5243
Eric Laurentc75307b2015-03-17 15:29:32 -07005244status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 int delayMs,
5246 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005247{
Eric Laurent6a94d692014-05-20 11:18:06 -07005248 ssize_t index;
5249 if (patchHandle) {
5250 index = mAudioPatches.indexOfKey(*patchHandle);
5251 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005252 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 }
5254 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005255 return INVALID_OPERATION;
5256 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5258 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005259 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005260 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 removeAudioPatch(patchDesc->mHandle);
5262 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005263 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005264 return status;
5265}
5266
5267status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5268 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 bool force,
5270 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005271{
5272 status_t status = NO_ERROR;
5273
Eric Laurent1f2f2232014-06-02 12:01:23 -07005274 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005275 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5276 inputDesc->mDevice = device;
5277
Mikhail Naganov708e0382018-05-30 09:53:04 -07005278 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005279 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005280 PatchBuilder patchBuilder;
5281 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005282 // AUDIO_SOURCE_HOTWORD is for internal use only:
5283 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005284 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5285 auto result = usecase;
5286 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5287 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5288 }
5289 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005290 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005291 addSource(deviceList.itemAt(0));
5292 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005293 }
5294 }
5295 return status;
5296}
5297
Eric Laurent6a94d692014-05-20 11:18:06 -07005298status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5299 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005300{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 ssize_t index;
5303 if (patchHandle) {
5304 index = mAudioPatches.indexOfKey(*patchHandle);
5305 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005306 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005307 }
5308 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005309 return INVALID_OPERATION;
5310 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5312 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005313 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005314 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 removeAudioPatch(patchDesc->mHandle);
5316 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005317 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005318 return status;
5319}
5320
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005321sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005322 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005323 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005324 audio_format_t& format,
5325 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005326 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005327{
5328 // Choose an input profile based on the requested capture parameters: select the first available
5329 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005330 //
5331 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5332 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005333
Glenn Kasten730b9262018-03-29 15:01:26 -07005334 sp<IOProfile> firstInexact;
5335 uint32_t updatedSamplingRate = 0;
5336 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5337 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005338 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005339 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005340 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005341 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005342 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005343 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005344 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005345 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005346 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005347 &channelMask /*updatedChannelMask*/,
5348 // FIXME ugly cast
5349 (audio_output_flags_t) flags,
5350 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005351 return profile;
5352 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005353 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5354 samplingRate,
5355 &updatedSamplingRate,
5356 format,
5357 &updatedFormat,
5358 channelMask,
5359 &updatedChannelMask,
5360 // FIXME ugly cast
5361 (audio_output_flags_t) flags,
5362 false /*exactMatchRequiredForInputFlags*/)) {
5363 firstInexact = profile;
5364 }
5365
Eric Laurente552edb2014-03-10 17:42:56 -07005366 }
5367 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005368 if (firstInexact != nullptr) {
5369 samplingRate = updatedSamplingRate;
5370 format = updatedFormat;
5371 channelMask = updatedChannelMask;
5372 return firstInexact;
5373 }
Eric Laurente552edb2014-03-10 17:42:56 -07005374 return NULL;
5375}
5376
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005377
5378audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005379 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005380{
François Gaffie036e1e92015-03-19 10:16:24 +01005381 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5382 audio_devices_t selectedDeviceFromMix =
5383 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005384
François Gaffie036e1e92015-03-19 10:16:24 +01005385 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5386 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005387 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005388 return getDeviceForInputSource(inputSource);
5389}
5390
5391audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5392{
Eric Laurentad2e7b92017-09-14 20:06:42 -07005393 // Routing
5394 // Scan the whole RouteMap to see if we have an explicit route:
5395 // if the input source in the RouteMap is the same as the argument above,
5396 // and activity count is non-zero and the device in the route descriptor is available
5397 // then select this device.
Paul McLean466dc8e2015-04-17 13:15:36 -06005398 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5399 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent2157f5b2018-04-25 18:33:02 -07005400 if ((inputSource == route->mSource) && route->isActiveOrChanged() &&
Eric Laurentad2e7b92017-09-14 20:06:42 -07005401 (mAvailableInputDevices.indexOf(route->mDeviceDescriptor) >= 0)) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005402 return route->mDeviceDescriptor->type();
5403 }
5404 }
5405
5406 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005407}
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005410 int index,
5411 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005412{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005413 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005414
5415 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5416 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5417 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5418 // the ringtone volume
5419 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5420 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5421 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5422 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5423 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5424 }
5425
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005426 // in-call: always cap volume by voice volume + some low headroom
5427 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005428 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005429 switch (stream) {
5430 case AUDIO_STREAM_SYSTEM:
5431 case AUDIO_STREAM_RING:
5432 case AUDIO_STREAM_MUSIC:
5433 case AUDIO_STREAM_ALARM:
5434 case AUDIO_STREAM_NOTIFICATION:
5435 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5436 case AUDIO_STREAM_DTMF:
5437 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005438 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005439 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005440 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005441 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005442 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005443 if (volumeDB > maxVoiceVolDb) {
5444 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5445 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5446 volumeDB = maxVoiceVolDb;
5447 }
5448 } break;
5449 default:
5450 break;
5451 }
5452 }
5453
Eric Laurente552edb2014-03-10 17:42:56 -07005454 // if a headset is connected, apply the following rules to ring tones and notifications
5455 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005456 // - always attenuate notifications volume by 6dB
5457 // - attenuate ring tones volume by 6dB unless music is not playing and
5458 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005459 // - if music is playing, always limit the volume to current music volume,
5460 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005461 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005462 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5463 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5464 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005465 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005466 AUDIO_DEVICE_OUT_USB_HEADSET |
5467 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005468 ((stream_strategy == STRATEGY_SONIFICATION)
5469 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005470 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005471 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005472 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005473 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005474 // when the phone is ringing we must consider that music could have been paused just before
5475 // by the music application and behave as if music was active if the last music track was
5476 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005477 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005478 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005479 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005480 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005481 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005482 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5483 musicDevice),
5484 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005485 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5486 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 if (volumeDB > minVolDB) {
5488 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005490 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005491 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5492 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5493 // on A2DP, also ensure notification volume is not too low compared to media when
5494 // intended to be played
5495 if ((volumeDB > -96.0f) &&
5496 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5497 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5498 stream, device,
5499 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5500 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5501 }
5502 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005503 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5504 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005505 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005506 }
5507 }
5508
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005509 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005510}
5511
Eric Laurent3839bc02018-07-10 18:33:34 -07005512int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5513 audio_stream_type_t srcStream,
5514 audio_stream_type_t dstStream)
5515{
5516 if (srcStream == dstStream) {
5517 return srcIndex;
5518 }
5519 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5520 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5521 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5522 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5523
5524 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5525}
5526
Eric Laurente0720872014-03-11 09:30:41 -07005527status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005528 int index,
5529 const sp<AudioOutputDescriptor>& outputDesc,
5530 audio_devices_t device,
5531 int delayMs,
5532 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005533{
Eric Laurente552edb2014-03-10 17:42:56 -07005534 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005535 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005537 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005538 return NO_ERROR;
5539 }
François Gaffie2110e042015-03-24 08:41:51 +01005540 audio_policy_forced_cfg_t forceUseForComm =
5541 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005542 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005543 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5544 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005545 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005546 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005547 return INVALID_OPERATION;
5548 }
5549
Eric Laurentc75307b2015-03-17 15:29:32 -07005550 if (device == AUDIO_DEVICE_NONE) {
5551 device = outputDesc->device();
5552 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005553
Eric Laurentffbc80f2015-03-18 18:30:19 -07005554 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005555 if (outputDesc->isFixedVolume(device) ||
5556 // Force VoIP volume to max for bluetooth SCO
5557 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5558 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005559 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005560 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005561
Eric Laurentffbc80f2015-03-18 18:30:19 -07005562 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005563
Eric Laurent3b73df72014-03-11 09:06:29 -07005564 if (stream == AUDIO_STREAM_VOICE_CALL ||
5565 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005566 float voiceVolume;
5567 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005568 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005569 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005570 } else {
5571 voiceVolume = 1.0;
5572 }
5573
Eric Laurent18fba842016-03-31 14:41:26 -07005574 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005575 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5576 mLastVoiceVolume = voiceVolume;
5577 }
5578 }
5579
5580 return NO_ERROR;
5581}
5582
Eric Laurentc75307b2015-03-17 15:29:32 -07005583void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5584 audio_devices_t device,
5585 int delayMs,
5586 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005587{
Eric Laurentc75307b2015-03-17 15:29:32 -07005588 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005589
Eric Laurent794fde22016-03-11 09:50:45 -08005590 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005591 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005592 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005594 device,
5595 delayMs,
5596 force);
5597 }
5598}
5599
Eric Laurente0720872014-03-11 09:30:41 -07005600void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 bool on,
5602 const sp<AudioOutputDescriptor>& outputDesc,
5603 int delayMs,
5604 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005605{
Eric Laurent72249d52015-06-08 11:12:15 -07005606 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5607 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005608 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005609 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005610 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005611 }
5612 }
5613}
5614
Eric Laurente0720872014-03-11 09:30:41 -07005615void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005616 bool on,
5617 const sp<AudioOutputDescriptor>& outputDesc,
5618 int delayMs,
5619 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005620{
Eric Laurente552edb2014-03-10 17:42:56 -07005621 if (device == AUDIO_DEVICE_NONE) {
5622 device = outputDesc->device();
5623 }
5624
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5626 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005627
5628 if (on) {
5629 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005630 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005631 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005632 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005634 }
5635 }
5636 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5637 outputDesc->mMuteCount[stream]++;
5638 } else {
5639 if (outputDesc->mMuteCount[stream] == 0) {
5640 ALOGV("setStreamMute() unmuting non muted stream!");
5641 return;
5642 }
5643 if (--outputDesc->mMuteCount[stream] == 0) {
5644 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005645 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005646 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005647 device,
5648 delayMs);
5649 }
5650 }
5651}
5652
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005653audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5654{
5655 // flags to stream type mapping
5656 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5657 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5658 }
5659 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5660 return AUDIO_STREAM_BLUETOOTH_SCO;
5661 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005662 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5663 return AUDIO_STREAM_TTS;
5664 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005665
5666 // usage to stream type mapping
5667 switch (attr->usage) {
5668 case AUDIO_USAGE_MEDIA:
5669 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005670 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005671 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5672 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005673 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5674 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005675 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5676 return AUDIO_STREAM_SYSTEM;
5677 case AUDIO_USAGE_VOICE_COMMUNICATION:
5678 return AUDIO_STREAM_VOICE_CALL;
5679
5680 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5681 return AUDIO_STREAM_DTMF;
5682
5683 case AUDIO_USAGE_ALARM:
5684 return AUDIO_STREAM_ALARM;
5685 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5686 return AUDIO_STREAM_RING;
5687
5688 case AUDIO_USAGE_NOTIFICATION:
5689 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5690 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5691 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5692 case AUDIO_USAGE_NOTIFICATION_EVENT:
5693 return AUDIO_STREAM_NOTIFICATION;
5694
5695 case AUDIO_USAGE_UNKNOWN:
5696 default:
5697 return AUDIO_STREAM_MUSIC;
5698 }
5699}
Eric Laurente83b55d2014-11-14 10:06:21 -08005700
François Gaffie53615e22015-03-19 09:24:12 +01005701bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5702{
Eric Laurente83b55d2014-11-14 10:06:21 -08005703 // has flags that map to a strategy?
5704 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5705 return true;
5706 }
5707
5708 // has known usage?
5709 switch (paa->usage) {
5710 case AUDIO_USAGE_UNKNOWN:
5711 case AUDIO_USAGE_MEDIA:
5712 case AUDIO_USAGE_VOICE_COMMUNICATION:
5713 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5714 case AUDIO_USAGE_ALARM:
5715 case AUDIO_USAGE_NOTIFICATION:
5716 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5717 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5718 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5719 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5720 case AUDIO_USAGE_NOTIFICATION_EVENT:
5721 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5722 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5723 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5724 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005725 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005726 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005727 break;
5728 default:
5729 return false;
5730 }
5731 return true;
5732}
5733
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005734bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005735 routing_strategy strategy, uint32_t inPastMs,
5736 nsecs_t sysTime) const
5737{
5738 if ((sysTime == 0) && (inPastMs != 0)) {
5739 sysTime = systemTime();
5740 }
Eric Laurent794fde22016-03-11 09:50:45 -08005741 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005742 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5743 (NUM_STRATEGIES == strategy)) &&
5744 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5745 return true;
5746 }
5747 }
5748 return false;
5749}
5750
Eric Laurent484e9272018-06-07 17:29:23 -07005751bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5752 routing_strategy strategy, uint32_t inPastMs,
5753 nsecs_t sysTime) const
5754{
5755 for (size_t i = 0; i < mOutputs.size(); i++) {
5756 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5757 if (outputDesc->sharesHwModuleWith(desc)
5758 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5759 return true;
5760 }
5761 }
5762 return false;
5763}
5764
François Gaffie2110e042015-03-24 08:41:51 +01005765audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5766{
5767 return mEngine->getForceUse(usage);
5768}
5769
5770bool AudioPolicyManager::isInCall()
5771{
5772 return isStateInCall(mEngine->getPhoneState());
5773}
5774
5775bool AudioPolicyManager::isStateInCall(int state)
5776{
5777 return is_state_in_call(state);
5778}
5779
Eric Laurentd60560a2015-04-10 11:31:20 -07005780void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5781{
5782 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5783 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5784 if (sourceDesc->mDevice->equals(deviceDesc)) {
5785 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5786 stopAudioSource(sourceDesc->getHandle());
5787 }
5788 }
5789
5790 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5791 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5792 bool release = false;
5793 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5794 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5795 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5796 source->ext.device.type == deviceDesc->type()) {
5797 release = true;
5798 }
5799 }
5800 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5801 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5802 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5803 sink->ext.device.type == deviceDesc->type()) {
5804 release = true;
5805 }
5806 }
5807 if (release) {
5808 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5809 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5810 }
5811 }
5812}
5813
Phil Burk09bc4612016-02-24 15:58:15 -08005814// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005815void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5816 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005817 // TODO Set this based on Config properties.
5818 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005819
5820 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5821 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005822 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005823
jiabin81772902018-04-02 17:52:27 -07005824 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5825 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5826 formats.clear();
5827 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5828 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005829 }
jiabin81772902018-04-02 17:52:27 -07005830 // Always enable IEC61937 when in MANUAL mode.
5831 formats.add(AUDIO_FORMAT_IEC61937);
5832 } else { // NEVER, AUTO or ALWAYS
5833 // Analyze original support for various formats.
5834 bool supportsAC3 = false;
5835 bool supportsOtherSurround = false;
5836 bool supportsIEC61937 = false;
5837 mSurroundFormats.clear();
5838 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5839 audio_format_t format = formats[formatIndex];
5840 switch (format) {
5841 case AUDIO_FORMAT_AC3:
5842 supportsAC3 = true;
5843 break;
5844 case AUDIO_FORMAT_E_AC3:
5845 case AUDIO_FORMAT_DTS:
5846 case AUDIO_FORMAT_DTS_HD:
5847 // If ALWAYS, remove all other surround formats here
5848 // since we will add them later.
5849 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5850 formats.removeAt(formatIndex);
5851 formatIndex--;
5852 }
5853 supportsOtherSurround = true;
5854 break;
5855 case AUDIO_FORMAT_IEC61937:
5856 supportsIEC61937 = true;
5857 break;
5858 default:
5859 break;
5860 }
5861 }
Phil Burk09bc4612016-02-24 15:58:15 -08005862
jiabin81772902018-04-02 17:52:27 -07005863 // Modify formats based on surround preferences.
5864 // If NEVER, remove support for surround formats.
5865 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5866 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5867 // Remove surround sound related formats.
5868 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5869 audio_format_t format = formats[formatIndex];
5870 switch(format) {
5871 case AUDIO_FORMAT_AC3:
5872 case AUDIO_FORMAT_E_AC3:
5873 case AUDIO_FORMAT_DTS:
5874 case AUDIO_FORMAT_DTS_HD:
5875 case AUDIO_FORMAT_IEC61937:
5876 formats.removeAt(formatIndex);
5877 break;
5878 default:
5879 formatIndex++; // keep it
5880 break;
5881 }
5882 }
5883 supportsAC3 = false;
5884 supportsOtherSurround = false;
5885 supportsIEC61937 = false;
5886 }
5887 } else { // AUTO or ALWAYS
5888 // Most TVs support AC3 even if they do not report it in the EDID.
5889 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5890 && !supportsAC3) {
5891 formats.add(AUDIO_FORMAT_AC3);
5892 supportsAC3 = true;
5893 }
5894
5895 // If ALWAYS, add support for raw surround formats if all are missing.
5896 // This assumes that if any of these formats are reported by the HAL
5897 // then the report is valid and should not be modified.
5898 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5899 formats.add(AUDIO_FORMAT_E_AC3);
5900 formats.add(AUDIO_FORMAT_DTS);
5901 formats.add(AUDIO_FORMAT_DTS_HD);
5902 supportsOtherSurround = true;
5903 }
5904
5905 // Add support for IEC61937 if any raw surround supported.
5906 // The HAL could do this but add it here, just in case.
5907 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5908 formats.add(AUDIO_FORMAT_IEC61937);
5909 supportsIEC61937 = true;
5910 }
5911
5912 // Add reported surround sound formats to enabled surround formats.
5913 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005914 audio_format_t format = formats[formatIndex];
5915 switch(format) {
5916 case AUDIO_FORMAT_AC3:
5917 case AUDIO_FORMAT_E_AC3:
5918 case AUDIO_FORMAT_DTS:
5919 case AUDIO_FORMAT_DTS_HD:
jiabin81772902018-04-02 17:52:27 -07005920 case AUDIO_FORMAT_AAC_LC:
5921 case AUDIO_FORMAT_DOLBY_TRUEHD:
5922 case AUDIO_FORMAT_E_AC3_JOC:
5923 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005924 default:
Phil Burk07ac1142016-03-25 13:39:29 -07005925 break;
5926 }
Phil Burk09bc4612016-02-24 15:58:15 -08005927 }
Phil Burk07ac1142016-03-25 13:39:29 -07005928 }
Phil Burk09bc4612016-02-24 15:58:15 -08005929 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005930}
5931
5932// Modify the list of channel masks supported.
5933void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5934 ChannelsVector &channelMasks = *channelMasksPtr;
5935 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5936 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5937
5938 // If NEVER, then remove support for channelMasks > stereo.
5939 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5940 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5941 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5942 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5943 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5944 channelMasks.removeAt(maskIndex);
5945 } else {
5946 maskIndex++;
5947 }
5948 }
jiabin81772902018-04-02 17:52:27 -07005949 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5950 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5951 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005952 bool supports5dot1 = false;
5953 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005954 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005955 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5956 supports5dot1 = true;
5957 break;
5958 }
5959 }
5960 // If not then add 5.1 support.
5961 if (!supports5dot1) {
5962 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5963 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5964 }
Phil Burk09bc4612016-02-24 15:58:15 -08005965 }
5966}
5967
Phil Burk00eeb322016-03-31 12:41:00 -07005968void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5969 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005970 AudioProfileVector &profiles)
5971{
5972 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005973
François Gaffie112b0af2015-11-19 16:13:25 +01005974 // Format MUST be checked first to update the list of AudioProfile
5975 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005976 reply = mpClientInterface->getParameters(
5977 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005978 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005979 AudioParameter repliedParameters(reply);
5980 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005981 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005982 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5983 return;
5984 }
Phil Burk09bc4612016-02-24 15:58:15 -08005985 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005986 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005987 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005988 }
Phil Burk09bc4612016-02-24 15:58:15 -08005989 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005990 }
François Gaffie112b0af2015-11-19 16:13:25 +01005991
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005992 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005993 ChannelsVector channelMasks;
5994 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005995 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005996 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005997
5998 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005999 reply = mpClientInterface->getParameters(
6000 ioHandle,
6001 requestedParameters.toString() + ";" +
6002 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006003 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006004 AudioParameter repliedParameters(reply);
6005 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006006 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006007 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006008 }
6009 }
6010 if (profiles.hasDynamicChannelsFor(format)) {
6011 reply = mpClientInterface->getParameters(ioHandle,
6012 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006013 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006014 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006015 AudioParameter repliedParameters(reply);
6016 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006017 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006018 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07006019 if (device == AUDIO_DEVICE_OUT_HDMI) {
6020 filterSurroundChannelMasks(&channelMasks);
6021 }
François Gaffie112b0af2015-11-19 16:13:25 +01006022 }
6023 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08006024 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006025 }
6026}
Eric Laurentd60560a2015-04-10 11:31:20 -07006027
Mikhail Naganovdc769682018-05-04 15:34:08 -07006028status_t AudioPolicyManager::installPatch(const char *caller,
6029 audio_patch_handle_t *patchHandle,
6030 AudioIODescriptorInterface *ioDescriptor,
6031 const struct audio_patch *patch,
6032 int delayMs)
6033{
6034 ssize_t index = mAudioPatches.indexOfKey(
6035 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6036 *patchHandle : ioDescriptor->getPatchHandle());
6037 sp<AudioPatch> patchDesc;
6038 status_t status = installPatch(
6039 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6040 if (status == NO_ERROR) {
6041 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6042 }
6043 return status;
6044}
6045
6046status_t AudioPolicyManager::installPatch(const char *caller,
6047 ssize_t index,
6048 audio_patch_handle_t *patchHandle,
6049 const struct audio_patch *patch,
6050 int delayMs,
6051 uid_t uid,
6052 sp<AudioPatch> *patchDescPtr)
6053{
6054 sp<AudioPatch> patchDesc;
6055 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6056 if (index >= 0) {
6057 patchDesc = mAudioPatches.valueAt(index);
6058 afPatchHandle = patchDesc->mAfPatchHandle;
6059 }
6060
6061 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6062 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6063 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6064 if (status == NO_ERROR) {
6065 if (index < 0) {
6066 patchDesc = new AudioPatch(patch, uid);
6067 addAudioPatch(patchDesc->mHandle, patchDesc);
6068 } else {
6069 patchDesc->mPatch = *patch;
6070 }
6071 patchDesc->mAfPatchHandle = afPatchHandle;
6072 if (patchHandle) {
6073 *patchHandle = patchDesc->mHandle;
6074 }
6075 nextAudioPortGeneration();
6076 mpClientInterface->onAudioPatchListUpdate();
6077 }
6078 if (patchDescPtr) *patchDescPtr = patchDesc;
6079 return status;
6080}
6081
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006082} // namespace android