blob: 1b088bb4774a6fb91cc9a11b5e19662d4e841a5f [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"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090032#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
Petri Gyntherf497f292018-04-17 18:46:10 -070034#define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010036
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070038#include <math.h>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110039#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070040
François Gaffie2110e042015-03-24 08:41:51 +010041#include <AudioPolicyManagerInterface.h>
42#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070044#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070047#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070048#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070050#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010052#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010054#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070055
Eric Laurent3b73df72014-03-11 09:06:29 -070056namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
67static const std::vector<audio_format_t> compressedFormatsOrder = {{
68 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
69 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
71static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
72 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
Eric Laurente552edb2014-03-10 17:42:56 -070076// ----------------------------------------------------------------------------
77// AudioPolicyInterface implementation
78// ----------------------------------------------------------------------------
79
Eric Laurente0720872014-03-11 09:30:41 -070080status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080081 audio_policy_dev_state_t state,
82 const char *device_address,
83 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070084{
jiabina7b43792018-02-15 16:04:46 -080085 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
86 nextAudioPortGeneration();
87 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080088}
89
François Gaffie44481e72016-04-20 07:49:57 +020090void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
91 audio_policy_dev_state_t state,
92 const String8 &device_address)
93{
94 AudioParameter param(device_address);
95 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070096 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020097 param.addInt(key, device);
98 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
99}
100
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800101status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800102 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800103 const char *device_address,
104 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800105{
Paul McLeane743a472015-01-28 11:07:31 -0800106 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
Mikhail Naganov7e22e942017-12-07 10:04:29 -0800107 device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700108
109 // connect/disconnect only 1 device at a time
110 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
111
François Gaffie53615e22015-03-19 09:24:12 +0100112 sp<DeviceDescriptor> devDesc =
113 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800114
Eric Laurente552edb2014-03-10 17:42:56 -0700115 // handle output devices
116 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700117 SortedVector <audio_io_handle_t> outputs;
118
Eric Laurent3a4311c2014-03-17 12:00:47 -0700119 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
120
Eric Laurente552edb2014-03-10 17:42:56 -0700121 // save a copy of the opened output descriptors before any output is opened or closed
122 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
123 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700124 switch (state)
125 {
126 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800127 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700128 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700129 ALOGW("setDeviceConnectionState() device already connected: %x", device);
130 return INVALID_OPERATION;
131 }
132 ALOGV("setDeviceConnectionState() connecting device %x", device);
133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700135 index = mAvailableOutputDevices.add(devDesc);
136 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100137 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700138 if (module == 0) {
139 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
140 device);
141 mAvailableOutputDevices.remove(devDesc);
142 return INVALID_OPERATION;
143 }
Paul McLeane743a472015-01-28 11:07:31 -0800144 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700145 } else {
146 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700147 }
148
François Gaffie44481e72016-04-20 07:49:57 +0200149 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
150 // parameters on newly connected devices (instead of opening the outputs...)
151 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
152
Eric Laurenta1d525f2015-01-29 13:36:45 -0800153 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700154 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200155
156 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
157 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700158 return INVALID_OPERATION;
159 }
François Gaffie2110e042015-03-24 08:41:51 +0100160 // Propagate device availability to Engine
161 mEngine->setDeviceConnectionState(devDesc, state);
162
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700163 // outputs should never be empty here
164 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
165 "checkOutputsForDevice() returned no outputs but status OK");
166 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
167 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800168
Eric Laurent3ae5f312015-02-03 17:12:08 -0800169 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700170 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700171 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700172 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700173 ALOGW("setDeviceConnectionState() device not connected: %x", device);
174 return INVALID_OPERATION;
175 }
176
Paul McLean5c477aa2014-08-20 16:47:57 -0700177 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
178
Paul McLeane743a472015-01-28 11:07:31 -0800179 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200180 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700181
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700184
Eric Laurenta1d525f2015-01-29 13:36:45 -0800185 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100186
187 // Propagate device availability to Engine
188 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700189 } break;
190
191 default:
192 ALOGE("setDeviceConnectionState() invalid state: %x", state);
193 return BAD_VALUE;
194 }
195
Mikhail Naganov37977152018-07-11 15:54:44 -0700196 checkForDeviceAndOutputChanges([&]() {
197 // outputs must be closed after checkOutputForAllStrategies() is executed
198 if (!outputs.isEmpty()) {
199 for (audio_io_handle_t output : outputs) {
200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
201 // close unused outputs after device disconnection or direct outputs that have been
202 // opened by checkOutputsForDevice() to query dynamic parameters
203 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
204 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
205 (desc->mDirectOpenCount == 0))) {
206 closeOutput(output);
207 }
Eric Laurente552edb2014-03-10 17:42:56 -0700208 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700209 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
210 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700212 return false;
213 });
Eric Laurente552edb2014-03-10 17:42:56 -0700214
Eric Laurent87ffa392015-05-22 10:32:38 -0700215 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700216 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
217 updateCallRouting(newDevice);
218 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100219 const audio_devices_t msdOutDevice = getMsdAudioOutDeviceTypes();
Eric Laurente552edb2014-03-10 17:42:56 -0700220 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700221 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
222 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
223 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700224 // do not force device change on duplicated output because if device is 0, it will
225 // also force a device 0 for the two outputs it is duplicated to which may override
226 // a valid device selection on those outputs.
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100227 bool force = (msdOutDevice == AUDIO_DEVICE_NONE || msdOutDevice != desc->device())
228 && !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100229 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700230 // always force when disconnecting (a non-duplicated device)
231 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700232 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700233 }
Eric Laurente552edb2014-03-10 17:42:56 -0700234 }
235
Eric Laurentd60560a2015-04-10 11:31:20 -0700236 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
237 cleanUpForDevice(devDesc);
238 }
239
Eric Laurent72aa32f2014-05-30 18:51:48 -0700240 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700241 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700242 } // end if is output device
243
Eric Laurente552edb2014-03-10 17:42:56 -0700244 // handle input devices
245 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700246 SortedVector <audio_io_handle_t> inputs;
247
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700249 switch (state)
250 {
251 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700252 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700254 ALOGW("setDeviceConnectionState() device already connected: %d", device);
255 return INVALID_OPERATION;
256 }
François Gaffie53615e22015-03-19 09:24:12 +0100257 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700258 if (module == NULL) {
259 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
260 device);
261 return INVALID_OPERATION;
262 }
François Gaffie44481e72016-04-20 07:49:57 +0200263
264 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
265 // parameters on newly connected devices (instead of opening the inputs...)
266 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
267
Paul McLean9080a4c2015-06-18 08:24:02 -0700268 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200269 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
270 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700271 return INVALID_OPERATION;
272 }
273
Eric Laurent3a4311c2014-03-17 12:00:47 -0700274 index = mAvailableInputDevices.add(devDesc);
275 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800276 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700277 } else {
278 return NO_MEMORY;
279 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800280
François Gaffie2110e042015-03-24 08:41:51 +0100281 // Propagate device availability to Engine
282 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700283 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700284
285 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700288 ALOGW("setDeviceConnectionState() device not connected: %d", device);
289 return INVALID_OPERATION;
290 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700291
292 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
293
294 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200295 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700296
Paul McLean9080a4c2015-06-18 08:24:02 -0700297 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700299
François Gaffie2110e042015-03-24 08:41:51 +0100300 // Propagate device availability to Engine
301 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700302 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700303
304 default:
305 ALOGE("setDeviceConnectionState() invalid state: %x", state);
306 return BAD_VALUE;
307 }
308
Eric Laurentd4692962014-05-05 18:13:44 -0700309 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700310 // As the input device list can impact the output device selection, update
311 // getDeviceForStrategy() cache
312 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700313
Eric Laurent87ffa392015-05-22 10:32:38 -0700314 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700315 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
316 updateCallRouting(newDevice);
317 }
318
Eric Laurentd60560a2015-04-10 11:31:20 -0700319 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
320 cleanUpForDevice(devDesc);
321 }
322
Eric Laurentb52c1522014-05-20 11:27:36 -0700323 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700324 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700325 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700326
327 ALOGW("setDeviceConnectionState() invalid device: %x", device);
328 return BAD_VALUE;
329}
330
Eric Laurente0720872014-03-11 09:30:41 -0700331audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100332 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700333{
Eric Laurent634b7142016-04-20 13:48:02 -0700334 sp<DeviceDescriptor> devDesc =
335 mHwModules.getDeviceDescriptor(device, device_address, "",
336 (strlen(device_address) != 0)/*matchAddress*/);
337
338 if (devDesc == 0) {
339 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
340 device, device_address);
341 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
342 }
François Gaffie53615e22015-03-19 09:24:12 +0100343
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 DeviceVector *deviceVector;
345
Eric Laurente552edb2014-03-10 17:42:56 -0700346 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700347 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700348 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 deviceVector = &mAvailableInputDevices;
350 } else {
351 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
352 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
Eric Laurent634b7142016-04-20 13:48:02 -0700354
355 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
356 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800357}
358
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800359status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
360 const char *device_address,
361 const char *device_name)
362{
363 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700364 String8 reply;
365 AudioParameter param;
366 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800367
368 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
369 device, device_address, device_name);
370
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800371 // connect/disconnect only 1 device at a time
372 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
373
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800374 // Check if the device is currently connected
375 sp<DeviceDescriptor> devDesc =
376 mHwModules.getDeviceDescriptor(device, device_address, device_name);
377 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
378 if (index < 0) {
379 // Nothing to do: device is not connected
380 return NO_ERROR;
381 }
382
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700383 // For offloaded A2DP, Hw modules may have the capability to
384 // configure codecs. Check if any of the loaded hw modules
385 // supports this.
386 // If supported, send a set parameter to configure A2DP codecs
387 // and return. No need to toggle device state.
388 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
389 reply = mpClientInterface->getParameters(
390 AUDIO_IO_HANDLE_NONE,
391 String8(AudioParameter::keyReconfigA2dpSupported));
392 AudioParameter repliedParameters(reply);
393 repliedParameters.getInt(
394 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
395 if (isReconfigA2dpSupported) {
396 const String8 key(AudioParameter::keyReconfigA2dp);
397 param.add(key, String8("true"));
398 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
399 return NO_ERROR;
400 }
401 }
402
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800403 // Toggle the device state: UNAVAILABLE -> AVAILABLE
404 // This will force reading again the device configuration
405 status = setDeviceConnectionState(device,
406 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
407 device_address, device_name);
408 if (status != NO_ERROR) {
409 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
410 status);
411 return status;
412 }
413
414 status = setDeviceConnectionState(device,
415 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
416 device_address, device_name);
417 if (status != NO_ERROR) {
418 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
419 status);
420 return status;
421 }
422
423 return NO_ERROR;
424}
425
Eric Laurentdc462862016-07-19 12:29:53 -0700426uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427{
428 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700429 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700430
Andy Hunga76c7de2016-12-13 19:14:31 -0800431 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700432 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700433 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800434 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
436
437 // release existing RX patch if any
438 if (mCallRxPatch != 0) {
439 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
440 mCallRxPatch.clear();
441 }
442 // release TX patch if any
443 if (mCallTxPatch != 0) {
444 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
445 mCallTxPatch.clear();
446 }
447
448 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
449 // via setOutputDevice() on primary output.
450 // Otherwise, create two audio patches for TX and RX path.
451 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700452 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700453 // If the TX device is also on the primary HW module, setOutputDevice() will take care
454 // of it due to legacy implementation. If not, create a patch.
455 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
456 == AUDIO_DEVICE_NONE) {
457 createTxPatch = true;
458 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700459 } else { // create RX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800460 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 createTxPatch = true;
462 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700463 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800464 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
465 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700466
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800467 return muteWaitMs;
468}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700469
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800470sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
471 bool isRx, audio_devices_t device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700472 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700473
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800474 sp<DeviceDescriptor> txSourceDeviceDesc;
475 if (isRx) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700476 patchBuilder.addSink(findDevice(mAvailableOutputDevices, device)).
477 addSource(findDevice(mAvailableInputDevices, AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800478 } else {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700479 patchBuilder.addSource(txSourceDeviceDesc = findDevice(mAvailableInputDevices, device)).
480 addSink(findDevice(mAvailableOutputDevices, AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800481 }
482
483 audio_devices_t outputDevice = isRx ? device : AUDIO_DEVICE_OUT_TELEPHONY_TX;
484 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(outputDevice, mOutputs);
485 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
486 // request to reuse existing output stream if one is already opened to reach the target device
487 if (output != AUDIO_IO_HANDLE_NONE) {
488 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
489 ALOG_ASSERT(!outputDesc->isDuplicated(),
490 "%s() %#x device output %d is duplicated", __func__, outputDevice, output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700491 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800492 }
493
494 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700495 // terminate active capture if on the same HW module as the call TX source device
496 // FIXME: would be better to refine to only inputs whose profile connects to the
497 // call TX device but this information is not in the audio patch and logic here must be
498 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800499 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800500 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700501 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700502 }
503 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700504 }
Eric Laurentdc462862016-07-19 12:29:53 -0700505
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800506 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700507 status_t status = mpClientInterface->createAudioPatch(
508 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800509 ALOGW_IF(status != NO_ERROR,
510 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
511 sp<AudioPatch> audioPatch;
512 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700513 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800514 audioPatch->mAfPatchHandle = afPatchHandle;
515 audioPatch->mUid = mUidCached;
516 }
517 return audioPatch;
518}
519
Mikhail Naganovdc769682018-05-04 15:34:08 -0700520sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100521 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700522 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700525 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700526}
527
Eric Laurente0720872014-03-11 09:30:41 -0700528void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700529{
530 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100531 // store previous phone state for management of sonification strategy below
532 int oldState = mEngine->getPhoneState();
533
534 if (mEngine->setPhoneState(state) != NO_ERROR) {
535 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700536 return;
537 }
François Gaffie2110e042015-03-24 08:41:51 +0100538 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700540 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700541 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800542 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700543 }
544
François Gaffie2110e042015-03-24 08:41:51 +0100545 /**
546 * Switching to or from incall state or switching between telephony and VoIP lead to force
547 * routing command.
548 */
549 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
550 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700551
552 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700553 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700554
Eric Laurente552edb2014-03-10 17:42:56 -0700555 int delayMs = 0;
556 if (isStateInCall(state)) {
557 nsecs_t sysTime = systemTime();
558 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700560 // mute media and sonification strategies and delay device switch by the largest
561 // latency of any output where either strategy is active.
562 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100563 if ((isStrategyActive(desc, STRATEGY_MEDIA,
564 SONIFICATION_HEADSET_MUSIC_DELAY,
565 sysTime) ||
566 isStrategyActive(desc, STRATEGY_SONIFICATION,
567 SONIFICATION_HEADSET_MUSIC_DELAY,
568 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700569 (delayMs < (int)desc->latency()*2)) {
570 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700571 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700572 setStrategyMute(STRATEGY_MEDIA, true, desc);
573 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700574 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700575 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
576 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700577 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
578 }
579 }
580
Eric Laurent87ffa392015-05-22 10:32:38 -0700581 if (hasPrimaryOutput()) {
582 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
583 // the device returned is not necessarily reachable via this output
584 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
585 // force routing command to audio hardware when ending call
586 // even if no device change is needed
587 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
588 rxDevice = mPrimaryOutput->device();
589 }
Eric Laurente552edb2014-03-10 17:42:56 -0700590
Eric Laurent87ffa392015-05-22 10:32:38 -0700591 if (state == AUDIO_MODE_IN_CALL) {
592 updateCallRouting(rxDevice, delayMs);
593 } else if (oldState == AUDIO_MODE_IN_CALL) {
594 if (mCallRxPatch != 0) {
595 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
596 mCallRxPatch.clear();
597 }
598 if (mCallTxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
600 mCallTxPatch.clear();
601 }
602 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
603 } else {
604 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700605 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700606 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700607
608 // reevaluate routing on all outputs in case tracks have been started during the call
609 for (size_t i = 0; i < mOutputs.size(); i++) {
610 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
611 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
612 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
Yung Ti Suf60c8242018-05-10 18:07:26 +0800613 setOutputDevice(desc, newDevice, (newDevice != AUDIO_DEVICE_NONE), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700614 }
615 }
616
Eric Laurente552edb2014-03-10 17:42:56 -0700617 if (isStateInCall(state)) {
618 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700619 // force reevaluating accessibility routing when call starts
620 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700621 }
622
623 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700624 if (state == AUDIO_MODE_RINGTONE &&
625 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700626 mLimitRingtoneVolume = true;
627 } else {
628 mLimitRingtoneVolume = false;
629 }
630}
631
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700632audio_mode_t AudioPolicyManager::getPhoneState() {
633 return mEngine->getPhoneState();
634}
635
Eric Laurente0720872014-03-11 09:30:41 -0700636void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700638{
François Gaffie2110e042015-03-24 08:41:51 +0100639 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700640 if (config == mEngine->getForceUse(usage)) {
641 return;
642 }
Eric Laurente552edb2014-03-10 17:42:56 -0700643
François Gaffie2110e042015-03-24 08:41:51 +0100644 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
645 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
646 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700647 }
François Gaffie2110e042015-03-24 08:41:51 +0100648 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
649 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700651
652 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700653 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800654
Eric Laurentdc462862016-07-19 12:29:53 -0700655 //FIXME: workaround for truncated touch sounds
656 // to be removed when the problem is handled by system UI
657 uint32_t delayMs = 0;
658 uint32_t waitMs = 0;
659 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
660 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
661 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700663 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700664 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665 }
Eric Laurente552edb2014-03-10 17:42:56 -0700666 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700667 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
668 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
669 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700670 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
671 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700672 }
Eric Laurente552edb2014-03-10 17:42:56 -0700673 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700674 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700675 }
676 }
677
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800678 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800679 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700680 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 if (activeDesc->mProfile->getSupportedDevices().types() &
682 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
683 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700684 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800685 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700686 }
Eric Laurente552edb2014-03-10 17:42:56 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688}
689
Eric Laurente0720872014-03-11 09:30:41 -0700690void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700691{
692 ALOGV("setSystemProperty() property %s, value %s", property, value);
693}
694
695// Find a direct output profile compatible with the parameters passed, even if the input flags do
696// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800697sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700698 audio_devices_t device,
699 uint32_t samplingRate,
700 audio_format_t format,
701 audio_channel_mask_t channelMask,
702 audio_output_flags_t flags)
703{
Eric Laurent861a6282015-05-18 15:40:16 -0700704 // only retain flags that will drive the direct output profile selection
705 // if explicitly requested
706 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700707 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
708 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700709 flags =
710 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
711
712 sp<IOProfile> profile;
713
Mikhail Naganovd4120142017-12-06 15:49:22 -0800714 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800715 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent861a6282015-05-18 15:40:16 -0700716 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700717 samplingRate, NULL /*updatedSamplingRate*/,
718 format, NULL /*updatedFormat*/,
719 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700720 flags)) {
721 continue;
722 }
723 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100724 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700725 continue;
726 }
727 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700734 }
Eric Laurente552edb2014-03-10 17:42:56 -0700735 }
736 }
Eric Laurent861a6282015-05-18 15:40:16 -0700737 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700738}
739
Eric Laurentf4e63452017-11-06 19:31:46 +0000740audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700741{
Eric Laurent3b73df72014-03-11 09:06:29 -0700742 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700743 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800744
745 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
746 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
747 // format, flags, etc. This may result in some discrepancy for functions that utilize
748 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
749 // and AudioSystem::getOutputSamplingRate().
750
Eric Laurentf4e63452017-11-06 19:31:46 +0000751 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
752 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700753
Eric Laurentf4e63452017-11-06 19:31:46 +0000754 ALOGV("getOutput() stream %d selected device %08x, output %d", stream, device, output);
755 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700756}
757
Eric Laurente83b55d2014-11-14 10:06:21 -0800758status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
759 audio_io_handle_t *output,
760 audio_session_t session,
761 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700762 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800763 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200764 audio_output_flags_t *flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700765 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800766 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700767{
Eric Laurente83b55d2014-11-14 10:06:21 -0800768 audio_attributes_t attributes;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700769 DeviceVector outputDevices;
770 routing_strategy strategy;
771 audio_devices_t device;
Eric Laurent97ac8712018-07-27 18:59:02 -0700772 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100773 audio_devices_t msdDevice = getMsdAudioOutDeviceTypes();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700774
Eric Laurent8f42ea12018-08-08 09:08:25 -0700775 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
776 if (*portId != AUDIO_PORT_HANDLE_NONE) {
777 return INVALID_OPERATION;
778 }
779
Eric Laurente83b55d2014-11-14 10:06:21 -0800780 if (attr != NULL) {
781 if (!isValidAttributes(attr)) {
782 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
783 attr->usage, attr->content_type, attr->flags,
784 attr->tags);
785 return BAD_VALUE;
786 }
787 attributes = *attr;
788 } else {
789 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
790 ALOGE("getOutputForAttr(): invalid stream type");
791 return BAD_VALUE;
792 }
793 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700794 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800795
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700796 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700797 " session %d selectedDeviceId %d",
798 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
799 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700800
Eric Laurent97ac8712018-07-27 18:59:02 -0700801 *stream = streamTypefromAttributesInt(&attributes);
802
803 strategy = getStrategyForAttr(&attributes);
804
Scott Randolph7b1fd232018-06-18 15:33:03 -0700805 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700806 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
807 sp<DeviceDescriptor> deviceDesc =
808 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
809 device = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700810 } else {
811 // If no explict route, is there a matching dynamic policy that applies?
812 sp<SwAudioOutputDescriptor> desc;
813 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
814 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
815 if (!audio_has_proportional_frames(config->format)) {
816 return BAD_VALUE;
817 }
818 *stream = streamTypefromAttributesInt(&attributes);
819 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700820 AudioMix *mix = desc->mPolicyMix;
821 sp<DeviceDescriptor> deviceDesc =
822 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
823 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700824 ALOGV("getOutputForAttr() returns output %d", *output);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700825 goto exit;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700826 }
827
828 // Virtual sources must always be dynamicaly or explicitly routed
829 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
830 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
831 return BAD_VALUE;
832 }
Eric Laurent97ac8712018-07-27 18:59:02 -0700833 device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700834 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700835
Eric Laurente83b55d2014-11-14 10:06:21 -0800836 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200837 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700838 }
839
Nadav Barb2f18162018-07-18 13:01:53 +0300840 // Set incall music only if device was explicitly set, and fallback to the device which is
841 // chosen by the engine if not.
842 // FIXME: provide a more generic approach which is not device specific and move this back
843 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200844 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
Nadav Barb2f18162018-07-18 13:01:53 +0300845 if (device == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Nadav Bar20919492018-11-20 10:20:51 +0200846 (*stream == AUDIO_STREAM_MUSIC || attributes.usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300847 audio_is_linear_pcm(config->format) &&
848 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700849 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300850 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
851 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700852 // Get the devce type directly from the engine to bypass preferred route logic
Nadav Barb2f18162018-07-18 13:01:53 +0300853 device = mEngine->getDeviceForStrategy(strategy);
854 }
855 }
856
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800857 ALOGV("getOutputForAttr() device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
858 "flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +0200859 device, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700860
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100861 *output = AUDIO_IO_HANDLE_NONE;
862 if (msdDevice != AUDIO_DEVICE_NONE) {
863 *output = getOutputForDevice(msdDevice, session, *stream, config, flags);
864 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
865 ALOGV("%s() Using MSD device 0x%x instead of device 0x%x",
866 __func__, msdDevice, device);
867 device = msdDevice;
868 } else {
869 *output = AUDIO_IO_HANDLE_NONE;
870 }
871 }
872 if (*output == AUDIO_IO_HANDLE_NONE) {
873 *output = getOutputForDevice(device, session, *stream, config, flags);
874 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800875 if (*output == AUDIO_IO_HANDLE_NONE) {
876 return INVALID_OPERATION;
877 }
Paul McLeanaa981192015-03-21 09:55:15 -0700878
Eric Laurent8fc147b2018-07-22 19:13:55 -0700879 outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -0700880 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
881 : AUDIO_PORT_HANDLE_NONE;
882
Eric Laurent8fc147b2018-07-22 19:13:55 -0700883exit:
884 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
885 .format = config->format,
886 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700887 *portId = AudioPort::getNextUniqueId();
888
Eric Laurent8fc147b2018-07-22 19:13:55 -0700889 sp<TrackClientDescriptor> clientDesc =
Eric Laurent97ac8712018-07-27 18:59:02 -0700890 new TrackClientDescriptor(*portId, uid, session, attributes, clientConfig,
891 requestedDeviceId, *stream,
892 getStrategyForAttr(&attributes),
893 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700894 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700895 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700896
897 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d for port ID %d",
898 *output, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700899
Eric Laurente83b55d2014-11-14 10:06:21 -0800900 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700901}
902
903audio_io_handle_t AudioPolicyManager::getOutputForDevice(
904 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800905 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700906 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800907 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200908 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700909{
Andy Hungc88b0642018-04-27 15:42:35 -0700910 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912
Eric Laurente552edb2014-03-10 17:42:56 -0700913 // open a direct output if required by specified parameters
914 //force direct flag if offload flag is set: offloading implies a direct output stream
915 // and all common behaviors are driven by checking only the direct flag
916 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200917 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
918 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
Nadav Bar766fb022018-01-07 12:18:03 +0200920 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
921 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700922 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800923 // only allow deep buffering for music stream type
924 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200925 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700926 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200927 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700928 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
929 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200930 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800931 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700932 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200933 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700934 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200935 audio_is_linear_pcm(config->format) &&
936 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200937 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700938 AUDIO_OUTPUT_FLAG_DIRECT);
939 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700940 }
Eric Laurente552edb2014-03-10 17:42:56 -0700941
Nadav Bar766fb022018-01-07 12:18:03 +0200942
Eric Laurentb732cf52014-09-24 19:08:21 -0700943 sp<IOProfile> profile;
944
945 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700946 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +0200947 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -0800948 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
949 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -0700950 goto non_direct_output;
951 }
952
Andy Hung2ddee192015-12-18 17:34:44 -0800953 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
954 // This prevents creating an offloaded track and tearing it down immediately after start
955 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700956 // FIXME: We should check the audio session here but we do not have it in this context.
957 // This may prevent offloading in rare situations where effects are left active by apps
958 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700959
Nadav Bar766fb022018-01-07 12:18:03 +0200960 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800961 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700962 profile = getProfileForDirectOutput(device,
Eric Laurentfe231122017-11-17 17:48:06 -0800963 config->sample_rate,
964 config->format,
965 config->channel_mask,
Nadav Bar766fb022018-01-07 12:18:03 +0200966 (audio_output_flags_t)*flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968
Eric Laurent1c333e22014-05-20 10:48:17 -0700969 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -0700970 // exclusive outputs for MMAP and Offload are enforced by different session ids.
971 for (size_t i = 0; i < mOutputs.size(); i++) {
972 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
973 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
974 // reuse direct output if currently open by the same client
975 // and configured with same parameters
976 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -0700977 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -0700978 (config->channel_mask == desc->mChannelMask) &&
979 (session == desc->mDirectClientSession)) {
980 desc->mDirectOpenCount++;
981 ALOGI("getOutputForDevice() reusing direct output %d for session %d",
982 mOutputs.keyAt(i), session);
983 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
985 }
986 }
Eric Laurent3974e3b2017-12-07 17:58:43 -0800987
988 if (!profile->canOpenNewIo()) {
989 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -0700990 }
Eric Laurent861a6282015-05-18 15:40:16 -0700991
Eric Laurent3974e3b2017-12-07 17:58:43 -0800992 sp<SwAudioOutputDescriptor> outputDesc =
993 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -0800994
Mikhail Naganov708e0382018-05-30 09:53:04 -0700995 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -0800996 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
997 : String8("");
998
Dean Wheatley3023b382018-08-09 07:42:40 +1000999 // MSD patch may be using the only output stream that can service this request. Release
1000 // MSD patch to prioritize this request over any active output on MSD.
1001 AudioPatchCollection msdPatches = getMsdPatches();
1002 for (size_t i = 0; i < msdPatches.size(); i++) {
1003 const auto& patch = msdPatches[i];
1004 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1005 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1006 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1007 (sink->ext.device.type & device) != AUDIO_DEVICE_NONE &&
1008 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1009 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1010 releaseAudioPatch(patch->mHandle, mUidCached);
1011 break;
1012 }
1013 }
1014 }
1015
Nadav Bar766fb022018-01-07 12:18:03 +02001016 status = outputDesc->open(config, device, address, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001017
1018 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001020 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001021 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001022 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
1023 ALOGV("getOutputForDevice() failed opening direct output: output %d sample rate %d %d,"
1024 "format %d %d, channel mask %04x %04x", output, config->sample_rate,
1025 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1026 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001027 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001028 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001030 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001031 if (audio_is_linear_pcm(config->format) &&
1032 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001033 goto non_direct_output;
1034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001036 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001037 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001038 outputDesc->mDirectClientSession = session;
1039
Eric Laurente552edb2014-03-10 17:42:56 -07001040 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001041 mPreviousOutputs = mOutputs;
Eric Laurentf4e63452017-11-06 19:31:46 +00001042 ALOGV("getOutputForDevice() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001043 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001044 return output;
1045 }
1046
Eric Laurentb732cf52014-09-24 19:08:21 -07001047non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001048
1049 // A request for HW A/V sync cannot fallback to a mixed output because time
1050 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001051 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001052 return AUDIO_IO_HANDLE_NONE;
1053 }
1054
Eric Laurente552edb2014-03-10 17:42:56 -07001055 // ignoring channel mask due to downmix capability in mixer
1056
1057 // open a non direct output
1058
1059 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001060 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // get which output is suitable for the specified stream. The actual
1062 // routing change will happen when startOutput() will be called
1063 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1064
Eric Laurent8838a382014-09-08 16:44:28 -07001065 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001066 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1067 output = selectOutput(outputs, *flags, config->format);
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
Eric Laurentf4e63452017-11-06 19:31:46 +00001069 ALOGW_IF((output == 0), "getOutputForDevice() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001070 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001071 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001072
Eric Laurente552edb2014-03-10 17:42:56 -07001073 return output;
1074}
1075
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001076sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001077 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001078 if (msdModule != 0) {
1079 DeviceVector msdInputDevices = mAvailableInputDevices.getDevicesFromHwModule(
1080 msdModule->getHandle());
1081 if (!msdInputDevices.isEmpty()) return msdInputDevices.itemAt(0);
1082 }
1083 return 0;
1084}
1085
1086audio_devices_t AudioPolicyManager::getMsdAudioOutDeviceTypes() const {
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001087 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001088 if (msdModule != 0) {
1089 return mAvailableOutputDevices.getDeviceTypesFromHwModule(msdModule->getHandle());
1090 }
1091 return AUDIO_DEVICE_NONE;
1092}
1093
1094const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1095 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001096 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1097 if (msdModule != 0) {
1098 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1099 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1100 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1101 const struct audio_port_config *source = &patch->mPatch.sources[j];
1102 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1103 source->ext.device.hw_module == msdModule->getHandle()) {
1104 msdPatches.addAudioPatch(patch->mHandle, patch);
1105 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001106 }
1107 }
1108 }
1109 return msdPatches;
1110}
1111
1112status_t AudioPolicyManager::getBestMsdAudioProfileFor(audio_devices_t outputDevice,
1113 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1114{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001115 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001116 if (msdModule == nullptr) {
1117 ALOGE("%s() unable to get MSD module", __func__);
1118 return NO_INIT;
1119 }
1120 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1121 if (deviceModule == nullptr) {
1122 ALOGE("%s() unable to get module for %#x", __func__, outputDevice);
1123 return NO_INIT;
1124 }
1125 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1126 if (inputProfiles.isEmpty()) {
1127 ALOGE("%s() no input profiles for MSD module", __func__);
1128 return NO_INIT;
1129 }
1130 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1131 if (outputProfiles.isEmpty()) {
1132 ALOGE("%s() no output profiles for device %#x", __func__, outputDevice);
1133 return NO_INIT;
1134 }
1135 AudioProfileVector msdProfiles;
1136 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1137 for (const auto &inProfile : inputProfiles) {
1138 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1139 msdProfiles.appendVector(inProfile->getAudioProfiles());
1140 }
1141 }
1142 AudioProfileVector deviceProfiles;
1143 for (const auto &outProfile : outputProfiles) {
1144 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1145 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1146 }
1147 }
1148 struct audio_config_base bestSinkConfig;
1149 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1150 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1151 &bestSinkConfig);
1152 if (result != NO_ERROR) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001153 ALOGD("%s() no matching profiles found for device: %#x, hwAvSync: %d",
1154 __func__, outputDevice, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001155 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001156 }
1157 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1158 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1159 sinkConfig->format = bestSinkConfig.format;
1160 // For encoded streams force direct flag to prevent downstream mixing.
1161 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1162 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1163 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1164 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1165 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1166 sourceConfig->format = bestSinkConfig.format;
1167 // Copy input stream directly without any processing (e.g. resampling).
1168 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1169 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1170 if (hwAvSync) {
1171 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1172 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1173 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1174 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1175 }
1176 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1177 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1178 sinkConfig->config_mask |= config_mask;
1179 sourceConfig->config_mask |= config_mask;
1180 return NO_ERROR;
1181}
1182
1183PatchBuilder AudioPolicyManager::buildMsdPatch(audio_devices_t outputDevice) const
1184{
1185 PatchBuilder patchBuilder;
1186 patchBuilder.addSource(getMsdAudioInDevice()).
1187 addSink(findDevice(mAvailableOutputDevices, outputDevice));
1188 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1189 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1190 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1191 // For now, we just forcefully try with HwAvSync first.
1192 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1193 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1194 getBestMsdAudioProfileFor(
1195 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1196 if (res == NO_ERROR) {
1197 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1198 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1199 }
1200 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1201 " supporting PCM format conversion.", __func__);
1202 return patchBuilder;
1203}
1204
1205status_t AudioPolicyManager::setMsdPatch(audio_devices_t outputDevice) {
1206 ALOGV("%s() for outputDevice %#x", __func__, outputDevice);
1207 if (outputDevice == AUDIO_DEVICE_NONE) {
1208 // Use media strategy for unspecified output device. This should only
1209 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1210 // therefore invalidate explicit routing requests.
1211 outputDevice = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1212 }
1213 PatchBuilder patchBuilder = buildMsdPatch(outputDevice);
1214 const struct audio_patch* patch = patchBuilder.patch();
1215 const AudioPatchCollection msdPatches = getMsdPatches();
1216 if (!msdPatches.isEmpty()) {
1217 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1218 "The current MSD prototype only supports one output patch");
1219 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1220 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1221 return NO_ERROR;
1222 }
1223 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1224 }
1225 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1226 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1227 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1228 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1229 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__, outputDevice,
1230 patch->sources[0].format, patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1231 return status;
1232}
1233
Eric Laurente0720872014-03-11 09:30:41 -07001234audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001235 audio_output_flags_t flags,
1236 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001237{
1238 // select one output among several that provide a path to a particular device or set of
1239 // devices (the list was previously build by getOutputsForDevice()).
1240 // The priority is as follows:
1241 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001242 // 2: the output with the bit depth the closest to the requested one
1243 // 3: the primary output
1244 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001245
1246 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001247 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001248 }
1249 if (outputs.size() == 1) {
1250 return outputs[0];
1251 }
1252
1253 int maxCommonFlags = 0;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001254 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1255 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1256 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001257 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1258 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001259
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001260 for (audio_io_handle_t output : outputs) {
1261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001262 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001263 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1264 continue;
1265 }
Eric Laurent8838a382014-09-08 16:44:28 -07001266 // if a valid format is specified, skip output if not compatible
1267 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001268 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001269 continue;
1270 }
Eric Laurente6930022016-02-11 10:20:40 -08001271 if (AudioPort::isBetterFormatMatch(
1272 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001273 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001274 bestFormat = outputDesc->mFormat;
1275 }
Eric Laurent8838a382014-09-08 16:44:28 -07001276 }
1277
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001278 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001279 if (commonFlags >= maxCommonFlags) {
1280 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001281 if (format != AUDIO_FORMAT_INVALID
1282 && AudioPort::isBetterFormatMatch(
1283 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001284 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001285 bestFormatForFlags = outputDesc->mFormat;
1286 }
1287 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001288 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001289 maxCommonFlags = commonFlags;
1290 bestFormatForFlags = outputDesc->mFormat;
1291 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001292 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001293 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001294 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001295 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001296 }
1297 }
1298 }
1299
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001300 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001301 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001302 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001303 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001304 return outputForFormat;
1305 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001306 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001307 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
1309
1310 return outputs[0];
1311}
1312
Eric Laurent8fc147b2018-07-22 19:13:55 -07001313status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001314{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001315 ALOGV("%s portId %d", __FUNCTION__, portId);
1316
1317 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1318 if (outputDesc == 0) {
1319 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001320 return BAD_VALUE;
1321 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001322 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001323
Eric Laurent8fc147b2018-07-22 19:13:55 -07001324 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001325 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001326
Eric Laurent733ce942017-12-07 12:18:25 -08001327 status_t status = outputDesc->start();
1328 if (status != NO_ERROR) {
1329 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001330 }
1331
Eric Laurent97ac8712018-07-27 18:59:02 -07001332 uint32_t delayMs;
1333 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001334
1335 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001336 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001337 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001338 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001339 if (delayMs != 0) {
1340 usleep(delayMs * 1000);
1341 }
1342
1343 return status;
1344}
1345
Eric Laurent97ac8712018-07-27 18:59:02 -07001346status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1347 const sp<TrackClientDescriptor>& client,
1348 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001349{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001350 // cannot start playback of STREAM_TTS if any other output is being used
1351 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001352
1353 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001354 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001355 if (stream == AUDIO_STREAM_TTS) {
1356 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001357 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001358 return INVALID_OPERATION;
1359 } else {
1360 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1361 }
1362 } else {
1363 // some playback other than beacon starts
1364 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1365 }
1366
Eric Laurent77305a62016-07-25 16:39:22 -07001367 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001368 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001369 bool force = !outputDesc->isActive() &&
1370 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001371
Eric Laurent97ac8712018-07-27 18:59:02 -07001372 audio_devices_t device = AUDIO_DEVICE_NONE;
1373 AudioMix *policyMix = NULL;
1374 const char *address = NULL;
1375 if (outputDesc->mPolicyMix != NULL) {
1376 policyMix = outputDesc->mPolicyMix;
1377 address = policyMix->mDeviceAddress.string();
1378 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1379 device = policyMix->mDeviceType;
1380 } else {
1381 device = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1382 }
1383 }
1384
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001385 // requiresMuteCheck is false when we can bypass mute strategy.
1386 // It covers a common case when there is no materially active audio
1387 // and muting would result in unnecessary delay and dropped audio.
1388 const uint32_t outputLatencyMs = outputDesc->latency();
1389 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1390
Eric Laurente552edb2014-03-10 17:42:56 -07001391 // increment usage count for this stream on the requested output:
1392 // NOTE that the usage count is the same for duplicated output and hardware output which is
1393 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001394 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001395
1396 if (client->hasPreferredDevice(true)) {
1397 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
1398 if (device != outputDesc->device()) {
1399 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1400 }
1401 }
Eric Laurente552edb2014-03-10 17:42:56 -07001402
Eric Laurent36829f92017-04-07 19:04:42 -07001403 if (stream == AUDIO_STREAM_MUSIC) {
1404 selectOutputForMusicEffects();
1405 }
1406
Eric Laurent592dd7b2018-08-05 18:58:48 -07001407 if (outputDesc->streamActiveCount(stream) == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001408 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001409 if (device == AUDIO_DEVICE_NONE) {
1410 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001411 }
Eric Laurent36829f92017-04-07 19:04:42 -07001412
Eric Laurente552edb2014-03-10 17:42:56 -07001413 routing_strategy strategy = getStrategy(stream);
1414 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001415 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1416 (beaconMuteLatency > 0);
1417 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001418 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001420 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001421 // An output has a shared device if
1422 // - managed by the same hw module
1423 // - supports the currently selected device
1424 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1425 && (desc->supportedDevices() & device) != AUDIO_DEVICE_NONE;
1426
Eric Laurent77305a62016-07-25 16:39:22 -07001427 // force a device change if any other output is:
1428 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001429 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001430 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001431 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001432 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001433 // change the device currently selected by the other output.
1434 if (sharedDevice &&
Eric Laurent77305a62016-07-25 16:39:22 -07001435 desc->device() != device &&
Eric Laurent77305a62016-07-25 16:39:22 -07001436 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001437 force = true;
1438 }
1439 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001440 // a notification so that audio focus effect can propagate, or that a mute/unmute
1441 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001442 const uint32_t latencyMs = desc->latency();
1443 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1444
1445 if (shouldWait && isActive && (waitMs < latencyMs)) {
1446 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001447 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001448
1449 // Require mute check if another output is on a shared device
1450 // and currently active to have proper drain and avoid pops.
1451 // Note restoring AudioTracks onto this output needs to invoke
1452 // a volume ramp if there is no mute.
1453 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001454 }
1455 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001456
1457 const uint32_t muteWaitMs =
1458 setOutputDevice(outputDesc, device, force, 0, NULL, address, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001459
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // apply volume rules for current stream and device if necessary
1461 checkAndSetVolume(stream,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001462 mVolumeCurves->getVolumeIndex(stream, outputDesc->device()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001463 outputDesc,
Shuhei Miyazaki6fe70332017-07-31 15:21:28 +09001464 outputDesc->device());
Eric Laurente552edb2014-03-10 17:42:56 -07001465
1466 // update the outputs if starting an output with a stream that can affect notification
1467 // routing
1468 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001469
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001470 // force reevaluating accessibility routing when ringtone or alarm starts
1471 if (strategy == STRATEGY_SONIFICATION) {
1472 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1473 }
Eric Laurentdc462862016-07-19 12:29:53 -07001474
1475 if (waitMs > muteWaitMs) {
1476 *delayMs = waitMs - muteWaitMs;
1477 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001478
1479 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1480 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1481 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1482 // change occurs after the MixerThread starts and causes a stream volume
1483 // glitch.
1484 //
1485 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
Eric Laurentdc462862016-07-19 12:29:53 -07001487
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001488 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1489 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1490 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1491 }
1492
Eric Laurent97ac8712018-07-27 18:59:02 -07001493 // Automatically enable the remote submix input when output is started on a re routing mix
1494 // of type MIX_TYPE_RECORDERS
1495 if (audio_is_remote_submix_device(device) && policyMix != NULL &&
1496 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1498 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1499 address,
1500 "remote-submix");
1501 }
1502
Eric Laurente552edb2014-03-10 17:42:56 -07001503 return NO_ERROR;
1504}
1505
Eric Laurent8fc147b2018-07-22 19:13:55 -07001506status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001507{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001508 ALOGV("%s portId %d", __FUNCTION__, portId);
1509
1510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1511 if (outputDesc == 0) {
1512 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 return BAD_VALUE;
1514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001515 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Eric Laurent97ac8712018-07-27 18:59:02 -07001517 ALOGV("stopOutput() output %d, stream %d, session %d",
1518 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001519
Eric Laurent97ac8712018-07-27 18:59:02 -07001520 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001521
Eric Laurent733ce942017-12-07 12:18:25 -08001522 if (status == NO_ERROR ) {
1523 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001524 }
1525 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001526}
1527
Eric Laurent97ac8712018-07-27 18:59:02 -07001528status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1529 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001530{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001531 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001532 audio_stream_type_t stream = client->stream();
1533
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001534 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1535
Eric Laurent592dd7b2018-08-05 18:58:48 -07001536 if (outputDesc->streamActiveCount(stream) > 0) {
1537 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001538 // Automatically disable the remote submix input when output is stopped on a
1539 // re routing mix of type MIX_TYPE_RECORDERS
1540 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1541 outputDesc->mPolicyMix != NULL &&
1542 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1543 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1544 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1545 outputDesc->mPolicyMix->mDeviceAddress,
1546 "remote-submix");
1547 }
1548 }
1549 bool forceDeviceUpdate = false;
1550 if (client->hasPreferredDevice(true)) {
1551 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1552 forceDeviceUpdate = true;
1553 }
1554
Eric Laurente552edb2014-03-10 17:42:56 -07001555 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001556 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001557
Eric Laurente552edb2014-03-10 17:42:56 -07001558 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001559 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001560 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001561 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001562 // delay the device switch by twice the latency because stopOutput() is executed when
1563 // the track stop() command is received and at that time the audio track buffer can
1564 // still contain data that needs to be drained. The latency only covers the audio HAL
1565 // and kernel buffers. Also the latency does not always include additional delay in the
1566 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001567 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001568
1569 // force restoring the device selection on other active outputs if it differs from the
1570 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001571 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001572 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001573 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001574 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001575 desc->isActive() &&
1576 outputDesc->sharesHwModuleWith(desc) &&
1577 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001578 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1579 bool force = desc->device() != newDevice2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001580
Eric Laurentc75307b2015-03-17 15:29:32 -07001581 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001582 newDevice2,
1583 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001584 delayMs);
1585 // re-apply device specific volume if not done by setOutputDevice()
1586 if (!force) {
1587 applyStreamVolumes(desc, newDevice2, delayMs);
1588 }
Eric Laurente552edb2014-03-10 17:42:56 -07001589 }
1590 }
1591 // update the outputs if stopping one with a stream that can affect notification routing
1592 handleNotificationRoutingForStream(stream);
1593 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001594
1595 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1596 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1597 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1598 }
1599
Eric Laurent36829f92017-04-07 19:04:42 -07001600 if (stream == AUDIO_STREAM_MUSIC) {
1601 selectOutputForMusicEffects();
1602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603 return NO_ERROR;
1604 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001605 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001606 return INVALID_OPERATION;
1607 }
1608}
1609
Eric Laurent8fc147b2018-07-22 19:13:55 -07001610void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001611{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001612 ALOGV("%s portId %d", __FUNCTION__, portId);
1613
1614 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1615 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001616 // If an output descriptor is closed due to a device routing change,
1617 // then there are race conditions with releaseOutput from tracks
1618 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1619 // destroyed shortly thereafter.
1620 //
1621 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001622 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001623 return;
1624 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001625
1626 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1629 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001630 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001631 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001632 return;
1633 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001634 if (--outputDesc->mDirectOpenCount == 0) {
1635 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001636 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001637 }
1638 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001639 // stopOutput() needs to be successfully called before releaseOutput()
1640 // otherwise there may be inaccurate stream reference counts.
1641 // This is checked in outputDesc->removeClient below.
1642 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001643}
1644
Eric Laurentcaf7f482014-11-25 17:50:47 -08001645status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1646 audio_io_handle_t *input,
1647 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001648 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001649 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001650 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001651 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001652 input_type_t *inputType,
1653 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001654{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001655 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001656 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001657 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
Eric Laurentad2e7b92017-09-14 20:06:42 -07001659 status_t status = NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -08001660 // handle legacy remote submix case where the address was not always specified
1661 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001662 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001663 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001664 AudioMix *policyMix = NULL;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001665 DeviceVector inputDevices;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001666 sp<AudioInputDescriptor> inputDesc;
1667 sp<RecordClientDescriptor> clientDesc;
1668 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001669 bool isSoundTrigger;
1670 audio_devices_t device;
1671
1672 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1673 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1674 return INVALID_OPERATION;
1675 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001676
Eric Laurentfe231122017-11-17 17:48:06 -08001677 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1678 inputSource = AUDIO_SOURCE_MIC;
1679 }
1680
Paul McLean466dc8e2015-04-17 13:15:36 -06001681 // Explicit routing?
1682 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001683 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
jiabinc0c831a2018-01-29 17:55:15 -08001684 deviceDesc = mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001685 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001686
Eric Laurentad2e7b92017-09-14 20:06:42 -07001687 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1688 // possible
1689 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1690 *input != AUDIO_IO_HANDLE_NONE) {
1691 ssize_t index = mInputs.indexOfKey(*input);
1692 if (index < 0) {
1693 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1694 status = BAD_VALUE;
1695 goto error;
1696 }
1697 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001698 RecordClientVector clients = inputDesc->getClientsForSession(session);
1699 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001700 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1701 status = BAD_VALUE;
1702 goto error;
1703 }
1704 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1705 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001706 // corresponds to a new client and is only permitted from the same UID.
1707 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001708 if (clients.size() > 1) {
1709 for (const auto& client : clients) {
1710 // The client map is ordered by key values (portId) and portIds are allocated
1711 // incrementaly. So the first client in this list is the one opened by audio flinger
1712 // when the mmap stream is created and should be ignored as it does not correspond
1713 // to an actual client
1714 if (client == *clients.cbegin()) {
1715 continue;
1716 }
1717 if (uid != client->uid() && !client->isSilenced()) {
1718 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1719 uid, client->portId(), client->uid());
1720 status = INVALID_OPERATION;
1721 goto error;
1722 }
Eric Laurent331679c2018-04-16 17:03:16 -07001723 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001724 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001725 *inputType = API_INPUT_LEGACY;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001726 device = inputDesc->mDevice;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001727
Eric Laurent8f42ea12018-08-08 09:08:25 -07001728 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001729 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001730 }
1731
1732 *input = AUDIO_IO_HANDLE_NONE;
1733 *inputType = API_INPUT_INVALID;
1734
Eric Laurentad2e7b92017-09-14 20:06:42 -07001735 halInputSource = inputSource;
1736
Eric Laurentc447ded2015-01-06 08:47:05 -08001737 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001738 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001739 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1740 if (status != NO_ERROR) {
1741 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001742 }
1743 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001744 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1745 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001746 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -07001747 if (deviceDesc != 0) {
1748 device = deviceDesc->type();
1749 } else {
1750 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1751 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001752 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001753 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001754 status = BAD_VALUE;
1755 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001756 }
Eric Laurentc722f302014-12-10 11:21:49 -08001757 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001758 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001759 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1760 // there is an external policy, but this input is attached to a mix of recorders,
1761 // meaning it receives audio injected into the framework, so the recorder doesn't
1762 // know about it and is therefore considered "legacy"
1763 *inputType = API_INPUT_LEGACY;
1764 } else {
1765 // recording a mix of players defined by an external policy, we're rerouting for
1766 // an external policy
1767 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1768 }
Eric Laurentc722f302014-12-10 11:21:49 -08001769 } else if (audio_is_remote_submix_device(device)) {
1770 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001771 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001772 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1773 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001774 } else {
1775 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001776 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001777
Eric Laurent599c7582015-12-07 18:05:55 -08001778 }
1779
Eric Laurent8f42ea12018-08-08 09:08:25 -07001780 *input = getInputForDevice(device, address, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001781 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001782 policyMix);
1783 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001784 status = INVALID_OPERATION;
1785 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001786 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001787
Eric Laurent8f42ea12018-08-08 09:08:25 -07001788exit:
1789
Mikhail Naganov708e0382018-05-30 09:53:04 -07001790 inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent2ac76942017-06-22 17:17:09 -07001791 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
Eric Laurent8f42ea12018-08-08 09:08:25 -07001792 : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001793
Eric Laurent8f42ea12018-08-08 09:08:25 -07001794 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1795 mSoundTriggerSessions.indexOfKey(session) > 0;
1796 *portId = AudioPort::getNextUniqueId();
1797
Eric Laurent8fc147b2018-07-22 19:13:55 -07001798 clientDesc = new RecordClientDescriptor(*portId, uid, session,
Eric Laurent8f42ea12018-08-08 09:08:25 -07001799 *attr, *config, requestedDeviceId,
1800 inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001801 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001802 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001803
1804 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1805 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001806
Eric Laurent599c7582015-12-07 18:05:55 -08001807 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808
1809error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001811}
1812
1813
1814audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1815 String8 address,
1816 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001817 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001818 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001819 audio_input_flags_t flags,
1820 AudioMix *policyMix)
1821{
1822 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1823 audio_source_t halInputSource = inputSource;
1824 bool isSoundTrigger = false;
1825
1826 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1827 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1828 if (index >= 0) {
1829 input = mSoundTriggerSessions.valueFor(session);
1830 isSoundTrigger = true;
1831 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1832 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1833 } else {
1834 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001835 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001836 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001837 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001838 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001839 }
1840
Andy Hungf129b032015-04-07 13:45:50 -07001841 // find a compatible input profile (not necessarily identical in parameters)
1842 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001843 // sampling rate and flags may be updated by getInputProfile
1844 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1845 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001846 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001847 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001848 audio_input_flags_t profileFlags = flags;
1849 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001850 profileFormat = config->format; // reset each time through loop, in case it is updated
Eric Laurent275e8e92014-11-30 15:14:47 -08001851 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001852 profileSamplingRate, profileFormat, profileChannelMask,
1853 profileFlags);
1854 if (profile != 0) {
1855 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001856 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1857 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001858 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1859 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1860 } else { // fail
Glenn Kastenfaa10a62017-05-25 15:52:05 -07001861 ALOGW("getInputForDevice() could not find profile for device 0x%X, "
Eric Laurentfe231122017-11-17 17:48:06 -08001862 "sampling rate %u, format %#x, channel mask 0x%X, flags %#x",
1863 device, config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001864 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001865 }
Eric Laurente552edb2014-03-10 17:42:56 -07001866 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001867 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001868 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001869 if (samplingRate == 0) {
1870 samplingRate = profileSamplingRate;
1871 }
Eric Laurente552edb2014-03-10 17:42:56 -07001872
Eric Laurent322b4d22015-04-03 15:57:54 -07001873 if (profile->getModuleHandle() == 0) {
1874 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001875 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001876 }
1877
Eric Laurent3974e3b2017-12-07 17:58:43 -08001878 if (!profile->canOpenNewIo()) {
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001879 for (size_t i = 0; i < mInputs.size(); ) {
1880 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1881 if (desc->mProfile != profile) {
1882 continue;
1883 }
1884 // if sound trigger, reuse input if used by other sound trigger on same session
1885 // else
1886 // reuse input if active client app is not in IDLE state
1887 //
1888 RecordClientVector clients = desc->clientsList();
1889 bool doClose = false;
1890 for (const auto& client : clients) {
1891 if (isSoundTrigger != client->isSoundTrigger()) {
1892 continue;
1893 }
1894 if (client->isSoundTrigger()) {
1895 if (session == client->session()) {
1896 return desc->mIoHandle;
1897 }
1898 continue;
1899 }
1900 if (client->active() && client->appState() != APP_STATE_IDLE) {
1901 return desc->mIoHandle;
1902 }
1903 doClose = true;
1904 }
1905 if (doClose) {
1906 closeInput(desc->mIoHandle);
1907 } else {
1908 i++;
1909 }
1910 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001911 }
1912
Eric Laurentfe231122017-11-17 17:48:06 -08001913 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001914
Eric Laurentfe231122017-11-17 17:48:06 -08001915 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1916 lConfig.sample_rate = profileSamplingRate;
1917 lConfig.channel_mask = profileChannelMask;
1918 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001919
Eric Laurent53b810e2017-12-10 17:25:10 -08001920 if (address == "") {
Mikhail Naganov708e0382018-05-30 09:53:04 -07001921 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent53b810e2017-12-10 17:25:10 -08001922 // the inputs vector must be of size >= 1, but we don't want to crash here
1923 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1924 }
1925
Eric Laurentfe231122017-11-17 17:48:06 -08001926 status_t status = inputDesc->open(&lConfig, device, address,
1927 halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001928
1929 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001930 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001931 (profileSamplingRate != lConfig.sample_rate) ||
1932 !audio_formats_match(profileFormat, lConfig.format) ||
1933 (profileChannelMask != lConfig.channel_mask)) {
1934 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001935 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08001936 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001937 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001938 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07001939 }
Eric Laurent599c7582015-12-07 18:05:55 -08001940 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001941 }
1942
Eric Laurentc722f302014-12-10 11:21:49 -08001943 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001944
Eric Laurent599c7582015-12-07 18:05:55 -08001945 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001946 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001947
Eric Laurent599c7582015-12-07 18:05:55 -08001948 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001949}
1950
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001951status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08001952{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001953 ALOGV("%s portId %d", __FUNCTION__, portId);
1954
1955 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
1956 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07001957 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001958 return BAD_VALUE;
1959 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001960 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07001961 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001962 if (client->active()) {
1963 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
1964 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07001965 }
1966
Eric Laurent8f42ea12018-08-08 09:08:25 -07001967 audio_session_t session = client->session();
1968
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001969 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001970
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001971 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07001972
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001973 status_t status = inputDesc->start();
1974 if (status != NO_ERROR) {
1975 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07001976 }
Eric Laurente552edb2014-03-10 17:42:56 -07001977
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08001978 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08001979 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07001980 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08001981
Eric Laurent8f42ea12018-08-08 09:08:25 -07001982 // indicate active capture to sound trigger service if starting capture from a mic on
1983 // primary HW module
1984 audio_devices_t device = getNewInputDevice(inputDesc);
1985 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001986
Eric Laurent8f42ea12018-08-08 09:08:25 -07001987 if (inputDesc->activeCount() == 1) {
1988 // if input maps to a dynamic policy with an activity listener, notify of state change
1989 if ((inputDesc->mPolicyMix != NULL)
1990 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1991 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1992 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08001993 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001994
Eric Laurent8f42ea12018-08-08 09:08:25 -07001995 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1996 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1997 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
1998 SoundTrigger::setCaptureState(true);
1999 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002000
Eric Laurent8f42ea12018-08-08 09:08:25 -07002001 // automatically enable the remote submix output when input is started if not
2002 // used by a policy mix of type MIX_TYPE_RECORDERS
2003 // For remote submix (a virtual device), we open only one input per capture request.
2004 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2005 String8 address = String8("");
2006 if (inputDesc->mPolicyMix == NULL) {
2007 address = String8("0");
2008 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2009 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002010 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002011 if (address != "") {
2012 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2013 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2014 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002015 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002016 }
Eric Laurente552edb2014-03-10 17:42:56 -07002017 }
2018
Eric Laurent8f42ea12018-08-08 09:08:25 -07002019 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002020
Eric Laurente552edb2014-03-10 17:42:56 -07002021 return NO_ERROR;
2022}
2023
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002025{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 ALOGV("%s portId %d", __FUNCTION__, portId);
2027
2028 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2029 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002030 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002031 return BAD_VALUE;
2032 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002033 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002034 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002035 if (!client->active()) {
2036 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002037 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002038 }
2039
Eric Laurent8f42ea12018-08-08 09:08:25 -07002040 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002041
Eric Laurent8f42ea12018-08-08 09:08:25 -07002042 inputDesc->stop();
2043 if (inputDesc->isActive()) {
2044 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2045 } else {
2046 // if input maps to a dynamic policy with an activity listener, notify of state change
2047 if ((inputDesc->mPolicyMix != NULL)
2048 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2049 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2050 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002051 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002052
2053 // automatically disable the remote submix output when input is stopped if not
2054 // used by a policy mix of type MIX_TYPE_RECORDERS
2055 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2056 String8 address = String8("");
2057 if (inputDesc->mPolicyMix == NULL) {
2058 address = String8("0");
2059 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2060 address = inputDesc->mPolicyMix->mDeviceAddress;
2061 }
2062 if (address != "") {
2063 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2064 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2065 address, "remote-submix");
2066 }
2067 }
2068
2069 audio_devices_t device = inputDesc->mDevice;
2070 resetInputDevice(input);
2071
2072 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2073 // primary HW module
2074 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2075 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2076 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2077 SoundTrigger::setCaptureState(false);
2078 }
2079 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002080 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002081 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002082}
2083
Eric Laurent8fc147b2018-07-22 19:13:55 -07002084void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002085{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002086 ALOGV("%s portId %d", __FUNCTION__, portId);
2087
2088 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2089 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002090 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002091 return;
2092 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002093 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002094 audio_io_handle_t input = inputDesc->mIoHandle;
2095
Eric Laurent8f42ea12018-08-08 09:08:25 -07002096 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002097
Andy Hung39efb7a2018-09-26 15:39:28 -07002098 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002099
Andy Hung39efb7a2018-09-26 15:39:28 -07002100 if (inputDesc->getClientCount() > 0) {
2101 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002102 return;
2103 }
2104
Eric Laurent05b90f82014-08-27 15:32:29 -07002105 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002106 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002107 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002108}
2109
Eric Laurent8f42ea12018-08-08 09:08:25 -07002110void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002111{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002112 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002113
2114 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002115 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002116 }
2117}
2118
Eric Laurent8f42ea12018-08-08 09:08:25 -07002119void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2120{
2121 stopInput(portId);
2122 releaseInput(portId);
2123}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002124
Eric Laurentd4692962014-05-05 18:13:44 -07002125void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002126 bool patchRemoved = false;
2127
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002128 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002129 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002130 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002131 if (patch_index >= 0) {
2132 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002133 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002134 mAudioPatches.removeItemsAt(patch_index);
2135 patchRemoved = true;
2136 }
Eric Laurentfe231122017-11-17 17:48:06 -08002137 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002138 }
2139 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002140 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002141 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002142
2143 if (patchRemoved) {
2144 mpClientInterface->onAudioPatchListUpdate();
2145 }
Eric Laurentd4692962014-05-05 18:13:44 -07002146}
2147
Eric Laurente0720872014-03-11 09:30:41 -07002148void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002149 int indexMin,
2150 int indexMax)
2151{
2152 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002153 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002154
2155 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002156 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2157 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002158 continue;
2159 }
2160 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002161 }
Eric Laurente552edb2014-03-10 17:42:56 -07002162}
2163
Eric Laurente0720872014-03-11 09:30:41 -07002164status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002165 int index,
2166 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002167{
2168
Nadav Bar7c605f62017-12-25 00:01:52 +02002169 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2170 // app that has MODIFY_PHONE_STATE permission.
2171 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2172 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002173 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002174 return BAD_VALUE;
2175 }
2176 if (!audio_is_output_device(device)) {
2177 return BAD_VALUE;
2178 }
2179
2180 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002181 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002182
Eric Laurent1fd372e2016-04-06 14:23:53 -07002183 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002184 stream, device, index);
2185
Eric Laurent28d09f02016-03-08 10:43:05 -08002186 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002187 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2188 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002189 continue;
2190 }
2191 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2192 }
Eric Laurente552edb2014-03-10 17:42:56 -07002193
Eric Laurent1fd372e2016-04-06 14:23:53 -07002194 // update volume on all outputs and streams matching the following:
2195 // - The requested stream (or a stream matching for volume control) is active on the output
2196 // - The device (or devices) selected by the strategy corresponding to this stream includes
2197 // the requested device
2198 // - For non default requested device, currently selected device on the output is either the
2199 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002200 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2201 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002202 status_t status = NO_ERROR;
2203 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002204 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2205 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002206 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002207 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002208 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002209 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002210 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002211 continue;
2212 }
Eric Laurent794fde22016-03-11 09:50:45 -08002213 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002214 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2215 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002216 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2217 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002218 continue;
2219 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002220 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002221 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002222 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002223 applyVolume = (curDevice & curStreamDevice) != 0;
2224 } else {
2225 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002226 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002227 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002228 // rescale index before applying to curStream as ranges may be different for
2229 // stream and curStream
2230 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002231 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002232 //FIXME: workaround for truncated touch sounds
2233 // delayed volume change for system stream to be removed when the problem is
2234 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002235 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002236 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002237 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002238 if (volStatus != NO_ERROR) {
2239 status = volStatus;
2240 }
2241 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002242 }
Eric Laurente552edb2014-03-10 17:42:56 -07002243 }
2244 return status;
2245}
2246
Eric Laurente0720872014-03-11 09:30:41 -07002247status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002248 int *index,
2249 audio_devices_t device)
2250{
2251 if (index == NULL) {
2252 return BAD_VALUE;
2253 }
2254 if (!audio_is_output_device(device)) {
2255 return BAD_VALUE;
2256 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002257 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002258 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002259 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002260 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2261 }
François Gaffiedfd74092015-03-19 12:10:59 +01002262 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002263
François Gaffied1ab2bd2015-12-02 18:20:06 +01002264 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002265 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2266 return NO_ERROR;
2267}
2268
Eric Laurent36829f92017-04-07 19:04:42 -07002269audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002270{
2271 // select one output among several suitable for global effects.
2272 // The priority is as follows:
2273 // 1: An offloaded output. If the effect ends up not being offloadable,
2274 // AudioFlinger will invalidate the track and the offloaded output
2275 // will be closed causing the effect to be moved to a PCM output.
2276 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002277 // 3: The primary output
2278 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002279
Eric Laurent3b73df72014-03-11 09:06:29 -07002280 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002281 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002282 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002283
Eric Laurent36829f92017-04-07 19:04:42 -07002284 if (outputs.size() == 0) {
2285 return AUDIO_IO_HANDLE_NONE;
2286 }
Eric Laurente552edb2014-03-10 17:42:56 -07002287
Eric Laurent36829f92017-04-07 19:04:42 -07002288 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2289 bool activeOnly = true;
2290
2291 while (output == AUDIO_IO_HANDLE_NONE) {
2292 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2293 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2294 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2295
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002296 for (audio_io_handle_t output : outputs) {
2297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002298 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2299 continue;
2300 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002301 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2302 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002303 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002304 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002305 }
2306 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002307 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002308 }
2309 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002310 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002311 }
2312 }
2313 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2314 output = outputOffloaded;
2315 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2316 output = outputDeepBuffer;
2317 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2318 output = outputPrimary;
2319 } else {
2320 output = outputs[0];
2321 }
2322 activeOnly = false;
2323 }
2324
2325 if (output != mMusicEffectOutput) {
2326 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2327 mMusicEffectOutput = output;
2328 }
2329
2330 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002331 return output;
2332}
2333
Eric Laurent36829f92017-04-07 19:04:42 -07002334audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2335{
2336 return selectOutputForMusicEffects();
2337}
2338
Eric Laurente0720872014-03-11 09:30:41 -07002339status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002340 audio_io_handle_t io,
2341 uint32_t strategy,
2342 int session,
2343 int id)
2344{
2345 ssize_t index = mOutputs.indexOfKey(io);
2346 if (index < 0) {
2347 index = mInputs.indexOfKey(io);
2348 if (index < 0) {
2349 ALOGW("registerEffect() unknown io %d", io);
2350 return INVALID_OPERATION;
2351 }
2352 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002353 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002354}
2355
Eric Laurentc75307b2015-03-17 15:29:32 -07002356bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2357{
Eric Laurent28d09f02016-03-08 10:43:05 -08002358 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002359 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2360 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002361 continue;
2362 }
2363 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2364 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002365 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002366}
2367
2368bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2369{
2370 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2371}
2372
Eric Laurente0720872014-03-11 09:30:41 -07002373bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002374{
2375 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002376 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002377 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002378 return true;
2379 }
2380 }
2381 return false;
2382}
2383
Eric Laurent275e8e92014-11-30 15:14:47 -08002384// Register a list of custom mixes with their attributes and format.
2385// When a mix is registered, corresponding input and output profiles are
2386// added to the remote submix hw module. The profile contains only the
2387// parameters (sampling rate, format...) specified by the mix.
2388// The corresponding input remote submix device is also connected.
2389//
2390// When a remote submix device is connected, the address is checked to select the
2391// appropriate profile and the corresponding input or output stream is opened.
2392//
2393// When capture starts, getInputForAttr() will:
2394// - 1 look for a mix matching the address passed in attribtutes tags if any
2395// - 2 if none found, getDeviceForInputSource() will:
2396// - 2.1 look for a mix matching the attributes source
2397// - 2.2 if none found, default to device selection by policy rules
2398// At this time, the corresponding output remote submix device is also connected
2399// and active playback use cases can be transferred to this mix if needed when reconnecting
2400// after AudioTracks are invalidated
2401//
2402// When playback starts, getOutputForAttr() will:
2403// - 1 look for a mix matching the address passed in attribtutes tags if any
2404// - 2 if none found, look for a mix matching the attributes usage
2405// - 3 if none found, default to device and output selection by policy rules.
2406
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002407status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002408{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002409 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2410 status_t res = NO_ERROR;
2411
2412 sp<HwModule> rSubmixModule;
2413 // examine each mix's route type
2414 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002415 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002416 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002417 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002418 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002419 break;
2420 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002421 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002422 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002423 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002424 rSubmixModule = mHwModules.getModuleFromName(
2425 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2426 if (rSubmixModule == 0) {
2427 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2428 i);
2429 res = INVALID_OPERATION;
2430 break;
2431 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002432 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002433
Eric Laurent97ac8712018-07-27 18:59:02 -07002434 String8 address = mix.mDeviceAddress;
2435 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2436 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2437 } else {
2438 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2439 }
François Gaffie036e1e92015-03-19 10:16:24 +01002440
Eric Laurent97ac8712018-07-27 18:59:02 -07002441 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002442 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002443 res = INVALID_OPERATION;
2444 break;
2445 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002446 audio_config_t outputConfig = mix.mFormat;
2447 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002448 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2449 // stereo and let audio flinger do the channel conversion if needed.
2450 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2451 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2452 rSubmixModule->addOutputProfile(address, &outputConfig,
2453 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2454 rSubmixModule->addInputProfile(address, &inputConfig,
2455 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002456
Eric Laurent97ac8712018-07-27 18:59:02 -07002457 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002458 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2459 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2460 address.string(), "remote-submix");
2461 } else {
2462 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2463 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2464 address.string(), "remote-submix");
2465 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2467 String8 address = mix.mDeviceAddress;
2468 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002469 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2470 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002471
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002472 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002473 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2474 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2475 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2476 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2477 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2478 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002479 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2480 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002481 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002482 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002483 } else {
2484 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002485 }
2486 break;
2487 }
2488 }
2489
2490 if (res != NO_ERROR) {
2491 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002492 i, device, address.string());
2493 res = INVALID_OPERATION;
2494 break;
2495 } else if (!foundOutput) {
2496 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2497 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002498 res = INVALID_OPERATION;
2499 break;
2500 }
Eric Laurentc722f302014-12-10 11:21:49 -08002501 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002502 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002503 if (res != NO_ERROR) {
2504 unregisterPolicyMixes(mixes);
2505 }
2506 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002507}
2508
2509status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2510{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002511 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002512 status_t res = NO_ERROR;
2513 sp<HwModule> rSubmixModule;
2514 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002515 for (const auto& mix : mixes) {
2516 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002517
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002518 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002519 rSubmixModule = mHwModules.getModuleFromName(
2520 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2521 if (rSubmixModule == 0) {
2522 res = INVALID_OPERATION;
2523 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002524 }
2525 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002526
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002527 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002528
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002529 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2530 res = INVALID_OPERATION;
2531 continue;
2532 }
2533
2534 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2535 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2536 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2537 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2538 address.string(), "remote-submix");
2539 }
2540 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2541 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2542 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2543 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2544 address.string(), "remote-submix");
2545 }
2546 rSubmixModule->removeOutputProfile(address);
2547 rSubmixModule->removeInputProfile(address);
2548
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002549 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2550 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002551 res = INVALID_OPERATION;
2552 continue;
2553 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002554 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002555 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002556 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002557}
2558
Andy Hungc29d82b2018-10-05 12:23:17 -07002559void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002560{
Andy Hungc29d82b2018-10-05 12:23:17 -07002561 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2562 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002563 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002564 std::string stateLiteral;
2565 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002566 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002567 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2568 "communications", "media", "record", "dock", "system",
2569 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2570 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2571 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002572 dst->appendFormat(" Force use for %s: %d\n",
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002573 forceUses[i], mEngine->getForceUse(i));
2574 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002575 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2576 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2577 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2578 mAvailableOutputDevices.dump(dst, String8("Available output"));
2579 mAvailableInputDevices.dump(dst, String8("Available input"));
2580 mHwModulesAll.dump(dst);
2581 mOutputs.dump(dst);
2582 mInputs.dump(dst);
2583 mVolumeCurves->dump(dst);
2584 mEffects.dump(dst);
2585 mAudioPatches.dump(dst);
2586 mPolicyMixes.dump(dst);
2587 mAudioSources.dump(dst);
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002588 if (!mSurroundFormats.empty()) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002589 dst->append("\nEnabled Surround Formats:\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002590 size_t i = 0;
2591 for (const auto& fmt : mSurroundFormats) {
Andy Hungc29d82b2018-10-05 12:23:17 -07002592 dst->append(i++ == 0 ? " " : ", ");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002593 std::string sfmt;
2594 FormatConverter::toString(fmt, sfmt);
Andy Hungc29d82b2018-10-05 12:23:17 -07002595 dst->append(sfmt.c_str());
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002596 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002597 dst->append("\n");
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07002598 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002599}
2600
2601status_t AudioPolicyManager::dump(int fd)
2602{
2603 String8 result;
2604 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002605 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002606 return NO_ERROR;
2607}
2608
2609// This function checks for the parameters which can be offloaded.
2610// This can be enhanced depending on the capability of the DSP and policy
2611// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002612bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002613{
2614 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002615 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002616 offloadInfo.sample_rate, offloadInfo.channel_mask,
2617 offloadInfo.format,
2618 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2619 offloadInfo.has_video);
2620
Andy Hung2ddee192015-12-18 17:34:44 -08002621 if (mMasterMono) {
2622 return false; // no offloading if mono is set.
2623 }
2624
Eric Laurente552edb2014-03-10 17:42:56 -07002625 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002626 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2627 ALOGV("offload disabled by audio.offload.disable");
2628 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002629 }
2630
2631 // Check if stream type is music, then only allow offload as of now.
2632 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2633 {
2634 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2635 return false;
2636 }
2637
2638 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002639 const bool allowOffloadWithVideo =
2640 property_get_bool("audio.offload.video", false /* default_value */);
2641 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002642 ALOGV("isOffloadSupported: has_video == true, returning false");
2643 return false;
2644 }
2645
2646 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002647 const int min_duration_secs = property_get_int32(
2648 "audio.offload.min.duration.secs", -1 /* default_value */);
2649 if (min_duration_secs >= 0) {
2650 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2651 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2652 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002653 return false;
2654 }
2655 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2656 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2657 return false;
2658 }
2659
2660 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2661 // creating an offloaded track and tearing it down immediately after start when audioflinger
2662 // detects there is an active non offloadable effect.
2663 // FIXME: We should check the audio session here but we do not have it in this context.
2664 // This may prevent offloading in rare situations where effects are left active by apps
2665 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002666 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002667 return false;
2668 }
2669
2670 // See if there is a profile to support this.
2671 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002672 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002673 offloadInfo.sample_rate,
2674 offloadInfo.format,
2675 offloadInfo.channel_mask,
2676 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002677 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2678 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002679}
2680
Eric Laurent6a94d692014-05-20 11:18:06 -07002681status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2682 audio_port_type_t type,
2683 unsigned int *num_ports,
2684 struct audio_port *ports,
2685 unsigned int *generation)
2686{
2687 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2688 generation == NULL) {
2689 return BAD_VALUE;
2690 }
2691 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2692 if (ports == NULL) {
2693 *num_ports = 0;
2694 }
2695
2696 size_t portsWritten = 0;
2697 size_t portsMax = *num_ports;
2698 *num_ports = 0;
2699 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002700 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2701 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002702 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002703 for (const auto& dev : mAvailableOutputDevices) {
2704 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002705 continue;
2706 }
2707 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002708 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002709 }
2710 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002711 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002712 }
2713 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002714 for (const auto& dev : mAvailableInputDevices) {
2715 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002716 continue;
2717 }
2718 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002719 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002720 }
2721 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002722 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002723 }
2724 }
2725 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2726 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2727 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2728 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2729 }
2730 *num_ports += mInputs.size();
2731 }
2732 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002733 size_t numOutputs = 0;
2734 for (size_t i = 0; i < mOutputs.size(); i++) {
2735 if (!mOutputs[i]->isDuplicated()) {
2736 numOutputs++;
2737 if (portsWritten < portsMax) {
2738 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2739 }
2740 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002741 }
Eric Laurent84c70242014-06-23 08:46:27 -07002742 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002743 }
2744 }
2745 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002746 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002747 return NO_ERROR;
2748}
2749
Eric Laurent99fcae42018-05-17 16:59:18 -07002750status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002751{
Eric Laurent99fcae42018-05-17 16:59:18 -07002752 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2753 return BAD_VALUE;
2754 }
2755 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2756 if (dev != 0) {
2757 dev->toAudioPort(port);
2758 return NO_ERROR;
2759 }
2760 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2761 if (dev != 0) {
2762 dev->toAudioPort(port);
2763 return NO_ERROR;
2764 }
2765 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2766 if (out != 0) {
2767 out->toAudioPort(port);
2768 return NO_ERROR;
2769 }
2770 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2771 if (in != 0) {
2772 in->toAudioPort(port);
2773 return NO_ERROR;
2774 }
2775 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002776}
2777
Eric Laurent6a94d692014-05-20 11:18:06 -07002778status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2779 audio_patch_handle_t *handle,
2780 uid_t uid)
2781{
2782 ALOGV("createAudioPatch()");
2783
2784 if (handle == NULL || patch == NULL) {
2785 return BAD_VALUE;
2786 }
2787 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2788
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002789 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002790 return BAD_VALUE;
2791 }
2792 // only one source per audio patch supported for now
2793 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002794 return INVALID_OPERATION;
2795 }
Eric Laurent874c42872014-08-08 15:13:39 -07002796
2797 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 return INVALID_OPERATION;
2799 }
Eric Laurent874c42872014-08-08 15:13:39 -07002800 for (size_t i = 0; i < patch->num_sinks; i++) {
2801 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2802 return INVALID_OPERATION;
2803 }
2804 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002805
2806 sp<AudioPatch> patchDesc;
2807 ssize_t index = mAudioPatches.indexOfKey(*handle);
2808
Eric Laurent6a94d692014-05-20 11:18:06 -07002809 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2810 patch->sources[0].role,
2811 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002812#if LOG_NDEBUG == 0
2813 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002814 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002815 patch->sinks[i].role,
2816 patch->sinks[i].type);
2817 }
2818#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002819
2820 if (index >= 0) {
2821 patchDesc = mAudioPatches.valueAt(index);
2822 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2823 mUidCached, patchDesc->mUid, uid);
2824 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2825 return INVALID_OPERATION;
2826 }
2827 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002828 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002829 }
2830
2831 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002832 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 if (outputDesc == NULL) {
2834 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2835 return BAD_VALUE;
2836 }
Eric Laurent84c70242014-06-23 08:46:27 -07002837 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2838 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002839 if (patchDesc != 0) {
2840 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2841 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2842 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2843 return BAD_VALUE;
2844 }
2845 }
Eric Laurent874c42872014-08-08 15:13:39 -07002846 DeviceVector devices;
2847 for (size_t i = 0; i < patch->num_sinks; i++) {
2848 // Only support mix to devices connection
2849 // TODO add support for mix to mix connection
2850 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2851 ALOGV("createAudioPatch() source mix but sink is not a device");
2852 return INVALID_OPERATION;
2853 }
2854 sp<DeviceDescriptor> devDesc =
2855 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2856 if (devDesc == 0) {
2857 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2858 return BAD_VALUE;
2859 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002860
François Gaffie53615e22015-03-19 09:24:12 +01002861 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002862 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002863 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002864 NULL, // updatedSamplingRate
2865 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002866 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002867 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002868 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002869 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002870 ALOGV("createAudioPatch() profile not supported for device %08x",
2871 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002872 return INVALID_OPERATION;
2873 }
2874 devices.add(devDesc);
2875 }
2876 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002877 return INVALID_OPERATION;
2878 }
Eric Laurent874c42872014-08-08 15:13:39 -07002879
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 // TODO: reconfigure output format and channels here
2881 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002882 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002883 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002884 index = mAudioPatches.indexOfKey(*handle);
2885 if (index >= 0) {
2886 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2887 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2888 }
2889 patchDesc = mAudioPatches.valueAt(index);
2890 patchDesc->mUid = uid;
2891 ALOGV("createAudioPatch() success");
2892 } else {
2893 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2894 return INVALID_OPERATION;
2895 }
2896 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2897 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2898 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002899 // only one sink supported when connecting an input device to a mix
2900 if (patch->num_sinks > 1) {
2901 return INVALID_OPERATION;
2902 }
François Gaffie53615e22015-03-19 09:24:12 +01002903 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 if (inputDesc == NULL) {
2905 return BAD_VALUE;
2906 }
2907 if (patchDesc != 0) {
2908 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2909 return BAD_VALUE;
2910 }
2911 }
2912 sp<DeviceDescriptor> devDesc =
2913 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2914 if (devDesc == 0) {
2915 return BAD_VALUE;
2916 }
2917
François Gaffie53615e22015-03-19 09:24:12 +01002918 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002919 devDesc->mAddress,
2920 patch->sinks[0].sample_rate,
2921 NULL, /*updatedSampleRate*/
2922 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002923 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002924 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002925 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002926 // FIXME for the parameter type,
2927 // and the NONE
2928 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002929 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002930 return INVALID_OPERATION;
2931 }
2932 // TODO: reconfigure output format and channels here
2933 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002934 devDesc->type(), inputDesc->mIoHandle);
2935 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002936 index = mAudioPatches.indexOfKey(*handle);
2937 if (index >= 0) {
2938 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2939 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2940 }
2941 patchDesc = mAudioPatches.valueAt(index);
2942 patchDesc->mUid = uid;
2943 ALOGV("createAudioPatch() success");
2944 } else {
2945 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2946 return INVALID_OPERATION;
2947 }
2948 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2949 // device to device connection
2950 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002951 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002952 return BAD_VALUE;
2953 }
2954 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002955 sp<DeviceDescriptor> srcDeviceDesc =
2956 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002957 if (srcDeviceDesc == 0) {
2958 return BAD_VALUE;
2959 }
Eric Laurent874c42872014-08-08 15:13:39 -07002960
Eric Laurent6a94d692014-05-20 11:18:06 -07002961 //update source and sink with our own data as the data passed in the patch may
2962 // be incomplete.
2963 struct audio_patch newPatch = *patch;
2964 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002965
Eric Laurent874c42872014-08-08 15:13:39 -07002966 for (size_t i = 0; i < patch->num_sinks; i++) {
2967 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2968 ALOGV("createAudioPatch() source device but one sink is not a device");
2969 return INVALID_OPERATION;
2970 }
2971
2972 sp<DeviceDescriptor> sinkDeviceDesc =
2973 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2974 if (sinkDeviceDesc == 0) {
2975 return BAD_VALUE;
2976 }
2977 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2978
Eric Laurent3bcf8592015-04-03 12:13:24 -07002979 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08002980 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07002981 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002982 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002983 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002984 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002985 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002986 return INVALID_OPERATION;
2987 }
Eric Laurent874c42872014-08-08 15:13:39 -07002988 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002989 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002990 // if the sink device is reachable via an opened output stream, request to go via
2991 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002992 audio_io_handle_t output = selectOutput(outputs,
2993 AUDIO_OUTPUT_FLAG_NONE,
2994 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002995 if (output != AUDIO_IO_HANDLE_NONE) {
2996 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2997 if (outputDesc->isDuplicated()) {
2998 return INVALID_OPERATION;
2999 }
3000 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003001 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003002 newPatch.num_sources = 2;
3003 }
Eric Laurent83b88082014-06-20 18:31:16 -07003004 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003005 }
3006 // TODO: check from routing capabilities in config file and other conflicting patches
3007
Mikhail Naganovdc769682018-05-04 15:34:08 -07003008 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3009 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003010 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3011 status);
3012 return INVALID_OPERATION;
3013 }
3014 } else {
3015 return BAD_VALUE;
3016 }
3017 } else {
3018 return BAD_VALUE;
3019 }
3020 return NO_ERROR;
3021}
3022
3023status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3024 uid_t uid)
3025{
3026 ALOGV("releaseAudioPatch() patch %d", handle);
3027
3028 ssize_t index = mAudioPatches.indexOfKey(handle);
3029
3030 if (index < 0) {
3031 return BAD_VALUE;
3032 }
3033 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3034 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3035 mUidCached, patchDesc->mUid, uid);
3036 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3037 return INVALID_OPERATION;
3038 }
3039
3040 struct audio_patch *patch = &patchDesc->mPatch;
3041 patchDesc->mUid = mUidCached;
3042 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003043 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003044 if (outputDesc == NULL) {
3045 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3046 return BAD_VALUE;
3047 }
3048
Eric Laurentc75307b2015-03-17 15:29:32 -07003049 setOutputDevice(outputDesc,
3050 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003051 true,
3052 0,
3053 NULL);
3054 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3055 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003056 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003057 if (inputDesc == NULL) {
3058 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3059 return BAD_VALUE;
3060 }
3061 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003062 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003063 true,
3064 NULL);
3065 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003066 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3067 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3068 status, patchDesc->mAfPatchHandle);
3069 removeAudioPatch(patchDesc->mHandle);
3070 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003071 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003072 } else {
3073 return BAD_VALUE;
3074 }
3075 } else {
3076 return BAD_VALUE;
3077 }
3078 return NO_ERROR;
3079}
3080
3081status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3082 struct audio_patch *patches,
3083 unsigned int *generation)
3084{
François Gaffie53615e22015-03-19 09:24:12 +01003085 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003086 return BAD_VALUE;
3087 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003088 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003089 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003090}
3091
Eric Laurente1715a42014-05-20 11:30:42 -07003092status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003093{
Eric Laurente1715a42014-05-20 11:30:42 -07003094 ALOGV("setAudioPortConfig()");
3095
3096 if (config == NULL) {
3097 return BAD_VALUE;
3098 }
3099 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3100 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003101 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3102 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003103 }
3104
Eric Laurenta121f902014-06-03 13:32:54 -07003105 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003106 if (config->type == AUDIO_PORT_TYPE_MIX) {
3107 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003108 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003109 if (outputDesc == NULL) {
3110 return BAD_VALUE;
3111 }
Eric Laurent84c70242014-06-23 08:46:27 -07003112 ALOG_ASSERT(!outputDesc->isDuplicated(),
3113 "setAudioPortConfig() called on duplicated output %d",
3114 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003115 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003116 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003117 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003118 if (inputDesc == NULL) {
3119 return BAD_VALUE;
3120 }
Eric Laurenta121f902014-06-03 13:32:54 -07003121 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003122 } else {
3123 return BAD_VALUE;
3124 }
3125 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3126 sp<DeviceDescriptor> deviceDesc;
3127 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3128 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3129 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3130 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3131 } else {
3132 return BAD_VALUE;
3133 }
3134 if (deviceDesc == NULL) {
3135 return BAD_VALUE;
3136 }
Eric Laurenta121f902014-06-03 13:32:54 -07003137 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003138 } else {
3139 return BAD_VALUE;
3140 }
3141
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003142 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003143 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3144 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003145 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003146 audioPortConfig->toAudioPortConfig(&newConfig, config);
3147 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003148 }
Eric Laurenta121f902014-06-03 13:32:54 -07003149 if (status != NO_ERROR) {
3150 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003151 }
Eric Laurente1715a42014-05-20 11:30:42 -07003152
3153 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003154}
3155
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003156void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3157{
Eric Laurentd60560a2015-04-10 11:31:20 -07003158 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003159 clearAudioPatches(uid);
3160 clearSessionRoutes(uid);
3161}
3162
Eric Laurent6a94d692014-05-20 11:18:06 -07003163void AudioPolicyManager::clearAudioPatches(uid_t uid)
3164{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003165 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003166 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3167 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003168 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003169 }
3170 }
3171}
3172
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003173void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3174 audio_io_handle_t ouptutToSkip)
3175{
3176 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3177 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3178 for (size_t j = 0; j < mOutputs.size(); j++) {
3179 if (mOutputs.keyAt(j) == ouptutToSkip) {
3180 continue;
3181 }
3182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3183 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3184 continue;
3185 }
3186 // If the default device for this strategy is on another output mix,
3187 // invalidate all tracks in this strategy to force re connection.
3188 // Otherwise select new device on the output mix.
3189 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003190 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003191 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3192 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3193 }
3194 }
3195 } else {
3196 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3197 setOutputDevice(outputDesc, newDevice, false);
3198 }
3199 }
3200}
3201
3202void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3203{
3204 // remove output routes associated with this uid
3205 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003206 for (size_t i = 0; i < mOutputs.size(); i++) {
3207 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003208 for (const auto& client : outputDesc->getClientIterable()) {
3209 if (client->hasPreferredDevice() && client->uid() == uid) {
3210 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3211 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003212 }
3213 }
3214 }
3215 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003216 for (const auto& strategy : affectedStrategies) {
3217 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003218 }
3219
3220 // remove input routes associated with this uid
3221 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003222 for (size_t i = 0; i < mInputs.size(); i++) {
3223 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003224 for (const auto& client : inputDesc->getClientIterable()) {
3225 if (client->hasPreferredDevice() && client->uid() == uid) {
3226 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3227 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003228 }
3229 }
3230 }
3231 // reroute inputs if necessary
3232 SortedVector<audio_io_handle_t> inputsToClose;
3233 for (size_t i = 0; i < mInputs.size(); i++) {
3234 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003235 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003236 inputsToClose.add(inputDesc->mIoHandle);
3237 }
3238 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003239 for (const auto& input : inputsToClose) {
3240 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003241 }
3242}
3243
Eric Laurentd60560a2015-04-10 11:31:20 -07003244void AudioPolicyManager::clearAudioSources(uid_t uid)
3245{
3246 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003247 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3248 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003249 stopAudioSource(mAudioSources.keyAt(i));
3250 }
3251 }
3252}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003253
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003254status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3255 audio_io_handle_t *ioHandle,
3256 audio_devices_t *device)
3257{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003258 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3259 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003260 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003261
François Gaffiedf372692015-03-19 10:43:27 +01003262 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003263}
3264
Eric Laurentd60560a2015-04-10 11:31:20 -07003265status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003266 const audio_attributes_t *attributes,
3267 audio_port_handle_t *portId,
3268 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003269{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003270 ALOGV("%s", __FUNCTION__);
3271 *portId = AUDIO_PORT_HANDLE_NONE;
3272
3273 if (source == NULL || attributes == NULL || portId == NULL) {
3274 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3275 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003276 return BAD_VALUE;
3277 }
3278
Eric Laurentd60560a2015-04-10 11:31:20 -07003279 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3280 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003281 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3282 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003283 return INVALID_OPERATION;
3284 }
3285
3286 sp<DeviceDescriptor> srcDeviceDesc =
3287 mAvailableInputDevices.getDevice(source->ext.device.type,
3288 String8(source->ext.device.address));
3289 if (srcDeviceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003290 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003291 return BAD_VALUE;
3292 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003293
3294 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003295
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003296 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003297 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003298
3299 sp<SourceClientDescriptor> sourceDesc =
3300 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDeviceDesc,
Eric Laurent97ac8712018-07-27 18:59:02 -07003301 streamTypefromAttributesInt(attributes),
3302 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003303
3304 status_t status = connectAudioSource(sourceDesc);
3305 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003306 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003307 }
3308 return status;
3309}
3310
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003311status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003312{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003313 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003314
3315 // make sure we only have one patch per source.
3316 disconnectAudioSource(sourceDesc);
3317
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003318 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003319 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003320 audio_stream_type_t stream = sourceDesc->stream();
3321 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003322
3323 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3324 sp<DeviceDescriptor> sinkDeviceDesc =
3325 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3326
3327 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003328
3329 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3330 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003331 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003332 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3333 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3334 // create patch between src device and output device
3335 // create Hwoutput and add to mHwOutputs
3336 } else {
3337 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3338 audio_io_handle_t output =
3339 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3340 if (output == AUDIO_IO_HANDLE_NONE) {
3341 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3342 return INVALID_OPERATION;
3343 }
3344 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3345 if (outputDesc->isDuplicated()) {
3346 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3347 return INVALID_OPERATION;
3348 }
Eric Laurent733ce942017-12-07 12:18:25 -08003349 status_t status = outputDesc->start();
3350 if (status != NO_ERROR) {
3351 return status;
3352 }
3353
Eric Laurentd60560a2015-04-10 11:31:20 -07003354 // create a special patch with no sink and two sources:
3355 // - the second source indicates to PatchPanel through which output mix this patch should
3356 // be connected as well as the stream type for volume control
3357 // - the sink is defined by whatever output device is currently selected for the output
3358 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003359 PatchBuilder patchBuilder;
3360 patchBuilder.addSource(srcDeviceDesc).addSource(outputDesc, { .stream = stream });
3361 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003362 &afPatchHandle,
3363 0);
3364 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3365 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003366 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003367 if (status != NO_ERROR) {
3368 ALOGW("%s patch panel could not connect device patch, error %d",
3369 __FUNCTION__, status);
3370 return INVALID_OPERATION;
3371 }
3372 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003373 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003374
3375 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003376 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003377 return status;
3378 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003379 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003380 if (delayMs != 0) {
3381 usleep(delayMs * 1000);
3382 }
3383 }
3384
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003385 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3386 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003387
3388 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003389}
3390
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003391status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003392{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003393 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3394 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003395 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003396 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003397 return BAD_VALUE;
3398 }
3399 status_t status = disconnectAudioSource(sourceDesc);
3400
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003401 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003402 return status;
3403}
3404
Andy Hung2ddee192015-12-18 17:34:44 -08003405status_t AudioPolicyManager::setMasterMono(bool mono)
3406{
3407 if (mMasterMono == mono) {
3408 return NO_ERROR;
3409 }
3410 mMasterMono = mono;
3411 // if enabling mono we close all offloaded devices, which will invalidate the
3412 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3413 // for recreating the new AudioTrack as non-offloaded PCM.
3414 //
3415 // If disabling mono, we leave all tracks as is: we don't know which clients
3416 // and tracks are able to be recreated as offloaded. The next "song" should
3417 // play back offloaded.
3418 if (mMasterMono) {
3419 Vector<audio_io_handle_t> offloaded;
3420 for (size_t i = 0; i < mOutputs.size(); ++i) {
3421 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3422 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3423 offloaded.push(desc->mIoHandle);
3424 }
3425 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003426 for (const auto& handle : offloaded) {
3427 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003428 }
3429 }
3430 // update master mono for all remaining outputs
3431 for (size_t i = 0; i < mOutputs.size(); ++i) {
3432 updateMono(mOutputs.keyAt(i));
3433 }
3434 return NO_ERROR;
3435}
3436
3437status_t AudioPolicyManager::getMasterMono(bool *mono)
3438{
3439 *mono = mMasterMono;
3440 return NO_ERROR;
3441}
3442
Eric Laurentac9cef52017-06-09 15:46:26 -07003443float AudioPolicyManager::getStreamVolumeDB(
3444 audio_stream_type_t stream, int index, audio_devices_t device)
3445{
3446 return computeVolume(stream, index, device);
3447}
3448
jiabin81772902018-04-02 17:52:27 -07003449status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3450 audio_format_t *surroundFormats,
3451 bool *surroundFormatsEnabled,
3452 bool reported)
3453{
3454 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3455 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3456 return BAD_VALUE;
3457 }
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003458 ALOGV("getSurroundFormats() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p"
3459 " reported %d", *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003460
3461 // Only return value if there is HDMI output.
3462 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
3463 return INVALID_OPERATION;
3464 }
3465
3466 size_t formatsWritten = 0;
3467 size_t formatsMax = *numSurroundFormats;
3468 *numSurroundFormats = 0;
Mikhail Naganov2563f232018-09-27 14:48:01 -07003469 std::unordered_set<audio_format_t> formats;
jiabin81772902018-04-02 17:52:27 -07003470 if (reported) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003471 // Return formats from HDMI profiles, that have already been resolved by
3472 // checkOutputsForDevice().
3473 DeviceVector hdmiOutputDevs = mAvailableOutputDevices.getDevicesFromTypeMask(
3474 AUDIO_DEVICE_OUT_HDMI);
3475 for (size_t i = 0; i < hdmiOutputDevs.size(); i++) {
3476 FormatVector supportedFormats =
3477 hdmiOutputDevs[i]->getAudioPort()->getAudioProfiles().getSupportedFormats();
3478 for (size_t j = 0; j < supportedFormats.size(); j++) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003479 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003480 formats.insert(supportedFormats[j]);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003481 } else {
3482 for (const auto& pair : mConfig.getSurroundFormats()) {
3483 if (pair.second.count(supportedFormats[j]) != 0) {
3484 formats.insert(pair.first);
3485 break;
3486 }
3487 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003488 }
3489 }
jiabin81772902018-04-02 17:52:27 -07003490 }
3491 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003492 for (const auto& pair : mConfig.getSurroundFormats()) {
3493 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003494 }
3495 }
Mikhail Naganov2563f232018-09-27 14:48:01 -07003496 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003497 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003498 surroundFormats[formatsWritten] = format;
jiabin81772902018-04-02 17:52:27 -07003499 bool formatEnabled = false;
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003500 if (mConfig.getSurroundFormats().count(format) == 0) {
3501 // Check sub-formats
3502 for (const auto& pair : mConfig.getSurroundFormats()) {
3503 for (const auto& subformat : pair.second) {
3504 formatEnabled = mSurroundFormats.count(subformat) != 0;
3505 if (formatEnabled) break;
3506 }
3507 if (formatEnabled) break;
jiabin81772902018-04-02 17:52:27 -07003508 }
3509 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003510 formatEnabled = mSurroundFormats.count(format) != 0;
jiabin81772902018-04-02 17:52:27 -07003511 }
3512 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3513 }
3514 (*numSurroundFormats)++;
3515 }
3516 return NO_ERROR;
3517}
3518
3519status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3520{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003521 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
jiabin81772902018-04-02 17:52:27 -07003522 // Check if audio format is a surround formats.
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003523 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3524 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003525 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003526 return BAD_VALUE;
3527 }
3528
3529 // Should only be called when MANUAL.
3530 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3531 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
3532 if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003533 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003534 return INVALID_OPERATION;
3535 }
3536
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003537 if ((mSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003538 return NO_ERROR;
3539 }
3540
3541 // The operation is valid only when there is HDMI output available.
3542 if ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_HDMI) == 0) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003543 ALOGW("%s() no HDMI out devices found", __func__);
jiabin81772902018-04-02 17:52:27 -07003544 return INVALID_OPERATION;
3545 }
3546
Mikhail Naganov2563f232018-09-27 14:48:01 -07003547 std::unordered_set<audio_format_t> surroundFormatsBackup(mSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003548 if (enabled) {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003549 mSurroundFormats.insert(audioFormat);
3550 for (const auto& subFormat : formatIter->second) {
3551 mSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003552 }
3553 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003554 mSurroundFormats.erase(audioFormat);
3555 for (const auto& subFormat : formatIter->second) {
3556 mSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003557 }
3558 }
3559
3560 sp<SwAudioOutputDescriptor> outputDesc;
3561 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003562 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003563 AUDIO_DEVICE_OUT_HDMI);
3564 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3565 // Simulate reconnection to update enabled surround sound formats.
3566 String8 address = hdmiOutputDevices[i]->mAddress;
3567 String8 name = hdmiOutputDevices[i]->getName();
3568 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3569 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3570 address.c_str(),
3571 name.c_str());
3572 if (status != NO_ERROR) {
3573 continue;
3574 }
3575 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3576 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3577 address.c_str(),
3578 name.c_str());
3579 profileUpdated |= (status == NO_ERROR);
3580 }
Mikhail Naganov708e0382018-05-30 09:53:04 -07003581 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003582 AUDIO_DEVICE_IN_HDMI);
3583 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3584 // Simulate reconnection to update enabled surround sound formats.
3585 String8 address = hdmiInputDevices[i]->mAddress;
3586 String8 name = hdmiInputDevices[i]->getName();
3587 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3588 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3589 address.c_str(),
3590 name.c_str());
3591 if (status != NO_ERROR) {
3592 continue;
3593 }
3594 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3596 address.c_str(),
3597 name.c_str());
3598 profileUpdated |= (status == NO_ERROR);
3599 }
3600
jiabin81772902018-04-02 17:52:27 -07003601 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003602 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003603 mSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003604 }
3605
3606 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3607}
3608
Eric Laurentf32108e2018-10-04 17:22:04 -07003609void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003610{
Eric Laurentf32108e2018-10-04 17:22:04 -07003611 Vector<sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
Eric Laurentf32108e2018-10-04 17:22:04 -07003612
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003613 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003614
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003615 for (size_t i = 0; i < activeInputs.size(); i++) {
3616 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
Eric Laurent8f42ea12018-08-08 09:08:25 -07003617 RecordClientVector clients = activeDesc->clientsList(true /*activeOnly*/);
3618 for (const auto& client : clients) {
3619 if (uid == client->uid()) {
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003620 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003621 }
3622 }
3623 }
3624}
3625
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003626status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003627{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003628 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003629
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003630 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003631 if (patchDesc == 0) {
3632 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003633 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003634 return BAD_VALUE;
3635 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003636 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003637
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003638 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003639 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003640 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003641 if (status == NO_ERROR) {
3642 swOutputDesc->stop();
3643 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003644 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3645 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003646 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003647 if (hwOutputDesc != 0) {
3648 // release patch between src device and output device
3649 // close Hwoutput and remove from mHwOutputs
3650 } else {
3651 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3652 }
3653 }
3654 return NO_ERROR;
3655}
3656
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003657sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003658 audio_io_handle_t output, routing_strategy strategy)
3659{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003660 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003661 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003662 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3663 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003664 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003665 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003666 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3667 source = sourceDesc;
3668 break;
3669 }
3670 }
3671 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003672}
3673
Eric Laurente552edb2014-03-10 17:42:56 -07003674// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003675// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003676// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003677uint32_t AudioPolicyManager::nextAudioPortGeneration()
3678{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003679 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003680}
3681
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003682// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3683static const char *kConfigLocationList[] =
3684 {"/odm/etc", "/vendor/etc", "/system/etc"};
3685static const int kConfigLocationListSize =
3686 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3687
3688static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3689 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003690 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003691 status_t ret;
3692
Petri Gyntherf497f292018-04-17 18:46:10 -07003693 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3694 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3695 // A2DP offload supported but disabled: try to use special XML file
3696 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3697 }
3698 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3699
3700 for (const char* fileName : fileNames) {
3701 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003702 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3703 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003704 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003705 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003706 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003707 return ret;
3708 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003709 }
3710 }
3711 return ret;
3712}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003713
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003714AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3715 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003716 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003717 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003718 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003719 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003720 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003721 mVolumeCurves(new VolumeCurvesCollection()),
3722 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003723 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003724 mAudioPortGeneration(1),
3725 mBeaconMuteRefCount(0),
3726 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003727 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003728 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003729 mMasterMono(false),
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08003730 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003731{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003732}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003733
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003734AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3735 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3736{
3737 loadConfig();
3738 initialize();
3739}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003740
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003741// This check is to catch any legacy platform updating to Q without having
3742// switched to XML since its deprecation on O.
3743// TODO: after Q release, remove this check and flag as XML is now the only
3744// option and all legacy platform should have transitioned to XML.
3745#ifndef USE_XML_AUDIO_POLICY_CONF
3746#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003747#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003748
3749void AudioPolicyManager::loadConfig() {
3750 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003751 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003752 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003753 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003754}
3755
3756status_t AudioPolicyManager::initialize() {
3757 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003758
3759 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003760 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3761 if (!engineInstance) {
3762 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003763 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003764 }
3765 // Retrieve the Policy Manager Interface
3766 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3767 if (mEngine == NULL) {
3768 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003769 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003770 }
3771 mEngine->setObserver(this);
3772 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003773 if (status != NO_ERROR) {
3774 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3775 return status;
3776 }
François Gaffie2110e042015-03-24 08:41:51 +01003777
Eric Laurent3a4311c2014-03-17 12:00:47 -07003778 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003779 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003780 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3781 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003782 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003783 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003784 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3785 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003786 continue;
3787 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003788 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003789 // open all output streams needed to access attached devices
3790 // except for direct output streams that are only opened when they are actually
3791 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003792 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003793 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003794 if (!outProfile->canOpenNewIo()) {
3795 ALOGE("Invalid Output profile max open count %u for profile %s",
3796 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3797 continue;
3798 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003799 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003800 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003801 continue;
3802 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003803 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003804 mTtsOutputAvailable = true;
3805 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003806
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003807 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003808 continue;
3809 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003810 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003811 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3812 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003813 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003814 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003815 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003816 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003817 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003818 if ((profileType & outputDeviceTypes) == 0) {
3819 continue;
3820 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003821 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3822 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003823 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov708e0382018-05-30 09:53:04 -07003824 const DeviceVector &devicesForType = supportedDevices.getDevicesFromTypeMask(
3825 profileType);
Eric Laurentc40d9692016-04-13 19:14:13 -07003826 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3827 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003828 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003829 status_t status = outputDesc->open(nullptr, profileType, address,
3830 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07003831
3832 if (status != NO_ERROR) {
3833 ALOGW("Cannot open output stream for device %08x on hw module %s",
3834 outputDesc->mDevice,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003835 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003836 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003837 for (const auto& dev : supportedDevices) {
3838 ssize_t index = mAvailableOutputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003839 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003840 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003841 mAvailableOutputDevices[index]->attach(hwModule);
Eric Laurentd78f1532014-09-16 16:38:20 -07003842 }
3843 }
3844 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003845 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003846 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003847 }
3848 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003849 setOutputDevice(outputDesc,
Eric Laurentfe231122017-11-17 17:48:06 -08003850 profileType,
Eric Laurentc40d9692016-04-13 19:14:13 -07003851 true,
3852 0,
3853 NULL,
Eric Laurentfe231122017-11-17 17:48:06 -08003854 address);
Eric Laurentd78f1532014-09-16 16:38:20 -07003855 }
Eric Laurente552edb2014-03-10 17:42:56 -07003856 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003857 // open input streams needed to access attached devices to validate
3858 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003859 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003860 if (!inProfile->canOpenNewIo()) {
3861 ALOGE("Invalid Input profile max open count %u for profile %s",
3862 inProfile->maxOpenCount, inProfile->getTagName().c_str());
3863 continue;
3864 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003865 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003866 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003867 continue;
3868 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003869 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003870 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003871 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3872
Eric Laurentd78f1532014-09-16 16:38:20 -07003873 if ((profileType & inputDeviceTypes) == 0) {
3874 continue;
3875 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003876 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08003877 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003878
Mikhail Naganov708e0382018-05-30 09:53:04 -07003879 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromTypeMask(profileType);
Eric Laurent53b810e2017-12-10 17:25:10 -08003880 // the inputs vector must be of size >= 1, but we don't want to crash here
3881 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3882 : String8("");
3883 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3884 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3885
Eric Laurentd78f1532014-09-16 16:38:20 -07003886 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08003887 status_t status = inputDesc->open(nullptr,
3888 profileType,
Eric Laurent53b810e2017-12-10 17:25:10 -08003889 address,
Eric Laurentfe231122017-11-17 17:48:06 -08003890 AUDIO_SOURCE_MIC,
3891 AUDIO_INPUT_FLAG_NONE,
3892 &input);
Eric Laurentd78f1532014-09-16 16:38:20 -07003893
3894 if (status == NO_ERROR) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003895 for (const auto& dev : inProfile->getSupportedDevices()) {
3896 ssize_t index = mAvailableInputDevices.indexOf(dev);
Eric Laurentd78f1532014-09-16 16:38:20 -07003897 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003898 if (index >= 0) {
3899 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3900 if (!devDesc->isAttached()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003901 devDesc->attach(hwModule);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003902 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003903 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003904 }
3905 }
Eric Laurentfe231122017-11-17 17:48:06 -08003906 inputDesc->close();
Eric Laurentd78f1532014-09-16 16:38:20 -07003907 } else {
3908 ALOGW("Cannot open input stream for device %08x on hw module %s",
Eric Laurentfe231122017-11-17 17:48:06 -08003909 profileType,
Mikhail Naganovd4120142017-12-06 15:49:22 -08003910 hwModule->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003911 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003912 }
3913 }
3914 // make sure all attached devices have been allocated a unique ID
3915 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003916 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003917 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003918 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3919 continue;
3920 }
François Gaffie2110e042015-03-24 08:41:51 +01003921 // The device is now validated and can be appended to the available devices of the engine
3922 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3923 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003924 i++;
3925 }
3926 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003927 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003928 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003929 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3930 continue;
3931 }
François Gaffie2110e042015-03-24 08:41:51 +01003932 // The device is now validated and can be appended to the available devices of the engine
3933 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3934 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003935 i++;
3936 }
3937 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003938 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003939 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003940 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003941 }
jiabin9ff780e2018-03-19 18:19:52 -07003942 // If microphones address is empty, set it according to device type
3943 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
3944 if (mAvailableInputDevices[i]->mAddress.isEmpty()) {
3945 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
3946 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
3947 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
3948 mAvailableInputDevices[i]->mAddress = String8(AUDIO_BACK_MICROPHONE_ADDRESS);
3949 }
3950 }
3951 }
Eric Laurente552edb2014-03-10 17:42:56 -07003952
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003953 if (mPrimaryOutput == 0) {
3954 ALOGE("Failed to open primary output");
3955 status = NO_INIT;
3956 }
Eric Laurente552edb2014-03-10 17:42:56 -07003957
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09003958 // Silence ALOGV statements
3959 property_set("log.tag." LOG_TAG, "D");
3960
Eric Laurente552edb2014-03-10 17:42:56 -07003961 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003962 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003963}
3964
Eric Laurente0720872014-03-11 09:30:41 -07003965AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003966{
Eric Laurente552edb2014-03-10 17:42:56 -07003967 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003968 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003969 }
3970 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08003971 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07003972 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003973 mAvailableOutputDevices.clear();
3974 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003975 mOutputs.clear();
3976 mInputs.clear();
3977 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08003978 mHwModulesAll.clear();
jiabin81772902018-04-02 17:52:27 -07003979 mSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003980}
3981
Eric Laurente0720872014-03-11 09:30:41 -07003982status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003983{
Eric Laurent87ffa392015-05-22 10:32:38 -07003984 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003985}
3986
Eric Laurente552edb2014-03-10 17:42:56 -07003987// ---
3988
Eric Laurent98e38192018-02-15 18:31:53 -08003989void AudioPolicyManager::addOutput(audio_io_handle_t output,
3990 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003991{
Eric Laurent1c333e22014-05-20 10:48:17 -07003992 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08003993 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08003994 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07003995 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07003996 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003997}
3998
François Gaffie53615e22015-03-19 09:24:12 +01003999void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4000{
4001 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004002 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004003}
4004
Eric Laurent98e38192018-02-15 18:31:53 -08004005void AudioPolicyManager::addInput(audio_io_handle_t input,
4006 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004007{
Eric Laurent1c333e22014-05-20 10:48:17 -07004008 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004009 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004010}
Eric Laurente552edb2014-03-10 17:42:56 -07004011
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004012void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004013 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004014 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004015 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004016 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004017 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004018 if (devDesc != 0) {
4019 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4020 desc->mIoHandle, address.string());
4021 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004022 }
4023}
4024
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004025status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004026 audio_policy_dev_state_t state,
4027 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004028 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004029{
François Gaffie53615e22015-03-19 09:24:12 +01004030 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004031 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004032
4033 if (audio_device_is_digital(device)) {
4034 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004035 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004036 }
Eric Laurente552edb2014-03-10 17:42:56 -07004037
Eric Laurent3b73df72014-03-11 09:06:29 -07004038 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004039 // first list already open outputs that can be routed to this device
4040 for (size_t i = 0; i < mOutputs.size(); i++) {
4041 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004042 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004043 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004044 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4045 outputs.add(mOutputs.keyAt(i));
4046 } else {
4047 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004048 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004049 }
Eric Laurente552edb2014-03-10 17:42:56 -07004050 }
4051 }
4052 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004053 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004054 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004055 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4056 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004057 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004058 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004059 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004060 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004061 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4062 j, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004063 }
Eric Laurente552edb2014-03-10 17:42:56 -07004064 }
4065 }
4066 }
4067
Eric Laurent7b279bb2015-12-14 10:18:23 -08004068 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004069
Eric Laurente552edb2014-03-10 17:42:56 -07004070 if (profiles.isEmpty() && outputs.isEmpty()) {
4071 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4072 return BAD_VALUE;
4073 }
4074
4075 // open outputs for matching profiles if needed. Direct outputs are also opened to
4076 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4077 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004078 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004079
4080 // nothing to do if one output is already opened for this profile
4081 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004082 for (j = 0; j < outputs.size(); j++) {
4083 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004084 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004085 // matching profile: save the sample rates, format and channel masks supported
4086 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004087 if (audio_device_is_digital(device)) {
4088 devDesc->importAudioPort(profile);
4089 }
Eric Laurente552edb2014-03-10 17:42:56 -07004090 break;
4091 }
4092 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004093 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004094 continue;
4095 }
4096
Eric Laurent3974e3b2017-12-07 17:58:43 -08004097 if (!profile->canOpenNewIo()) {
4098 ALOGW("Max Output number %u already opened for this profile %s",
4099 profile->maxOpenCount, profile->getTagName().c_str());
4100 continue;
4101 }
4102
Eric Laurent83efe1c2017-07-09 16:51:08 -07004103 ALOGV("opening output for device %08x with params %s profile %p name %s",
4104 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004105 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004106 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004107 status_t status = desc->open(nullptr, device, address,
4108 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004109
Eric Laurentfe231122017-11-17 17:48:06 -08004110 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004111 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004112 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004113 char *param = audio_device_address_to_parameter(device, address);
4114 mpClientInterface->setParameters(output, String8(param));
4115 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004116 }
Phil Burk00eeb322016-03-31 12:41:00 -07004117 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004118 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004119 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004120 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004121 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004122 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004123 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004124 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004125 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4126 profile->pickAudioProfile(
4127 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004128 config.offload_info.sample_rate = config.sample_rate;
4129 config.offload_info.channel_mask = config.channel_mask;
4130 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004131
4132 status_t status = desc->open(&config, device, address, AUDIO_STREAM_DEFAULT,
4133 AUDIO_OUTPUT_FLAG_NONE, &output);
4134 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004135 output = AUDIO_IO_HANDLE_NONE;
4136 }
Eric Laurentd4692962014-05-05 18:13:44 -07004137 }
4138
Eric Laurentcf2c0212014-07-25 16:20:43 -07004139 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004141 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004142 sp<AudioPolicyMix> policyMix;
4143 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004144 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4145 address.string());
4146 }
François Gaffie036e1e92015-03-19 10:16:24 +01004147 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004148 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004149
Eric Laurent87ffa392015-05-22 10:32:38 -07004150 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4151 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004152 // no duplicated output for direct outputs and
4153 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004154 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004155
Eric Laurentd4692962014-05-05 18:13:44 -07004156 //TODO: configure audio effect output stage here
4157
4158 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004159 sp<SwAudioOutputDescriptor> dupOutputDesc =
4160 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4161 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4162 &duplicatedOutput);
4163 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004164 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004165 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004166 } else {
4167 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004168 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004169 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004170 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004171 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004172 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004173 }
Eric Laurente552edb2014-03-10 17:42:56 -07004174 }
4175 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004176 } else {
4177 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004179 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004180 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004181 profiles.removeAt(profile_index);
4182 profile_index--;
4183 } else {
4184 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004185 // Load digital format info only for digital devices
4186 if (audio_device_is_digital(device)) {
4187 devDesc->importAudioPort(profile);
4188 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004189
François Gaffie53615e22015-03-19 09:24:12 +01004190 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004191 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4192 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004193 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004194 NULL/*patch handle*/, address.string());
4195 }
Eric Laurente552edb2014-03-10 17:42:56 -07004196 ALOGV("checkOutputsForDevice(): adding output %d", output);
4197 }
4198 }
4199
4200 if (profiles.isEmpty()) {
4201 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4202 return BAD_VALUE;
4203 }
Eric Laurentd4692962014-05-05 18:13:44 -07004204 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004205 // check if one opened output is not needed any more after disconnecting one device
4206 for (size_t i = 0; i < mOutputs.size(); i++) {
4207 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004208 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004209 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004210 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004211 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004212 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004213 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004214 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4215 mOutputs.keyAt(i));
4216 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004217 }
Eric Laurente552edb2014-03-10 17:42:56 -07004218 }
4219 }
Eric Laurentd4692962014-05-05 18:13:44 -07004220 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004221 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004222 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4223 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004224 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004225 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004226 "clearing direct output profile %zu on module %s",
4227 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004228 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004229 }
4230 }
4231 }
4232 }
4233 return NO_ERROR;
4234}
4235
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004236status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004237 audio_policy_dev_state_t state,
4238 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004239 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004240{
Paul McLean9080a4c2015-06-18 08:24:02 -07004241 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004242 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004243
4244 if (audio_device_is_digital(device)) {
4245 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004246 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004247 }
4248
Eric Laurentd4692962014-05-05 18:13:44 -07004249 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4250 // first list already open inputs that can be routed to this device
4251 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4252 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004253 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004254 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4255 inputs.add(mInputs.keyAt(input_index));
4256 }
4257 }
4258
4259 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004260 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004261 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004262 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004263 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004264 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004265 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004266
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004267 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004268 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004269 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004270 profiles.add(profile);
Mikhail Naganovd4120142017-12-06 15:49:22 -08004271 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4272 profile_index, hwModule->getName());
Eric Laurent275e8e92014-11-30 15:14:47 -08004273 }
Eric Laurentd4692962014-05-05 18:13:44 -07004274 }
4275 }
4276 }
4277
4278 if (profiles.isEmpty() && inputs.isEmpty()) {
4279 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4280 return BAD_VALUE;
4281 }
4282
4283 // open inputs for matching profiles if needed. Direct inputs are also opened to
4284 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4285 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4286
Eric Laurent1c333e22014-05-20 10:48:17 -07004287 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004288
Eric Laurentd4692962014-05-05 18:13:44 -07004289 // nothing to do if one input is already opened for this profile
4290 size_t input_index;
4291 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4292 desc = mInputs.valueAt(input_index);
4293 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004294 if (audio_device_is_digital(device)) {
4295 devDesc->importAudioPort(profile);
4296 }
Eric Laurentd4692962014-05-05 18:13:44 -07004297 break;
4298 }
4299 }
4300 if (input_index != mInputs.size()) {
4301 continue;
4302 }
4303
Eric Laurent3974e3b2017-12-07 17:58:43 -08004304 if (!profile->canOpenNewIo()) {
4305 ALOGW("Max Input number %u already opened for this profile %s",
4306 profile->maxOpenCount, profile->getTagName().c_str());
4307 continue;
4308 }
4309
Eric Laurentfe231122017-11-17 17:48:06 -08004310 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004311 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004312 status_t status = desc->open(nullptr,
4313 device,
4314 address,
4315 AUDIO_SOURCE_MIC,
4316 AUDIO_INPUT_FLAG_NONE,
4317 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004318
Eric Laurentcf2c0212014-07-25 16:20:43 -07004319 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004320 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004321 char *param = audio_device_address_to_parameter(device, address);
4322 mpClientInterface->setParameters(input, String8(param));
4323 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004324 }
Phil Burk00eeb322016-03-31 12:41:00 -07004325 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004326 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004327 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004328 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004329 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004330 }
4331
4332 if (input != 0) {
4333 addInput(input, desc);
4334 }
4335 } // endif input != 0
4336
Eric Laurentcf2c0212014-07-25 16:20:43 -07004337 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004338 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004339 profiles.removeAt(profile_index);
4340 profile_index--;
4341 } else {
4342 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004343 if (audio_device_is_digital(device)) {
4344 devDesc->importAudioPort(profile);
4345 }
Eric Laurentd4692962014-05-05 18:13:44 -07004346 ALOGV("checkInputsForDevice(): adding input %d", input);
4347 }
4348 } // end scan profiles
4349
4350 if (profiles.isEmpty()) {
4351 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4352 return BAD_VALUE;
4353 }
4354 } else {
4355 // Disconnect
4356 // check if one opened input is not needed any more after disconnecting one device
4357 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4358 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004359 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004360 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4361 mInputs.keyAt(input_index));
4362 inputs.add(mInputs.keyAt(input_index));
4363 }
4364 }
4365 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004366 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004367 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004368 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004369 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004370 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004371 if (profile->supportDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004372 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4373 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004374 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004375 }
4376 }
4377 }
4378 } // end disconnect
4379
4380 return NO_ERROR;
4381}
4382
4383
Eric Laurente0720872014-03-11 09:30:41 -07004384void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004385{
4386 ALOGV("closeOutput(%d)", output);
4387
Eric Laurentc75307b2015-03-17 15:29:32 -07004388 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004389 if (outputDesc == NULL) {
4390 ALOGW("closeOutput() unknown output %d", output);
4391 return;
4392 }
François Gaffie036e1e92015-03-19 10:16:24 +01004393 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004394
Eric Laurente552edb2014-03-10 17:42:56 -07004395 // look for duplicated outputs connected to the output being removed.
4396 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004397 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004398 if (dupOutputDesc->isDuplicated() &&
4399 (dupOutputDesc->mOutput1 == outputDesc ||
4400 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004401 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004402 if (dupOutputDesc->mOutput1 == outputDesc) {
4403 outputDesc2 = dupOutputDesc->mOutput2;
4404 } else {
4405 outputDesc2 = dupOutputDesc->mOutput1;
4406 }
4407 // As all active tracks on duplicated output will be deleted,
4408 // and as they were also referenced on the other output, the reference
4409 // count for their stream type must be adjusted accordingly on
4410 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004411 const bool wasActive = outputDesc2->isActive();
4412 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4413 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004414 }
Eric Laurent733ce942017-12-07 12:18:25 -08004415 // stop() will be a no op if the output is still active but is needed in case all
4416 // active streams refcounts where cleared above
4417 if (wasActive) {
4418 outputDesc2->stop();
4419 }
Eric Laurente552edb2014-03-10 17:42:56 -07004420 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4421 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4422
4423 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004424 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004425 }
4426 }
4427
Eric Laurent05b90f82014-08-27 15:32:29 -07004428 nextAudioPortGeneration();
4429
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004430 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004431 if (index >= 0) {
4432 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004433 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004434 mAudioPatches.removeItemsAt(index);
4435 mpClientInterface->onAudioPatchListUpdate();
4436 }
4437
Eric Laurentfe231122017-11-17 17:48:06 -08004438 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004439
François Gaffie53615e22015-03-19 09:24:12 +01004440 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004441 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004442
4443 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4444 // no direct outputs are open.
4445 if (getMsdAudioOutDeviceTypes() != AUDIO_DEVICE_NONE) {
4446 bool directOutputOpen = false;
4447 for (size_t i = 0; i < mOutputs.size(); i++) {
4448 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4449 directOutputOpen = true;
4450 break;
4451 }
4452 }
4453 if (!directOutputOpen) {
4454 ALOGV("no direct outputs open, reset MSD patch");
4455 setMsdPatch();
4456 }
4457 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004458}
4459
4460void AudioPolicyManager::closeInput(audio_io_handle_t input)
4461{
4462 ALOGV("closeInput(%d)", input);
4463
4464 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4465 if (inputDesc == NULL) {
4466 ALOGW("closeInput() unknown input %d", input);
4467 return;
4468 }
4469
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004471
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004472 audio_devices_t device = inputDesc->mDevice;
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004473 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004474 if (index >= 0) {
4475 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004476 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004477 mAudioPatches.removeItemsAt(index);
4478 mpClientInterface->onAudioPatchListUpdate();
4479 }
4480
Eric Laurentfe231122017-11-17 17:48:06 -08004481 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004482 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004483
4484 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
4485 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
4486 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4487 SoundTrigger::setCaptureState(false);
4488 }
Eric Laurente552edb2014-03-10 17:42:56 -07004489}
4490
Eric Laurentc75307b2015-03-17 15:29:32 -07004491SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4492 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004493 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004494{
4495 SortedVector<audio_io_handle_t> outputs;
4496
4497 ALOGVV("getOutputsForDevice() device %04x", device);
4498 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004499 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004500 i, openOutputs.valueAt(i)->isDuplicated(),
4501 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004502 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4503 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4504 outputs.add(openOutputs.keyAt(i));
4505 }
4506 }
4507 return outputs;
4508}
4509
Mikhail Naganov37977152018-07-11 15:54:44 -07004510void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4511{
4512 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4513 // output is suspended before any tracks are moved to it
4514 checkA2dpSuspend();
4515 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004516 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004517 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004518 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004519 setMsdPatch();
4520 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004521}
4522
Eric Laurente0720872014-03-11 09:30:41 -07004523void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004524{
4525 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4526 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4527 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4528 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4529
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004530 // also take into account external policy-related changes: add all outputs which are
4531 // associated with policies in the "before" and "after" output vectors
4532 ALOGVV("checkOutputForStrategy(): policy related outputs");
4533 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004534 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004535 if (desc != 0 && desc->mPolicyMix != NULL) {
4536 srcOutputs.add(desc->mIoHandle);
4537 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4538 }
4539 }
4540 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004541 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004542 if (desc != 0 && desc->mPolicyMix != NULL) {
4543 dstOutputs.add(desc->mIoHandle);
4544 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4545 }
4546 }
4547
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004548 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004549 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4550 // audio from invalidated tracks will be rendered when unmuting
4551 uint32_t maxLatency = 0;
4552 for (audio_io_handle_t srcOut : srcOutputs) {
4553 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4554 if (desc != 0 && maxLatency < desc->latency()) {
4555 maxLatency = desc->latency();
4556 }
4557 }
Eric Laurente552edb2014-03-10 17:42:56 -07004558 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4559 strategy, srcOutputs[0], dstOutputs[0]);
4560 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004561 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004562 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4563 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004564 setStrategyMute(strategy, true, desc);
Eric Laurentac3a6902018-05-11 16:39:10 -07004565 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004566 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004567 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004568 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004569 if (source != 0){
4570 connectAudioSource(source);
4571 }
Eric Laurente552edb2014-03-10 17:42:56 -07004572 }
4573
4574 // Move effects associated to this strategy from previous output to new output
4575 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004576 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004577 }
4578 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004579 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004580 if (getStrategy((audio_stream_type_t)i) == strategy) {
4581 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004582 }
4583 }
4584 }
4585}
4586
Eric Laurente0720872014-03-11 09:30:41 -07004587void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004588{
François Gaffie2110e042015-03-24 08:41:51 +01004589 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004590 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004591 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004592 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004593 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004594 checkOutputForStrategy(STRATEGY_SONIFICATION);
4595 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004596 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004597 checkOutputForStrategy(STRATEGY_MEDIA);
4598 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004599 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004600}
4601
Eric Laurente0720872014-03-11 09:30:41 -07004602void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004603{
François Gaffie53615e22015-03-19 09:24:12 +01004604 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004605 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004606 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004607 return;
4608 }
4609
Eric Laurent3a4311c2014-03-17 12:00:47 -07004610 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004611 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4612 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4613 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004614
4615 // if suspended, restore A2DP output if:
4616 // ((SCO device is NOT connected) ||
4617 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4618 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004619 //
Eric Laurentf732e072016-08-03 19:30:28 -07004620 // if not suspended, suspend A2DP output if:
4621 // (SCO device is connected) &&
4622 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4623 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004624 //
4625 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004626 if (!isScoConnected ||
4627 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4628 AUDIO_POLICY_FORCE_BT_SCO) &&
4629 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4630 AUDIO_POLICY_FORCE_BT_SCO) &&
4631 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004632 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004633
4634 mpClientInterface->restoreOutput(a2dpOutput);
4635 mA2dpSuspended = false;
4636 }
4637 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004638 if (isScoConnected &&
4639 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4640 AUDIO_POLICY_FORCE_BT_SCO) ||
4641 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4642 AUDIO_POLICY_FORCE_BT_SCO) ||
4643 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004644 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004645
4646 mpClientInterface->suspendOutput(a2dpOutput);
4647 mA2dpSuspended = true;
4648 }
4649 }
4650}
4651
Eric Laurent97ac8712018-07-27 18:59:02 -07004652template <class IoDescriptor, class Filter>
4653sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4654 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4655{
4656 auto activeClients = desc->clientsList(true /*activeOnly*/);
4657 auto activeClientsWithRoute =
4658 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4659 active = activeClients.size() > 0;
4660 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4661 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4662 }
4663 return nullptr;
4664}
4665
4666template <class IoCollection, class Filter>
4667sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4668 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4669{
4670 sp<DeviceDescriptor> device;
4671 for (size_t i = 0; i < ioCollection.size(); i++) {
4672 auto desc = ioCollection.valueAt(i);
4673 bool active;
4674 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4675 if (active && curDevice == nullptr) {
4676 return nullptr;
4677 } else if (curDevice != nullptr) {
4678 device = curDevice;
4679 }
4680 }
4681 return device;
4682}
4683
Eric Laurentc75307b2015-03-17 15:29:32 -07004684audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4685 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004686{
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004687 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 if (index >= 0) {
4689 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4690 if (patchDesc->mUid != mUidCached) {
4691 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004692 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 return outputDesc->device();
4694 }
4695 }
4696
Eric Laurent97ac8712018-07-27 18:59:02 -07004697 // Honor explicit routing requests only if no client using default routing is active on this
4698 // input: a specific app can not force routing for other apps by setting a preferred device.
4699 bool active; // unused
4700 sp<DeviceDescriptor> deviceDesc =
4701 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
4702 if (deviceDesc != nullptr) {
4703 return deviceDesc->type();
Eric Laurentf3a5a602018-05-22 18:42:55 -07004704 }
4705
Eric Laurente552edb2014-03-10 17:42:56 -07004706 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004707 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004708 // use device for strategy enforced audible
4709 // 2: we are in call or the strategy phone is active on the output:
4710 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004711 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004712 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004713 // 4: the strategy for enforced audible is active but not enforced on the output:
4714 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004715 // 5: the strategy accessibility is active on the output:
4716 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004717 // 6: the strategy "respectful" sonification is active on the output:
4718 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004719 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004720 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004721 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004722 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004723 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004724 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004725
4726 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4727 // with a refined rule considering mutually exclusive devices (using same backend)
4728 // as opposed to all streams on the same audio HAL module.
Eric Laurent97ac8712018-07-27 18:59:02 -07004729 audio_devices_t device = AUDIO_DEVICE_NONE;
François Gaffiead3183e2015-03-18 16:55:35 +01004730 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004731 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004732 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4733 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004734 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004735 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004736 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004737 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004738 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
4739 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004740 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4741 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004742 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004743 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004744 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004745 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004746 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004747 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004748 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004749 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004750 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004751 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004752 }
4753
Eric Laurent1c333e22014-05-20 10:48:17 -07004754 ALOGV("getNewOutputDevice() selected device %x", device);
4755 return device;
4756}
4757
Eric Laurentfb66dd92016-01-28 18:32:03 -08004758audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004759{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004760 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004761
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004762 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 if (index >= 0) {
4764 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4765 if (patchDesc->mUid != mUidCached) {
4766 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004767 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004768 return inputDesc->mDevice;
4769 }
4770 }
4771
Eric Laurent97ac8712018-07-27 18:59:02 -07004772 // Honor explicit routing requests only if no client using default routing is active on this
4773 // input: a specific app can not force routing for other apps by setting a preferred device.
4774 bool active;
4775 sp<DeviceDescriptor> deviceDesc =
4776 findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4777 if (deviceDesc != nullptr) {
4778 return deviceDesc->type();
4779 }
4780
Eric Laurentdc95a252018-04-12 12:46:56 -07004781 // If we are not in call and no client is active on this input, this methods returns
4782 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4c1ef4b2018-11-13 16:46:26 -08004783 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004784 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4785 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4786 }
4787 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004788 device = getDeviceAndMixForInputSource(source);
4789 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004790
Eric Laurente552edb2014-03-10 17:42:56 -07004791 return device;
4792}
4793
Eric Laurent794fde22016-03-11 09:50:45 -08004794bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4795 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004796 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004797}
4798
Eric Laurente0720872014-03-11 09:30:41 -07004799uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004800 return (uint32_t)getStrategy(stream);
4801}
4802
Eric Laurente0720872014-03-11 09:30:41 -07004803audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004804 // By checking the range of stream before calling getStrategy, we avoid
4805 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4806 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004807 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 return AUDIO_DEVICE_NONE;
4809 }
Eric Laurentb0688d62018-08-14 15:49:18 -07004810 audio_devices_t activeDevices = AUDIO_DEVICE_NONE;
Eric Laurent28d09f02016-03-08 10:43:05 -08004811 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004812 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4813 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004814 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 }
Eric Laurent794fde22016-03-11 09:50:45 -08004816 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004817 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004818 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurentb0688d62018-08-14 15:49:18 -07004819 devices |= curDevices;
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004820 for (audio_io_handle_t output : getOutputsForDevice(curDevices, mOutputs)) {
4821 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004822 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004823 activeDevices |= outputDesc->device();
Eric Laurent28d09f02016-03-08 10:43:05 -08004824 }
4825 }
Eric Laurente552edb2014-03-10 17:42:56 -07004826 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004827
Eric Laurentb0688d62018-08-14 15:49:18 -07004828 // Favor devices selected on active streams if any to report correct device in case of
4829 // explicit device selection
4830 if (activeDevices != AUDIO_DEVICE_NONE) {
4831 devices = activeDevices;
4832 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004833 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4834 and doesn't really need to.*/
4835 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4836 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4837 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4838 }
Eric Laurente552edb2014-03-10 17:42:56 -07004839 return devices;
4840}
4841
François Gaffie2110e042015-03-24 08:41:51 +01004842routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4843{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004844 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004845 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004846}
4847
Eric Laurent97ac8712018-07-27 18:59:02 -07004848routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004849 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004850 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004851 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004852 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004853 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004854 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004855 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004856 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07004857 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004858}
4859
Eric Laurente0720872014-03-11 09:30:41 -07004860void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004861 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004862 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004863 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4864 updateDevicesAndOutputs();
4865 break;
4866 default:
4867 break;
4868 }
4869}
4870
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004871uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004872
4873 // skip beacon mute management if a dedicated TTS output is available
4874 if (mTtsOutputAvailable) {
4875 return 0;
4876 }
4877
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004878 switch(event) {
4879 case STARTING_OUTPUT:
4880 mBeaconMuteRefCount++;
4881 break;
4882 case STOPPING_OUTPUT:
4883 if (mBeaconMuteRefCount > 0) {
4884 mBeaconMuteRefCount--;
4885 }
4886 break;
4887 case STARTING_BEACON:
4888 mBeaconPlayingRefCount++;
4889 break;
4890 case STOPPING_BEACON:
4891 if (mBeaconPlayingRefCount > 0) {
4892 mBeaconPlayingRefCount--;
4893 }
4894 break;
4895 }
4896
4897 if (mBeaconMuteRefCount > 0) {
4898 // any playback causes beacon to be muted
4899 return setBeaconMute(true);
4900 } else {
4901 // no other playback: unmute when beacon starts playing, mute when it stops
4902 return setBeaconMute(mBeaconPlayingRefCount == 0);
4903 }
4904}
4905
4906uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4907 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4908 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4909 // keep track of muted state to avoid repeating mute/unmute operations
4910 if (mBeaconMuted != mute) {
4911 // mute/unmute AUDIO_STREAM_TTS on all outputs
4912 ALOGV("\t muting %d", mute);
4913 uint32_t maxLatency = 0;
4914 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004915 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004916 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004917 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004918 0 /*delay*/, AUDIO_DEVICE_NONE);
4919 const uint32_t latency = desc->latency() * 2;
4920 if (latency > maxLatency) {
4921 maxLatency = latency;
4922 }
4923 }
4924 mBeaconMuted = mute;
4925 return maxLatency;
4926 }
4927 return 0;
4928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004931 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004932{
Eric Laurent97ac8712018-07-27 18:59:02 -07004933 // Honor explicit routing requests only if all active clients have a preferred route in which
4934 // case the last active client route is used
4935 sp<DeviceDescriptor> deviceDesc = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
4936 if (deviceDesc != nullptr) {
4937 return deviceDesc->type();
Paul McLeanaa981192015-03-21 09:55:15 -07004938 }
4939
Eric Laurente552edb2014-03-10 17:42:56 -07004940 if (fromCache) {
4941 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4942 strategy, mDeviceForStrategy[strategy]);
4943 return mDeviceForStrategy[strategy];
4944 }
François Gaffie2110e042015-03-24 08:41:51 +01004945 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004946}
4947
Eric Laurente0720872014-03-11 09:30:41 -07004948void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004949{
4950 for (int i = 0; i < NUM_STRATEGIES; i++) {
4951 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4952 }
4953 mPreviousOutputs = mOutputs;
4954}
4955
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004956uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004957 audio_devices_t prevDevice,
4958 uint32_t delayMs)
4959{
4960 // mute/unmute strategies using an incompatible device combination
4961 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4962 // if unmuting, unmute only after the specified delay
4963 if (outputDesc->isDuplicated()) {
4964 return 0;
4965 }
4966
4967 uint32_t muteWaitMs = 0;
4968 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004969 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004970
4971 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4972 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004973 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004974 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4975 bool doMute = false;
4976
4977 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4978 doMute = true;
4979 outputDesc->mStrategyMutedByDevice[i] = true;
4980 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4981 doMute = true;
4982 outputDesc->mStrategyMutedByDevice[i] = false;
4983 }
Eric Laurent99401132014-05-07 19:48:15 -07004984 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004985 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004986 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004987 // skip output if it does not share any device with current output
4988 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4989 == AUDIO_DEVICE_NONE) {
4990 continue;
4991 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004992 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004993 mute ? "muting" : "unmuting", i, curDevice);
4994 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004995 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004996 if (mute) {
4997 // FIXME: should not need to double latency if volume could be applied
4998 // immediately by the audioflinger mixer. We must account for the delay
4999 // between now and the next time the audioflinger thread for this output
5000 // will process a buffer (which corresponds to one buffer size,
5001 // usually 1/2 or 1/4 of the latency).
5002 if (muteWaitMs < desc->latency() * 2) {
5003 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005004 }
5005 }
5006 }
5007 }
5008 }
5009 }
5010
Eric Laurent99401132014-05-07 19:48:15 -07005011 // temporary mute output if device selection changes to avoid volume bursts due to
5012 // different per device volumes
5013 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005014 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5015 // temporary mute duration is conservatively set to 4 times the reported latency
5016 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5017 if (muteWaitMs < tempMuteWaitMs) {
5018 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005019 }
Eric Laurentdc462862016-07-19 12:29:53 -07005020
Eric Laurent99401132014-05-07 19:48:15 -07005021 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005022 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005023 // make sure that we do not start the temporary mute period too early in case of
5024 // delayed device change
5025 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005026 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005027 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005028 }
5029 }
5030 }
5031
Eric Laurente552edb2014-03-10 17:42:56 -07005032 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5033 if (muteWaitMs > delayMs) {
5034 muteWaitMs -= delayMs;
5035 usleep(muteWaitMs * 1000);
5036 return muteWaitMs;
5037 }
5038 return 0;
5039}
5040
Eric Laurentc75307b2015-03-17 15:29:32 -07005041uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005042 audio_devices_t device,
5043 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005045 audio_patch_handle_t *patchHandle,
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005046 const char *address,
5047 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005048{
Eric Laurentc75307b2015-03-17 15:29:32 -07005049 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005050 AudioParameter param;
5051 uint32_t muteWaitMs;
5052
5053 if (outputDesc->isDuplicated()) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005054 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs,
5055 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
5056 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs,
5057 nullptr /* patchHandle */, nullptr /* address */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005058 return muteWaitMs;
5059 }
5060 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5061 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005062 if ((device != AUDIO_DEVICE_NONE) &&
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005063 ((device & outputDesc->supportedDevices()) == AUDIO_DEVICE_NONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005064 return 0;
5065 }
5066
5067 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005068 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005069
5070 audio_devices_t prevDevice = outputDesc->mDevice;
5071
Paul McLeanaa981192015-03-21 09:55:15 -07005072 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005073
5074 if (device != AUDIO_DEVICE_NONE) {
5075 outputDesc->mDevice = device;
5076 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005077
5078 // if the outputs are not materially active, there is no need to mute.
5079 if (requiresMuteCheck) {
5080 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5081 } else {
5082 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5083 muteWaitMs = 0;
5084 }
Eric Laurente552edb2014-03-10 17:42:56 -07005085
5086 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005087 // the requested device is AUDIO_DEVICE_NONE
5088 // OR the requested device is the same as current device
5089 // AND force is not specified
5090 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005091 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005092 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5093 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005094 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005095 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005096 return muteWaitMs;
5097 }
5098
5099 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005100
Eric Laurente552edb2014-03-10 17:42:56 -07005101 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005102 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005103 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005104 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005105 DeviceVector deviceList;
5106 if ((address == NULL) || (strlen(address) == 0)) {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005107 deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
Eric Laurentc40d9692016-04-13 19:14:13 -07005108 } else {
Mikhail Naganov708e0382018-05-30 09:53:04 -07005109 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
5110 device, String8(address));
5111 if (deviceDesc) deviceList.add(deviceDesc);
Eric Laurentc40d9692016-04-13 19:14:13 -07005112 }
5113
Eric Laurent1c333e22014-05-20 10:48:17 -07005114 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005115 PatchBuilder patchBuilder;
5116 patchBuilder.addSource(outputDesc);
Eric Laurent1c333e22014-05-20 10:48:17 -07005117 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005118 patchBuilder.addSink(deviceList.itemAt(i));
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07005120 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005121 }
5122 }
Eric Laurente552edb2014-03-10 17:42:56 -07005123
5124 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005125 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005126
5127 return muteWaitMs;
5128}
5129
Eric Laurentc75307b2015-03-17 15:29:32 -07005130status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005131 int delayMs,
5132 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005133{
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 ssize_t index;
5135 if (patchHandle) {
5136 index = mAudioPatches.indexOfKey(*patchHandle);
5137 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005138 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005139 }
5140 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005141 return INVALID_OPERATION;
5142 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5144 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005145 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005146 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005147 removeAudioPatch(patchDesc->mHandle);
5148 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005149 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005150 return status;
5151}
5152
5153status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5154 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005155 bool force,
5156 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005157{
5158 status_t status = NO_ERROR;
5159
Eric Laurent1f2f2232014-06-02 12:01:23 -07005160 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005161 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5162 inputDesc->mDevice = device;
5163
Mikhail Naganov708e0382018-05-30 09:53:04 -07005164 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromTypeMask(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005165 if (!deviceList.isEmpty()) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005166 PatchBuilder patchBuilder;
5167 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005168 // AUDIO_SOURCE_HOTWORD is for internal use only:
5169 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005170 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5171 auto result = usecase;
5172 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5173 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5174 }
5175 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005176 //only one input device for now
Mikhail Naganovdc769682018-05-04 15:34:08 -07005177 addSource(deviceList.itemAt(0));
5178 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005179 }
5180 }
5181 return status;
5182}
5183
Eric Laurent6a94d692014-05-20 11:18:06 -07005184status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5185 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005186{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005187 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 ssize_t index;
5189 if (patchHandle) {
5190 index = mAudioPatches.indexOfKey(*patchHandle);
5191 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005192 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 }
5194 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005195 return INVALID_OPERATION;
5196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5198 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005199 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005200 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 removeAudioPatch(patchDesc->mHandle);
5202 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005203 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005204 return status;
5205}
5206
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005207sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005208 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005209 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005210 audio_format_t& format,
5211 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005212 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005213{
5214 // Choose an input profile based on the requested capture parameters: select the first available
5215 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005216 //
5217 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5218 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005219
Glenn Kasten730b9262018-03-29 15:01:26 -07005220 sp<IOProfile> firstInexact;
5221 uint32_t updatedSamplingRate = 0;
5222 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5223 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005224 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005225 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005226 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005227 //updatedFormat = format;
Eric Laurent275e8e92014-11-30 15:14:47 -08005228 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005229 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005230 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005231 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005232 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005233 &channelMask /*updatedChannelMask*/,
5234 // FIXME ugly cast
5235 (audio_output_flags_t) flags,
5236 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005237 return profile;
5238 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005239 if (firstInexact == nullptr && profile->isCompatibleProfile(device, address,
5240 samplingRate,
5241 &updatedSamplingRate,
5242 format,
5243 &updatedFormat,
5244 channelMask,
5245 &updatedChannelMask,
5246 // FIXME ugly cast
5247 (audio_output_flags_t) flags,
5248 false /*exactMatchRequiredForInputFlags*/)) {
5249 firstInexact = profile;
5250 }
5251
Eric Laurente552edb2014-03-10 17:42:56 -07005252 }
5253 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005254 if (firstInexact != nullptr) {
5255 samplingRate = updatedSamplingRate;
5256 format = updatedFormat;
5257 channelMask = updatedChannelMask;
5258 return firstInexact;
5259 }
Eric Laurente552edb2014-03-10 17:42:56 -07005260 return NULL;
5261}
5262
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005263
5264audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005265 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005266{
Eric Laurent97ac8712018-07-27 18:59:02 -07005267 // Honor explicit routing requests only if all active clients have a preferred route in which
5268 // case the last active client route is used
5269 sp<DeviceDescriptor> deviceDesc =
5270 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
5271 if (deviceDesc != nullptr) {
5272 return deviceDesc->type();
5273 }
5274
5275
François Gaffie036e1e92015-03-19 10:16:24 +01005276 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5277 audio_devices_t selectedDeviceFromMix =
5278 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005279
François Gaffie036e1e92015-03-19 10:16:24 +01005280 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5281 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005282 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005283 return getDeviceForInputSource(inputSource);
5284}
5285
5286audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5287{
Eric Laurent97ac8712018-07-27 18:59:02 -07005288 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005289}
5290
Eric Laurente0720872014-03-11 09:30:41 -07005291float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005292 int index,
5293 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005294{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005295 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005296
5297 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5298 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5299 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5300 // the ringtone volume
5301 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5302 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5303 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5304 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5305 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5306 }
5307
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005308 // in-call: always cap volume by voice volume + some low headroom
5309 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005310 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005311 switch (stream) {
5312 case AUDIO_STREAM_SYSTEM:
5313 case AUDIO_STREAM_RING:
5314 case AUDIO_STREAM_MUSIC:
5315 case AUDIO_STREAM_ALARM:
5316 case AUDIO_STREAM_NOTIFICATION:
5317 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5318 case AUDIO_STREAM_DTMF:
5319 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005320 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005321 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005322 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005323 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005324 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005325 if (volumeDB > maxVoiceVolDb) {
5326 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5327 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5328 volumeDB = maxVoiceVolDb;
5329 }
5330 } break;
5331 default:
5332 break;
5333 }
5334 }
5335
Eric Laurente552edb2014-03-10 17:42:56 -07005336 // if a headset is connected, apply the following rules to ring tones and notifications
5337 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005338 // - always attenuate notifications volume by 6dB
5339 // - attenuate ring tones volume by 6dB unless music is not playing and
5340 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005341 // - if music is playing, always limit the volume to current music volume,
5342 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005343 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005344 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5345 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5346 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005347 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005348 AUDIO_DEVICE_OUT_USB_HEADSET |
5349 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005350 ((stream_strategy == STRATEGY_SONIFICATION)
5351 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005352 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005353 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005354 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005355 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005356 // when the phone is ringing we must consider that music could have been paused just before
5357 // by the music application and behave as if music was active if the last music track was
5358 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005359 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005360 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005361 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005362 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005363 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005364 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5365 musicDevice),
5366 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005367 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5368 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005369 if (volumeDB > minVolDB) {
5370 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005371 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005372 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005373 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5374 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5375 // on A2DP, also ensure notification volume is not too low compared to media when
5376 // intended to be played
5377 if ((volumeDB > -96.0f) &&
5378 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5379 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5380 stream, device,
5381 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5382 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5383 }
5384 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005385 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5386 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005387 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005388 }
5389 }
5390
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005391 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005392}
5393
Eric Laurent3839bc02018-07-10 18:33:34 -07005394int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5395 audio_stream_type_t srcStream,
5396 audio_stream_type_t dstStream)
5397{
5398 if (srcStream == dstStream) {
5399 return srcIndex;
5400 }
5401 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5402 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5403 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5404 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5405
5406 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5407}
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005410 int index,
5411 const sp<AudioOutputDescriptor>& outputDesc,
5412 audio_devices_t device,
5413 int delayMs,
5414 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005415{
Eric Laurente552edb2014-03-10 17:42:56 -07005416 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005417 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005418 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005419 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005420 return NO_ERROR;
5421 }
François Gaffie2110e042015-03-24 08:41:51 +01005422 audio_policy_forced_cfg_t forceUseForComm =
5423 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005424 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005425 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5426 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005427 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005428 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005429 return INVALID_OPERATION;
5430 }
5431
Eric Laurentc75307b2015-03-17 15:29:32 -07005432 if (device == AUDIO_DEVICE_NONE) {
5433 device = outputDesc->device();
5434 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005435
Eric Laurentffbc80f2015-03-18 18:30:19 -07005436 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005437 if (outputDesc->isFixedVolume(device) ||
5438 // Force VoIP volume to max for bluetooth SCO
5439 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5440 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005441 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005442 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005443
Eric Laurentffbc80f2015-03-18 18:30:19 -07005444 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005445
Eric Laurent3b73df72014-03-11 09:06:29 -07005446 if (stream == AUDIO_STREAM_VOICE_CALL ||
5447 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005448 float voiceVolume;
5449 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005450 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005451 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005452 } else {
5453 voiceVolume = 1.0;
5454 }
5455
Eric Laurent18fba842016-03-31 14:41:26 -07005456 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005457 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5458 mLastVoiceVolume = voiceVolume;
5459 }
5460 }
5461
5462 return NO_ERROR;
5463}
5464
Eric Laurentc75307b2015-03-17 15:29:32 -07005465void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5466 audio_devices_t device,
5467 int delayMs,
5468 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005469{
Eric Laurentc75307b2015-03-17 15:29:32 -07005470 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005471
Eric Laurent794fde22016-03-11 09:50:45 -08005472 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005473 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005474 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005475 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005476 device,
5477 delayMs,
5478 force);
5479 }
5480}
5481
Eric Laurente0720872014-03-11 09:30:41 -07005482void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005483 bool on,
5484 const sp<AudioOutputDescriptor>& outputDesc,
5485 int delayMs,
5486 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005487{
Eric Laurent72249d52015-06-08 11:12:15 -07005488 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5489 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005490 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005491 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005492 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005493 }
5494 }
5495}
5496
Eric Laurente0720872014-03-11 09:30:41 -07005497void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005498 bool on,
5499 const sp<AudioOutputDescriptor>& outputDesc,
5500 int delayMs,
5501 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005502{
Eric Laurente552edb2014-03-10 17:42:56 -07005503 if (device == AUDIO_DEVICE_NONE) {
5504 device = outputDesc->device();
5505 }
5506
Eric Laurentc75307b2015-03-17 15:29:32 -07005507 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5508 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005509
5510 if (on) {
5511 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005512 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005513 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005514 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005515 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005516 }
5517 }
5518 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5519 outputDesc->mMuteCount[stream]++;
5520 } else {
5521 if (outputDesc->mMuteCount[stream] == 0) {
5522 ALOGV("setStreamMute() unmuting non muted stream!");
5523 return;
5524 }
5525 if (--outputDesc->mMuteCount[stream] == 0) {
5526 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005527 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005528 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005529 device,
5530 delayMs);
5531 }
5532 }
5533}
5534
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005535audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5536{
5537 // flags to stream type mapping
5538 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5539 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5540 }
5541 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5542 return AUDIO_STREAM_BLUETOOTH_SCO;
5543 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005544 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5545 return AUDIO_STREAM_TTS;
5546 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005547
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005548 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005549}
Eric Laurente83b55d2014-11-14 10:06:21 -08005550
François Gaffie53615e22015-03-19 09:24:12 +01005551bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5552{
Eric Laurente83b55d2014-11-14 10:06:21 -08005553 // has flags that map to a strategy?
5554 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5555 return true;
5556 }
5557
5558 // has known usage?
5559 switch (paa->usage) {
5560 case AUDIO_USAGE_UNKNOWN:
5561 case AUDIO_USAGE_MEDIA:
5562 case AUDIO_USAGE_VOICE_COMMUNICATION:
5563 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5564 case AUDIO_USAGE_ALARM:
5565 case AUDIO_USAGE_NOTIFICATION:
5566 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5567 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5568 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5569 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5570 case AUDIO_USAGE_NOTIFICATION_EVENT:
5571 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5572 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5573 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5574 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005575 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005576 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005577 break;
5578 default:
5579 return false;
5580 }
5581 return true;
5582}
5583
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005584bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005585 routing_strategy strategy, uint32_t inPastMs,
5586 nsecs_t sysTime) const
5587{
5588 if ((sysTime == 0) && (inPastMs != 0)) {
5589 sysTime = systemTime();
5590 }
Eric Laurent794fde22016-03-11 09:50:45 -08005591 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005592 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005593 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005594 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5595 return true;
5596 }
5597 }
5598 return false;
5599}
5600
Eric Laurent484e9272018-06-07 17:29:23 -07005601bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<AudioOutputDescriptor>& outputDesc,
5602 routing_strategy strategy, uint32_t inPastMs,
5603 nsecs_t sysTime) const
5604{
5605 for (size_t i = 0; i < mOutputs.size(); i++) {
5606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5607 if (outputDesc->sharesHwModuleWith(desc)
5608 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5609 return true;
5610 }
5611 }
5612 return false;
5613}
5614
François Gaffie2110e042015-03-24 08:41:51 +01005615audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5616{
5617 return mEngine->getForceUse(usage);
5618}
5619
5620bool AudioPolicyManager::isInCall()
5621{
5622 return isStateInCall(mEngine->getPhoneState());
5623}
5624
5625bool AudioPolicyManager::isStateInCall(int state)
5626{
5627 return is_state_in_call(state);
5628}
5629
Eric Laurentd60560a2015-04-10 11:31:20 -07005630void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5631{
5632 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005633 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5634 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5635 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5636 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005637 }
5638 }
5639
5640 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5641 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5642 bool release = false;
5643 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5644 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5645 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5646 source->ext.device.type == deviceDesc->type()) {
5647 release = true;
5648 }
5649 }
5650 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5651 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5652 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5653 sink->ext.device.type == deviceDesc->type()) {
5654 release = true;
5655 }
5656 }
5657 if (release) {
5658 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5659 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5660 }
5661 }
5662}
5663
Phil Burk09bc4612016-02-24 15:58:15 -08005664// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005665void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5666 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005667 // TODO Set this based on Config properties.
5668 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005669
5670 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5671 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005672 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005673
jiabin81772902018-04-02 17:52:27 -07005674 // If MANUAL, keep the supported surround sound formats as current enabled ones.
5675 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
5676 formats.clear();
5677 for (auto it = mSurroundFormats.begin(); it != mSurroundFormats.end(); it++) {
5678 formats.add(*it);
Phil Burk09bc4612016-02-24 15:58:15 -08005679 }
jiabin81772902018-04-02 17:52:27 -07005680 // Always enable IEC61937 when in MANUAL mode.
5681 formats.add(AUDIO_FORMAT_IEC61937);
5682 } else { // NEVER, AUTO or ALWAYS
5683 // Analyze original support for various formats.
5684 bool supportsAC3 = false;
5685 bool supportsOtherSurround = false;
5686 bool supportsIEC61937 = false;
5687 mSurroundFormats.clear();
5688 for (ssize_t formatIndex = 0; formatIndex < (ssize_t)formats.size(); formatIndex++) {
5689 audio_format_t format = formats[formatIndex];
5690 switch (format) {
5691 case AUDIO_FORMAT_AC3:
5692 supportsAC3 = true;
5693 break;
5694 case AUDIO_FORMAT_E_AC3:
5695 case AUDIO_FORMAT_DTS:
5696 case AUDIO_FORMAT_DTS_HD:
5697 // If ALWAYS, remove all other surround formats here
5698 // since we will add them later.
5699 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5700 formats.removeAt(formatIndex);
5701 formatIndex--;
5702 }
5703 supportsOtherSurround = true;
5704 break;
5705 case AUDIO_FORMAT_IEC61937:
5706 supportsIEC61937 = true;
5707 break;
5708 default:
5709 break;
5710 }
5711 }
Phil Burk09bc4612016-02-24 15:58:15 -08005712
jiabin81772902018-04-02 17:52:27 -07005713 // Modify formats based on surround preferences.
5714 // If NEVER, remove support for surround formats.
5715 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5716 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5717 // Remove surround sound related formats.
5718 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5719 audio_format_t format = formats[formatIndex];
5720 switch(format) {
5721 case AUDIO_FORMAT_AC3:
5722 case AUDIO_FORMAT_E_AC3:
5723 case AUDIO_FORMAT_DTS:
5724 case AUDIO_FORMAT_DTS_HD:
5725 case AUDIO_FORMAT_IEC61937:
5726 formats.removeAt(formatIndex);
5727 break;
5728 default:
5729 formatIndex++; // keep it
5730 break;
5731 }
5732 }
5733 supportsAC3 = false;
5734 supportsOtherSurround = false;
5735 supportsIEC61937 = false;
5736 }
5737 } else { // AUTO or ALWAYS
5738 // Most TVs support AC3 even if they do not report it in the EDID.
5739 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5740 && !supportsAC3) {
5741 formats.add(AUDIO_FORMAT_AC3);
5742 supportsAC3 = true;
5743 }
5744
5745 // If ALWAYS, add support for raw surround formats if all are missing.
5746 // This assumes that if any of these formats are reported by the HAL
5747 // then the report is valid and should not be modified.
5748 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5749 formats.add(AUDIO_FORMAT_E_AC3);
5750 formats.add(AUDIO_FORMAT_DTS);
5751 formats.add(AUDIO_FORMAT_DTS_HD);
5752 supportsOtherSurround = true;
5753 }
5754
5755 // Add support for IEC61937 if any raw surround supported.
5756 // The HAL could do this but add it here, just in case.
5757 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5758 formats.add(AUDIO_FORMAT_IEC61937);
5759 supportsIEC61937 = true;
5760 }
5761
5762 // Add reported surround sound formats to enabled surround formats.
5763 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
Phil Burk07ac1142016-03-25 13:39:29 -07005764 audio_format_t format = formats[formatIndex];
Mikhail Naganov02743e22018-11-28 15:56:55 -08005765 if (mConfig.getSurroundFormats().count(format) != 0) {
5766 mSurroundFormats.insert(format);
Phil Burk07ac1142016-03-25 13:39:29 -07005767 }
Phil Burk09bc4612016-02-24 15:58:15 -08005768 }
Phil Burk07ac1142016-03-25 13:39:29 -07005769 }
Phil Burk09bc4612016-02-24 15:58:15 -08005770 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005771}
5772
5773// Modify the list of channel masks supported.
5774void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5775 ChannelsVector &channelMasks = *channelMasksPtr;
5776 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5777 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5778
5779 // If NEVER, then remove support for channelMasks > stereo.
5780 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5781 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5782 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5783 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5784 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5785 channelMasks.removeAt(maskIndex);
5786 } else {
5787 maskIndex++;
5788 }
5789 }
jiabin81772902018-04-02 17:52:27 -07005790 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5791 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5792 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005793 bool supports5dot1 = false;
5794 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005795 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005796 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5797 supports5dot1 = true;
5798 break;
5799 }
5800 }
5801 // If not then add 5.1 support.
5802 if (!supports5dot1) {
5803 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5804 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5805 }
Phil Burk09bc4612016-02-24 15:58:15 -08005806 }
5807}
5808
Phil Burk00eeb322016-03-31 12:41:00 -07005809void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5810 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005811 AudioProfileVector &profiles)
5812{
5813 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005814
François Gaffie112b0af2015-11-19 16:13:25 +01005815 // Format MUST be checked first to update the list of AudioProfile
5816 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005817 reply = mpClientInterface->getParameters(
5818 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005819 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005820 AudioParameter repliedParameters(reply);
5821 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005822 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005823 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5824 return;
5825 }
Phil Burk09bc4612016-02-24 15:58:15 -08005826 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005827 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005828 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005829 }
Phil Burk09bc4612016-02-24 15:58:15 -08005830 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005831 }
François Gaffie112b0af2015-11-19 16:13:25 +01005832
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005833 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005834 ChannelsVector channelMasks;
5835 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005836 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005837 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005838
5839 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005840 reply = mpClientInterface->getParameters(
5841 ioHandle,
5842 requestedParameters.toString() + ";" +
5843 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005844 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005845 AudioParameter repliedParameters(reply);
5846 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005847 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005848 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005849 }
5850 }
5851 if (profiles.hasDynamicChannelsFor(format)) {
5852 reply = mpClientInterface->getParameters(ioHandle,
5853 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005854 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005855 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005856 AudioParameter repliedParameters(reply);
5857 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005858 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005859 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005860 if (device == AUDIO_DEVICE_OUT_HDMI) {
5861 filterSurroundChannelMasks(&channelMasks);
5862 }
François Gaffie112b0af2015-11-19 16:13:25 +01005863 }
5864 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005865 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005866 }
5867}
Eric Laurentd60560a2015-04-10 11:31:20 -07005868
Mikhail Naganovdc769682018-05-04 15:34:08 -07005869status_t AudioPolicyManager::installPatch(const char *caller,
5870 audio_patch_handle_t *patchHandle,
5871 AudioIODescriptorInterface *ioDescriptor,
5872 const struct audio_patch *patch,
5873 int delayMs)
5874{
5875 ssize_t index = mAudioPatches.indexOfKey(
5876 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5877 *patchHandle : ioDescriptor->getPatchHandle());
5878 sp<AudioPatch> patchDesc;
5879 status_t status = installPatch(
5880 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5881 if (status == NO_ERROR) {
5882 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5883 }
5884 return status;
5885}
5886
5887status_t AudioPolicyManager::installPatch(const char *caller,
5888 ssize_t index,
5889 audio_patch_handle_t *patchHandle,
5890 const struct audio_patch *patch,
5891 int delayMs,
5892 uid_t uid,
5893 sp<AudioPatch> *patchDescPtr)
5894{
5895 sp<AudioPatch> patchDesc;
5896 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5897 if (index >= 0) {
5898 patchDesc = mAudioPatches.valueAt(index);
5899 afPatchHandle = patchDesc->mAfPatchHandle;
5900 }
5901
5902 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5903 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5904 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5905 if (status == NO_ERROR) {
5906 if (index < 0) {
5907 patchDesc = new AudioPatch(patch, uid);
5908 addAudioPatch(patchDesc->mHandle, patchDesc);
5909 } else {
5910 patchDesc->mPatch = *patch;
5911 }
5912 patchDesc->mAfPatchHandle = afPatchHandle;
5913 if (patchHandle) {
5914 *patchHandle = patchDesc->mHandle;
5915 }
5916 nextAudioPortGeneration();
5917 mpClientInterface->onAudioPatchListUpdate();
5918 }
5919 if (patchDescPtr) *patchDescPtr = patchDesc;
5920 return status;
5921}
5922
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005923} // namespace android