blob: 47e6016614f69c794d56015ba14a00b58ddf3934 [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 Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Eric Laurentd4692962014-05-05 18:13:44 -070041
François Gaffie2110e042015-03-24 08:41:51 +010042#include <AudioPolicyManagerInterface.h>
43#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070044#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070045#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080047#include <media/AudioPolicyHelper.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070049#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070051#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010053#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010054#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010055#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurentdc462862016-07-19 12:29:53 -070059//FIXME: workaround for truncated touch sounds
60// to be removed when the problem is handled by system UI
61#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070062
63// Largest difference in dB on earpiece in call between the voice volume and another
64// media / notification / system volume.
65constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
66
Mikhail Naganov15be9d22017-11-08 14:18:13 +110067// Compressed formats for MSD module, ordered from most preferred to least preferred.
68static const std::vector<audio_format_t> compressedFormatsOrder = {{
69 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
70 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
71// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
72static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
73 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
74 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
75 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
76
Eric Laurente552edb2014-03-10 17:42:56 -070077// ----------------------------------------------------------------------------
78// AudioPolicyInterface implementation
79// ----------------------------------------------------------------------------
80
Eric Laurente0720872014-03-11 09:30:41 -070081status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080082 audio_policy_dev_state_t state,
83 const char *device_address,
84 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070085{
jiabina7b43792018-02-15 16:04:46 -080086 status_t status = setDeviceConnectionStateInt(device, state, device_address, device_name);
87 nextAudioPortGeneration();
88 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -080089}
90
François Gaffie11d30102018-11-02 16:09:09 +010091void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
92 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +020093{
François Gaffie11d30102018-11-02 16:09:09 +010094 AudioParameter param(device->address());
François Gaffie44481e72016-04-20 07:49:57 +020095 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070096 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +010097 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +020098 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
99}
100
François Gaffie11d30102018-11-02 16:09:09 +0100101status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
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",
François Gaffie11d30102018-11-02 16:09:09 +0100107 deviceType, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -0700108
109 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100110 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700111
François Gaffie11d30102018-11-02 16:09:09 +0100112 sp<DeviceDescriptor> device =
113 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -0800114
Eric Laurente552edb2014-03-10 17:42:56 -0700115 // handle output devices
François Gaffie11d30102018-11-02 16:09:09 +0100116 if (audio_is_output_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700117 SortedVector <audio_io_handle_t> outputs;
118
François Gaffie11d30102018-11-02 16:09:09 +0100119 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700120
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) {
François Gaffie11d30102018-11-02 16:09:09 +0100129 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700130 return INVALID_OPERATION;
131 }
François Gaffie11d30102018-11-02 16:09:09 +0100132 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700133
Eric Laurente552edb2014-03-10 17:42:56 -0700134 // register new device as available
François Gaffie11d30102018-11-02 16:09:09 +0100135 index = mAvailableOutputDevices.add(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700136 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100137 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(deviceType);
Eric Laurentcf817a22014-08-04 20:36:31 -0700138 if (module == 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100139 ALOGD("setDeviceConnectionState() could not find HW module for device %s",
140 device->toString().c_str());
141 mAvailableOutputDevices.remove(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700142 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...)
François Gaffie11d30102018-11-02 16:09:09 +0100151 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200152
François Gaffie11d30102018-11-02 16:09:09 +0100153 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
154 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200155
François Gaffie11d30102018-11-02 16:09:09 +0100156 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700157 return INVALID_OPERATION;
158 }
François Gaffie2110e042015-03-24 08:41:51 +0100159 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100160 mEngine->setDeviceConnectionState(device, state);
François Gaffie2110e042015-03-24 08:41:51 +0100161
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700162 // outputs should never be empty here
163 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
164 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100165 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800166
Eric Laurent3ae5f312015-02-03 17:12:08 -0800167 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700168 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700169 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700170 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100171 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700172 return INVALID_OPERATION;
173 }
174
François Gaffie11d30102018-11-02 16:09:09 +0100175 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700176
Paul McLeane743a472015-01-28 11:07:31 -0800177 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100178 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700179
Eric Laurente552edb2014-03-10 17:42:56 -0700180 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100181 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700182
François Gaffie11d30102018-11-02 16:09:09 +0100183 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100184
185 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100186 mEngine->setDeviceConnectionState(device, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700187 } break;
188
189 default:
François Gaffie11d30102018-11-02 16:09:09 +0100190 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700191 return BAD_VALUE;
192 }
193
Mikhail Naganov37977152018-07-11 15:54:44 -0700194 checkForDeviceAndOutputChanges([&]() {
195 // outputs must be closed after checkOutputForAllStrategies() is executed
196 if (!outputs.isEmpty()) {
197 for (audio_io_handle_t output : outputs) {
198 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100199 // close unused outputs after device disconnection or direct outputs that have
200 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700201 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
202 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
203 (desc->mDirectOpenCount == 0))) {
204 closeOutput(output);
205 }
Eric Laurente552edb2014-03-10 17:42:56 -0700206 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700207 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
208 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700209 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700210 return false;
211 });
Eric Laurente552edb2014-03-10 17:42:56 -0700212
Eric Laurent87ffa392015-05-22 10:32:38 -0700213 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100214 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
215 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700216 }
François Gaffie11d30102018-11-02 16:09:09 +0100217 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700218 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700219 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
220 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100221 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700222 // do not force device change on duplicated output because if device is 0, it will
223 // also force a device 0 for the two outputs it is duplicated to which may override
224 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100225 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100226 && !desc->isDuplicated()
François Gaffie11d30102018-11-02 16:09:09 +0100227 && (!device_distinguishes_on_address(deviceType)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700228 // always force when disconnecting (a non-duplicated device)
229 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100230 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700231 }
Eric Laurente552edb2014-03-10 17:42:56 -0700232 }
233
Eric Laurentd60560a2015-04-10 11:31:20 -0700234 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100235 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700236 }
237
Eric Laurent72aa32f2014-05-30 18:51:48 -0700238 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700239 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700240 } // end if is output device
241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // handle input devices
François Gaffie11d30102018-11-02 16:09:09 +0100243 if (audio_is_input_device(deviceType)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700244 SortedVector <audio_io_handle_t> inputs;
245
François Gaffie11d30102018-11-02 16:09:09 +0100246 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700247 switch (state)
248 {
249 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700250 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700251 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100252 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700253 return INVALID_OPERATION;
254 }
François Gaffie11d30102018-11-02 16:09:09 +0100255 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(deviceType);
Eric Laurent6a94d692014-05-20 11:18:06 -0700256 if (module == NULL) {
257 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
François Gaffie11d30102018-11-02 16:09:09 +0100258 deviceType);
Eric Laurent6a94d692014-05-20 11:18:06 -0700259 return INVALID_OPERATION;
260 }
François Gaffie44481e72016-04-20 07:49:57 +0200261
262 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
263 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100264 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200265
François Gaffie11d30102018-11-02 16:09:09 +0100266 if (checkInputsForDevice(device, state, inputs) != NO_ERROR) {
267 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Eric Laurentd4692962014-05-05 18:13:44 -0700268 return INVALID_OPERATION;
269 }
270
François Gaffie11d30102018-11-02 16:09:09 +0100271 index = mAvailableInputDevices.add(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700272 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800273 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700274 } else {
275 return NO_MEMORY;
276 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800277
François Gaffie2110e042015-03-24 08:41:51 +0100278 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100279 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700280 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700281
282 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700283 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700284 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100285 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700286 return INVALID_OPERATION;
287 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700288
François Gaffie11d30102018-11-02 16:09:09 +0100289 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700290
291 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100292 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700293
François Gaffie11d30102018-11-02 16:09:09 +0100294 checkInputsForDevice(device, state, inputs);
295 mAvailableInputDevices.remove(device);
Paul McLean5c477aa2014-08-20 16:47:57 -0700296
François Gaffie2110e042015-03-24 08:41:51 +0100297 // Propagate device availability to Engine
François Gaffie11d30102018-11-02 16:09:09 +0100298 mEngine->setDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700299 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700300
301 default:
François Gaffie11d30102018-11-02 16:09:09 +0100302 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700303 return BAD_VALUE;
304 }
305
Eric Laurentd4692962014-05-05 18:13:44 -0700306 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700307 // As the input device list can impact the output device selection, update
308 // getDeviceForStrategy() cache
309 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700310
Eric Laurent87ffa392015-05-22 10:32:38 -0700311 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
313 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700314 }
315
Eric Laurentd60560a2015-04-10 11:31:20 -0700316 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700318 }
319
Eric Laurentb52c1522014-05-20 11:27:36 -0700320 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700321 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700322 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700323
François Gaffie11d30102018-11-02 16:09:09 +0100324 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700325 return BAD_VALUE;
326}
327
Eric Laurente0720872014-03-11 09:30:41 -0700328audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100329 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700330{
Eric Laurent634b7142016-04-20 13:48:02 -0700331 sp<DeviceDescriptor> devDesc =
332 mHwModules.getDeviceDescriptor(device, device_address, "",
333 (strlen(device_address) != 0)/*matchAddress*/);
334
335 if (devDesc == 0) {
336 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
337 device, device_address);
338 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
339 }
François Gaffie53615e22015-03-19 09:24:12 +0100340
Eric Laurent3a4311c2014-03-17 12:00:47 -0700341 DeviceVector *deviceVector;
342
Eric Laurente552edb2014-03-10 17:42:56 -0700343 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700344 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700345 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 deviceVector = &mAvailableInputDevices;
347 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100348 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700349 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
Eric Laurent634b7142016-04-20 13:48:02 -0700351
352 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
353 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800354}
355
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800356status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
357 const char *device_address,
358 const char *device_name)
359{
360 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700361 String8 reply;
362 AudioParameter param;
363 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800364
365 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
366 device, device_address, device_name);
367
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800368 // connect/disconnect only 1 device at a time
369 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
370
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800371 // Check if the device is currently connected
372 sp<DeviceDescriptor> devDesc =
373 mHwModules.getDeviceDescriptor(device, device_address, device_name);
374 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
375 if (index < 0) {
376 // Nothing to do: device is not connected
377 return NO_ERROR;
378 }
379
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700380 // For offloaded A2DP, Hw modules may have the capability to
381 // configure codecs. Check if any of the loaded hw modules
382 // supports this.
383 // If supported, send a set parameter to configure A2DP codecs
384 // and return. No need to toggle device state.
385 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
386 reply = mpClientInterface->getParameters(
387 AUDIO_IO_HANDLE_NONE,
388 String8(AudioParameter::keyReconfigA2dpSupported));
389 AudioParameter repliedParameters(reply);
390 repliedParameters.getInt(
391 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
392 if (isReconfigA2dpSupported) {
393 const String8 key(AudioParameter::keyReconfigA2dp);
394 param.add(key, String8("true"));
395 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
396 return NO_ERROR;
397 }
398 }
399
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800400 // Toggle the device state: UNAVAILABLE -> AVAILABLE
401 // This will force reading again the device configuration
402 status = setDeviceConnectionState(device,
403 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
404 device_address, device_name);
405 if (status != NO_ERROR) {
406 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
407 status);
408 return status;
409 }
410
411 status = setDeviceConnectionState(device,
412 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
413 device_address, device_name);
414 if (status != NO_ERROR) {
415 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
416 status);
417 return status;
418 }
419
420 return NO_ERROR;
421}
422
François Gaffie11d30102018-11-02 16:09:09 +0100423uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700424{
425 bool createTxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700426 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427
François Gaffie11d30102018-11-02 16:09:09 +0100428 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700429 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700430 }
François Gaffie11d30102018-11-02 16:09:09 +0100431 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
432
433 auto txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
434 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
435 rxDevices.toString().c_str(), txDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700436
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.
François Gaffie11d30102018-11-02 16:09:09 +0100451 if (availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) {
452 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, 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.
François Gaffie11d30102018-11-02 16:09:09 +0100455 if (!availablePrimaryModuleInputDevices().contains(txDevice)) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700456 createTxPatch = true;
457 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700458 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100459 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700460 createTxPatch = true;
461 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700462 if (createTxPatch) { // create TX path audio patch
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800463 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txDevice, delayMs);
464 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700465
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800466 return muteWaitMs;
467}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700468
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800469sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100470 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700471 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700472
François Gaffie11d30102018-11-02 16:09:09 +0100473 if (device == nullptr) {
474 return nullptr;
475 }
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800476 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100477 patchBuilder.addSink(device).
478 addSource(mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800479 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100480 patchBuilder.addSource(device).
481 addSink(mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800482 }
483
François Gaffie11d30102018-11-02 16:09:09 +0100484 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
485 const sp<DeviceDescriptor> outputDevice = isRx ?
486 device : mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX);
487 SortedVector<audio_io_handle_t> outputs =
488 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
489 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800490 // request to reuse existing output stream if one is already opened to reach the target device
491 if (output != AUDIO_IO_HANDLE_NONE) {
492 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100493 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
494 outputDevice->toString().c_str(), output);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700495 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800496 }
497
498 if (!isRx) {
Eric Laurentc0a889f2015-10-14 14:36:34 -0700499 // terminate active capture if on the same HW module as the call TX source device
500 // FIXME: would be better to refine to only inputs whose profile connects to the
501 // call TX device but this information is not in the audio patch and logic here must be
502 // symmetric to the one in startInput()
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800503 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100504 if (activeDesc->hasSameHwModuleAs(device)) {
Eric Laurent8f42ea12018-08-08 09:08:25 -0700505 closeActiveClients(activeDesc);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700506 }
507 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700508 }
Eric Laurentdc462862016-07-19 12:29:53 -0700509
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800510 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Mikhail Naganovdc769682018-05-04 15:34:08 -0700511 status_t status = mpClientInterface->createAudioPatch(
512 patchBuilder.patch(), &afPatchHandle, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800513 ALOGW_IF(status != NO_ERROR,
514 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
515 sp<AudioPatch> audioPatch;
516 if (status == NO_ERROR) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700517 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800518 audioPatch->mAfPatchHandle = afPatchHandle;
519 audioPatch->mUid = mUidCached;
520 }
521 return audioPatch;
522}
523
Mikhail Naganovdc769682018-05-04 15:34:08 -0700524sp<DeviceDescriptor> AudioPolicyManager::findDevice(
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100525 const DeviceVector& devices, audio_devices_t device) const {
Mikhail Naganov708e0382018-05-30 09:53:04 -0700526 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800527 ALOG_ASSERT(!deviceList.isEmpty(),
528 "%s() selected device type %#x is not in devices list", __func__, device);
Mikhail Naganovdc769682018-05-04 15:34:08 -0700529 return deviceList.itemAt(0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700530}
531
Mikhail Naganov100f0122018-11-29 11:22:16 -0800532audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
533 const DeviceVector& devices, const char *moduleId) const {
534 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
535 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
536}
537
538bool AudioPolicyManager::isDeviceOfModule(
539 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
540 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
541 if (module != 0) {
542 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
543 .indexOf(devDesc) != NAME_NOT_FOUND
544 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
545 .indexOf(devDesc) != NAME_NOT_FOUND;
546 }
547 return false;
548}
549
Eric Laurente0720872014-03-11 09:30:41 -0700550void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700551{
552 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100553 // store previous phone state for management of sonification strategy below
554 int oldState = mEngine->getPhoneState();
555
556 if (mEngine->setPhoneState(state) != NO_ERROR) {
557 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700558 return;
559 }
François Gaffie2110e042015-03-24 08:41:51 +0100560 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700561 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700562 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700563 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800564 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700565 }
566
François Gaffie2110e042015-03-24 08:41:51 +0100567 /**
568 * Switching to or from incall state or switching between telephony and VoIP lead to force
569 * routing command.
570 */
571 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
572 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700573
574 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700575 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700576
Eric Laurente552edb2014-03-10 17:42:56 -0700577 int delayMs = 0;
578 if (isStateInCall(state)) {
579 nsecs_t sysTime = systemTime();
580 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700581 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700582 // mute media and sonification strategies and delay device switch by the largest
583 // latency of any output where either strategy is active.
584 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100585 if ((isStrategyActive(desc, STRATEGY_MEDIA,
586 SONIFICATION_HEADSET_MUSIC_DELAY,
587 sysTime) ||
588 isStrategyActive(desc, STRATEGY_SONIFICATION,
589 SONIFICATION_HEADSET_MUSIC_DELAY,
590 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700591 (delayMs < (int)desc->latency()*2)) {
592 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700593 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700594 setStrategyMute(STRATEGY_MEDIA, true, desc);
595 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700596 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700597 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
598 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700599 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
600 }
601 }
602
Eric Laurent87ffa392015-05-22 10:32:38 -0700603 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100604 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700605 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100606 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700607 // force routing command to audio hardware when ending call
608 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100609 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
610 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 }
Eric Laurente552edb2014-03-10 17:42:56 -0700612
Eric Laurent87ffa392015-05-22 10:32:38 -0700613 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100614 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700615 } else if (oldState == AUDIO_MODE_IN_CALL) {
616 if (mCallRxPatch != 0) {
617 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
618 mCallRxPatch.clear();
619 }
620 if (mCallTxPatch != 0) {
621 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
622 mCallTxPatch.clear();
623 }
François Gaffie11d30102018-11-02 16:09:09 +0100624 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700625 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100626 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700627 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700628 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700629
630 // reevaluate routing on all outputs in case tracks have been started during the call
631 for (size_t i = 0; i < mOutputs.size(); i++) {
632 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100633 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700634 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100635 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700636 }
637 }
638
Eric Laurente552edb2014-03-10 17:42:56 -0700639 if (isStateInCall(state)) {
640 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700641 // force reevaluating accessibility routing when call starts
642 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700643 }
644
645 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700646 if (state == AUDIO_MODE_RINGTONE &&
647 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700648 mLimitRingtoneVolume = true;
649 } else {
650 mLimitRingtoneVolume = false;
651 }
652}
653
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700654audio_mode_t AudioPolicyManager::getPhoneState() {
655 return mEngine->getPhoneState();
656}
657
Eric Laurente0720872014-03-11 09:30:41 -0700658void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100659 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700660{
François Gaffie2110e042015-03-24 08:41:51 +0100661 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700662 if (config == mEngine->getForceUse(usage)) {
663 return;
664 }
Eric Laurente552edb2014-03-10 17:42:56 -0700665
François Gaffie2110e042015-03-24 08:41:51 +0100666 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
667 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
668 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700669 }
François Gaffie2110e042015-03-24 08:41:51 +0100670 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
671 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
672 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700673
674 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700675 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800676
Eric Laurentdc462862016-07-19 12:29:53 -0700677 //FIXME: workaround for truncated touch sounds
678 // to be removed when the problem is handled by system UI
679 uint32_t delayMs = 0;
680 uint32_t waitMs = 0;
681 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
682 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
683 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700684 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100685 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
686 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700689 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100690 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -0700691 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100692 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700693 }
François Gaffie11d30102018-11-02 16:09:09 +0100694 if (forceVolumeReeval && !newDevices.isEmpty()) {
695 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700696 }
697 }
698
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800699 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100700 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700701 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800702 if (activeDesc->mProfile->getSupportedDevices().types() &
François Gaffie11d30102018-11-02 16:09:09 +0100703 (newDevice->type() & ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800704 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700705 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800706 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700707 }
Eric Laurente552edb2014-03-10 17:42:56 -0700708 }
Eric Laurente552edb2014-03-10 17:42:56 -0700709}
710
Eric Laurente0720872014-03-11 09:30:41 -0700711void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700712{
713 ALOGV("setSystemProperty() property %s, value %s", property, value);
714}
715
Michael Chana94fbb22018-04-24 14:31:19 +1000716// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
717// search to profiles for direct outputs.
718sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100719 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000720 uint32_t samplingRate,
721 audio_format_t format,
722 audio_channel_mask_t channelMask,
723 audio_output_flags_t flags,
724 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700725{
Michael Chana94fbb22018-04-24 14:31:19 +1000726 if (directOnly) {
727 // only retain flags that will drive the direct output profile selection
728 // if explicitly requested
729 static const uint32_t kRelevantFlags =
730 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
731 AUDIO_OUTPUT_FLAG_VOIP_RX);
732 flags =
733 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
734 }
Eric Laurent861a6282015-05-18 15:40:16 -0700735
736 sp<IOProfile> profile;
737
Mikhail Naganovd4120142017-12-06 15:49:22 -0800738 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800739 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100740 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700741 samplingRate, NULL /*updatedSamplingRate*/,
742 format, NULL /*updatedFormat*/,
743 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700744 flags)) {
745 continue;
746 }
747 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100748 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700749 continue;
750 }
Michael Chana94fbb22018-04-24 14:31:19 +1000751 if (!directOnly) return curProfile;
752 // when searching for direct outputs, if several profiles are compatible, give priority
753 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100754 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700755 continue;
756 }
757 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100758 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700759 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700760 }
Eric Laurente552edb2014-03-10 17:42:56 -0700761 }
762 }
Eric Laurent861a6282015-05-18 15:40:16 -0700763 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700764}
765
Eric Laurentf4e63452017-11-06 19:31:46 +0000766audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700767{
Eric Laurent3b73df72014-03-11 09:06:29 -0700768 routing_strategy strategy = getStrategy(stream);
François Gaffie11d30102018-11-02 16:09:09 +0100769 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800770
771 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
772 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
773 // format, flags, etc. This may result in some discrepancy for functions that utilize
774 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
775 // and AudioSystem::getOutputSamplingRate().
776
François Gaffie11d30102018-11-02 16:09:09 +0100777 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
778 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
Eric Laurente552edb2014-03-10 17:42:56 -0700779
François Gaffie11d30102018-11-02 16:09:09 +0100780 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
781 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000782 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700783}
784
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700785status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
786 const audio_attributes_t *srcAttr,
787 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700788{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700789 if (srcAttr != NULL) {
790 if (!isValidAttributes(srcAttr)) {
791 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
792 __func__,
793 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
794 srcAttr->tags);
795 return BAD_VALUE;
796 }
797 *dstAttr = *srcAttr;
798 } else {
799 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
800 ALOGE("%s: invalid stream type", __func__);
801 return BAD_VALUE;
802 }
803 stream_type_to_audio_attributes(srcStream, dstAttr);
804 }
805 return NO_ERROR;
806}
807
808status_t AudioPolicyManager::getOutputForAttrInt(audio_attributes_t *resultAttr,
809 audio_io_handle_t *output,
810 audio_session_t session,
811 const audio_attributes_t *attr,
812 audio_stream_type_t *stream,
813 uid_t uid,
814 const audio_config_t *config,
815 audio_output_flags_t *flags,
816 audio_port_handle_t *selectedDeviceId)
817{
François Gaffie11d30102018-11-02 16:09:09 +0100818 DeviceVector devices;
Eric Laurent8fc147b2018-07-22 19:13:55 -0700819 routing_strategy strategy;
François Gaffie11d30102018-11-02 16:09:09 +0100820 audio_devices_t deviceType = AUDIO_DEVICE_NONE;
Eric Laurent97ac8712018-07-27 18:59:02 -0700821 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100822 DeviceVector msdDevices = getMsdAudioOutDevices();
Eric Laurent8fc147b2018-07-22 19:13:55 -0700823
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700824 status_t status = getAudioAttributes(resultAttr, attr, *stream);
825 if (status != NO_ERROR) {
826 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700827 }
828
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700829 ALOGV("%s usage=%d, content=%d, tag=%s flags=%08x"
Eric Laurent97ac8712018-07-27 18:59:02 -0700830 " session %d selectedDeviceId %d",
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700831 __func__,
832 resultAttr->usage, resultAttr->content_type, resultAttr->tags, resultAttr->flags,
Eric Laurent97ac8712018-07-27 18:59:02 -0700833 session, requestedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700834
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700835 *stream = streamTypefromAttributesInt(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700836
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700837 strategy = getStrategyForAttr(resultAttr);
Eric Laurent97ac8712018-07-27 18:59:02 -0700838
Scott Randolph7b1fd232018-06-18 15:33:03 -0700839 // First check for explicit routing (eg. setPreferredDevice)
Eric Laurent97ac8712018-07-27 18:59:02 -0700840 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
841 sp<DeviceDescriptor> deviceDesc =
842 mAvailableOutputDevices.getDeviceFromId(requestedDeviceId);
François Gaffie11d30102018-11-02 16:09:09 +0100843 deviceType = deviceDesc->type();
Scott Randolph7b1fd232018-06-18 15:33:03 -0700844 } else {
845 // If no explict route, is there a matching dynamic policy that applies?
846 sp<SwAudioOutputDescriptor> desc;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700847 if (mPolicyMixes.getOutputForAttr(*resultAttr, uid, desc) == NO_ERROR) {
Scott Randolph7b1fd232018-06-18 15:33:03 -0700848 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
849 if (!audio_has_proportional_frames(config->format)) {
850 return BAD_VALUE;
851 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700852 *stream = streamTypefromAttributesInt(resultAttr);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700853 *output = desc->mIoHandle;
Eric Laurent97ac8712018-07-27 18:59:02 -0700854 AudioMix *mix = desc->mPolicyMix;
855 sp<DeviceDescriptor> deviceDesc =
856 mAvailableOutputDevices.getDevice(mix->mDeviceType, mix->mDeviceAddress);
857 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700858 ALOGV("%s returns output %d", __func__, *output);
859 return NO_ERROR;
Scott Randolph7b1fd232018-06-18 15:33:03 -0700860 }
861
862 // Virtual sources must always be dynamicaly or explicitly routed
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700863 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
864 ALOGW("%s no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE", __func__);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700865 return BAD_VALUE;
866 }
François Gaffie11d30102018-11-02 16:09:09 +0100867 deviceType = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700868 }
Scott Randolph7b1fd232018-06-18 15:33:03 -0700869
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700870 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200871 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700872 }
873
Nadav Barb2f18162018-07-18 13:01:53 +0300874 // Set incall music only if device was explicitly set, and fallback to the device which is
875 // chosen by the engine if not.
876 // FIXME: provide a more generic approach which is not device specific and move this back
877 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200878 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
François Gaffie11d30102018-11-02 16:09:09 +0100879 if (deviceType == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700880 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300881 audio_is_linear_pcm(config->format) &&
882 isInCall()) {
Eric Laurent97ac8712018-07-27 18:59:02 -0700883 if (requestedDeviceId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300884 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
885 } else {
Eric Laurent97ac8712018-07-27 18:59:02 -0700886 // Get the devce type directly from the engine to bypass preferred route logic
François Gaffie11d30102018-11-02 16:09:09 +0100887 deviceType = mEngine->getDeviceForStrategy(strategy);
Nadav Barb2f18162018-07-18 13:01:53 +0300888 }
889 }
890
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700891 ALOGV("%s device 0x%x, sampling rate %d, format %#x, channel mask %#x, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -0800892 "flags %#x",
François Gaffie11d30102018-11-02 16:09:09 +0100893 __func__,
894 deviceType, config->sample_rate, config->format, config->channel_mask, *flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700895
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100896 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +0100897 if (!msdDevices.isEmpty()) {
898 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
899 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(deviceType);
900 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(deviceDesc) == NO_ERROR) {
901 ALOGV("%s() Using MSD devices %s instead of device %s",
902 __func__, msdDevices.toString().c_str(), deviceDesc->toString().c_str());
903 deviceType = msdDevices.types();
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100904 } else {
905 *output = AUDIO_IO_HANDLE_NONE;
906 }
907 }
François Gaffie11d30102018-11-02 16:09:09 +0100908 devices = mAvailableOutputDevices.getDevicesFromTypeMask(deviceType);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100909 if (*output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +0100910 *output = getOutputForDevices(devices, session, *stream, config, flags);
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100911 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800912 if (*output == AUDIO_IO_HANDLE_NONE) {
913 return INVALID_OPERATION;
914 }
Paul McLeanaa981192015-03-21 09:55:15 -0700915
François Gaffie11d30102018-11-02 16:09:09 +0100916 *selectedDeviceId = getFirstDeviceId(devices);
Eric Laurent2ac76942017-06-22 17:17:09 -0700917
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700918 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
919
920 return NO_ERROR;
921}
922
923status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
924 audio_io_handle_t *output,
925 audio_session_t session,
926 audio_stream_type_t *stream,
927 uid_t uid,
928 const audio_config_t *config,
929 audio_output_flags_t *flags,
930 audio_port_handle_t *selectedDeviceId,
931 audio_port_handle_t *portId)
932{
933 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
934 if (*portId != AUDIO_PORT_HANDLE_NONE) {
935 return INVALID_OPERATION;
936 }
937 const audio_port_handle_t requestedDeviceId = *selectedDeviceId;
938 audio_attributes_t resultAttr;
939 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
940 config, flags, selectedDeviceId);
941 if (status != NO_ERROR) {
942 return status;
943 }
944
Eric Laurent8fc147b2018-07-22 19:13:55 -0700945 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
946 .format = config->format,
947 .channel_mask = config->channel_mask };
Eric Laurent8f42ea12018-08-08 09:08:25 -0700948 *portId = AudioPort::getNextUniqueId();
949
Eric Laurent8fc147b2018-07-22 19:13:55 -0700950 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700951 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Eric Laurent97ac8712018-07-27 18:59:02 -0700952 requestedDeviceId, *stream,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700953 getStrategyForAttr(&resultAttr),
Eric Laurent97ac8712018-07-27 18:59:02 -0700954 *flags);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700955 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -0700956 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -0700957
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700958 ALOGV("%s returns output %d selectedDeviceId %d for port ID %d",
959 __func__, *output, requestedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -0700960
Eric Laurente83b55d2014-11-14 10:06:21 -0800961 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700962}
963
François Gaffie11d30102018-11-02 16:09:09 +0100964audio_io_handle_t AudioPolicyManager::getOutputForDevices(
965 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -0800966 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -0800968 const audio_config_t *config,
Nadav Bar766fb022018-01-07 12:18:03 +0200969 audio_output_flags_t *flags)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700970{
Andy Hungc88b0642018-04-27 15:42:35 -0700971 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700972 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700973
Eric Laurente552edb2014-03-10 17:42:56 -0700974 // open a direct output if required by specified parameters
975 //force direct flag if offload flag is set: offloading implies a direct output stream
976 // and all common behaviors are driven by checking only the direct flag
977 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +0200978 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
979 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
Nadav Bar766fb022018-01-07 12:18:03 +0200981 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
982 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -0700983 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800984 // only allow deep buffering for music stream type
985 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +0200986 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700987 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +0200988 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700989 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
990 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +0200991 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800992 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700993 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +0200994 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700995 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +0200996 audio_is_linear_pcm(config->format) &&
997 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200998 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700999 AUDIO_OUTPUT_FLAG_DIRECT);
1000 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001001 }
Eric Laurente552edb2014-03-10 17:42:56 -07001002
Nadav Bar766fb022018-01-07 12:18:03 +02001003
Eric Laurentb732cf52014-09-24 19:08:21 -07001004 sp<IOProfile> profile;
1005
1006 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001007 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001008 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001009 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1010 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001011 goto non_direct_output;
1012 }
1013
Andy Hung2ddee192015-12-18 17:34:44 -08001014 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1015 // This prevents creating an offloaded track and tearing it down immediately after start
1016 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001017 // FIXME: We should check the audio session here but we do not have it in this context.
1018 // This may prevent offloading in rare situations where effects are left active by apps
1019 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001020
Nadav Bar766fb022018-01-07 12:18:03 +02001021 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001022 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001023 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001024 config->sample_rate,
1025 config->format,
1026 config->channel_mask,
1027 (audio_output_flags_t)*flags,
1028 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001029 }
1030
Eric Laurent1c333e22014-05-20 10:48:17 -07001031 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001032 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1033 for (size_t i = 0; i < mOutputs.size(); i++) {
1034 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1035 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1036 // reuse direct output if currently open by the same client
1037 // and configured with same parameters
1038 if ((config->sample_rate == desc->mSamplingRate) &&
Andy Hung5659ed52018-04-30 10:31:26 -07001039 (config->format == desc->mFormat) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001040 (config->channel_mask == desc->mChannelMask) &&
1041 (session == desc->mDirectClientSession)) {
1042 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001043 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001044 mOutputs.keyAt(i), session);
1045 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001046 }
1047 }
1048 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001049
1050 if (!profile->canOpenNewIo()) {
1051 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
Eric Laurent861a6282015-05-18 15:40:16 -07001053
Eric Laurent3974e3b2017-12-07 17:58:43 -08001054 sp<SwAudioOutputDescriptor> outputDesc =
1055 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001056
François Gaffie11d30102018-11-02 16:09:09 +01001057 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001058
Dean Wheatley3023b382018-08-09 07:42:40 +10001059 // MSD patch may be using the only output stream that can service this request. Release
1060 // MSD patch to prioritize this request over any active output on MSD.
1061 AudioPatchCollection msdPatches = getMsdPatches();
1062 for (size_t i = 0; i < msdPatches.size(); i++) {
1063 const auto& patch = msdPatches[i];
1064 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1065 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1066 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
François Gaffie11d30102018-11-02 16:09:09 +01001067 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001068 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1069 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1070 releaseAudioPatch(patch->mHandle, mUidCached);
1071 break;
1072 }
1073 }
1074 }
1075
François Gaffie11d30102018-11-02 16:09:09 +01001076 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001077
1078 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001079 if (status != NO_ERROR ||
Eric Laurentfe231122017-11-17 17:48:06 -08001080 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
Andy Hung5659ed52018-04-30 10:31:26 -07001081 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
Eric Laurentfe231122017-11-17 17:48:06 -08001082 (config->channel_mask != 0 && config->channel_mask != outputDesc->mChannelMask)) {
François Gaffie11d30102018-11-02 16:09:09 +01001083 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1084 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
Eric Laurentfe231122017-11-17 17:48:06 -08001085 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1086 config->channel_mask, outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001087 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001088 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001089 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001090 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001091 if (audio_is_linear_pcm(config->format) &&
1092 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001093 goto non_direct_output;
1094 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001095 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001096 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001097 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001098 outputDesc->mDirectClientSession = session;
1099
Eric Laurente552edb2014-03-10 17:42:56 -07001100 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001101 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001102 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001103 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001104 return output;
1105 }
1106
Eric Laurentb732cf52014-09-24 19:08:21 -07001107non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001108
1109 // A request for HW A/V sync cannot fallback to a mixed output because time
1110 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001111 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001112 return AUDIO_IO_HANDLE_NONE;
1113 }
1114
Eric Laurente552edb2014-03-10 17:42:56 -07001115 // ignoring channel mask due to downmix capability in mixer
1116
1117 // open a non direct output
1118
1119 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001120 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001121 // get which output is suitable for the specified stream. The actual
1122 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001123 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
Eric Laurent8838a382014-09-08 16:44:28 -07001125 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001126 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin40573322018-11-08 12:08:02 -08001127 output = selectOutput(outputs, *flags, config->format,
1128 config->channel_mask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 }
François Gaffie11d30102018-11-02 16:09:09 +01001130 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001131 "sampling rate %d, format %#x, channels %#x, flags %#x",
Nadav Bar766fb022018-01-07 12:18:03 +02001132 stream, config->sample_rate, config->format, config->channel_mask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001133
Eric Laurente552edb2014-03-10 17:42:56 -07001134 return output;
1135}
1136
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001137sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001138 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1139 mAvailableInputDevices);
1140 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1141}
1142
1143DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1144 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1145 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001146}
1147
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001148const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1149 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001150 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1151 if (msdModule != 0) {
1152 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1153 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1154 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1155 const struct audio_port_config *source = &patch->mPatch.sources[j];
1156 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1157 source->ext.device.hw_module == msdModule->getHandle()) {
1158 msdPatches.addAudioPatch(patch->mHandle, patch);
1159 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001160 }
1161 }
1162 }
1163 return msdPatches;
1164}
1165
François Gaffie11d30102018-11-02 16:09:09 +01001166status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001167 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1168{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001169 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001170 if (msdModule == nullptr) {
1171 ALOGE("%s() unable to get MSD module", __func__);
1172 return NO_INIT;
1173 }
1174 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice);
1175 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001176 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001177 return NO_INIT;
1178 }
1179 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1180 if (inputProfiles.isEmpty()) {
1181 ALOGE("%s() no input profiles for MSD module", __func__);
1182 return NO_INIT;
1183 }
1184 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1185 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001186 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001187 return NO_INIT;
1188 }
1189 AudioProfileVector msdProfiles;
1190 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1191 for (const auto &inProfile : inputProfiles) {
1192 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1193 msdProfiles.appendVector(inProfile->getAudioProfiles());
1194 }
1195 }
1196 AudioProfileVector deviceProfiles;
1197 for (const auto &outProfile : outputProfiles) {
1198 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1199 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1200 }
1201 }
1202 struct audio_config_base bestSinkConfig;
1203 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1204 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1205 &bestSinkConfig);
1206 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001207 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1208 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001209 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001210 }
1211 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1212 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1213 sinkConfig->format = bestSinkConfig.format;
1214 // For encoded streams force direct flag to prevent downstream mixing.
1215 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1216 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1217 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1218 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1219 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1220 sourceConfig->format = bestSinkConfig.format;
1221 // Copy input stream directly without any processing (e.g. resampling).
1222 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1223 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1224 if (hwAvSync) {
1225 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1226 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1227 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1228 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1229 }
1230 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1231 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1232 sinkConfig->config_mask |= config_mask;
1233 sourceConfig->config_mask |= config_mask;
1234 return NO_ERROR;
1235}
1236
François Gaffie11d30102018-11-02 16:09:09 +01001237PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001238{
1239 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001240 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001241 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1242 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1243 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1244 // For now, we just forcefully try with HwAvSync first.
1245 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1246 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1247 getBestMsdAudioProfileFor(
1248 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1249 if (res == NO_ERROR) {
1250 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1251 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1252 }
1253 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1254 " supporting PCM format conversion.", __func__);
1255 return patchBuilder;
1256}
1257
François Gaffie11d30102018-11-02 16:09:09 +01001258status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1259 sp<DeviceDescriptor> device = outputDevice;
1260 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001261 // Use media strategy for unspecified output device. This should only
1262 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1263 // therefore invalidate explicit routing requests.
François Gaffie11d30102018-11-02 16:09:09 +01001264 DeviceVector devices = getDevicesForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
1265 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1266 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 }
François Gaffie11d30102018-11-02 16:09:09 +01001268 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1269 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001270 const struct audio_patch* patch = patchBuilder.patch();
1271 const AudioPatchCollection msdPatches = getMsdPatches();
1272 if (!msdPatches.isEmpty()) {
1273 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1274 "The current MSD prototype only supports one output patch");
1275 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1276 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1277 return NO_ERROR;
1278 }
1279 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1280 }
1281 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1282 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1283 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1284 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001285 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1286 device->toString().c_str(), patch->sources[0].format,
1287 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001288 return status;
1289}
1290
Eric Laurente0720872014-03-11 09:30:41 -07001291audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001292 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001293 audio_format_t format,
1294 audio_channel_mask_t channelMask,
1295 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001296{
1297 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001298 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001299 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001300 // 1: the output supporting haptic playback when requesting haptic playback
1301 // 2: the output with the highest number of requested policy flags
1302 // 3: the output with the bit depth the closest to the requested one
1303 // 4: the primary output
1304 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001305
1306 if (outputs.size() == 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001307 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001308 }
1309 if (outputs.size() == 1) {
1310 return outputs[0];
1311 }
1312
1313 int maxCommonFlags = 0;
jiabin40573322018-11-08 12:08:02 -08001314 const size_t hapticChannelCount = audio_channel_count_from_out_mask(
1315 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001316 audio_io_handle_t outputForFlags = AUDIO_IO_HANDLE_NONE;
1317 audio_io_handle_t outputForPrimary = AUDIO_IO_HANDLE_NONE;
1318 audio_io_handle_t outputForFormat = AUDIO_IO_HANDLE_NONE;
Eric Laurente6930022016-02-11 10:20:40 -08001319 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1320 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001321
Eric Laurente78b6762018-12-19 16:29:01 -08001322 // Flags which must be present on both the request and the selected output
1323 static const audio_output_flags_t kMandatedFlags = (audio_output_flags_t)
1324 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1325
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001326 for (audio_io_handle_t output : outputs) {
1327 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001328 if (!outputDesc->isDuplicated()) {
chenhg1794d712018-10-09 15:20:37 -07001329 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1330 continue;
1331 }
jiabin40573322018-11-08 12:08:02 -08001332 // If haptic channel is specified, use the haptic output if present.
1333 // When using haptic output, same audio format and sample rate are required.
1334 if (hapticChannelCount > 0) {
1335 // If haptic channel is specified, use the first output that
1336 // support haptic playback.
1337 if (audio_channel_count_from_out_mask(
1338 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) >= hapticChannelCount
1339 && format == outputDesc->mFormat
1340 && samplingRate == outputDesc->mSamplingRate) {
1341 return output;
1342 }
1343 } else {
1344 // When haptic channel is not specified, skip haptic output.
1345 if (outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
1346 continue;
1347 }
1348 }
Eric Laurente78b6762018-12-19 16:29:01 -08001349 if ((kMandatedFlags & flags) !=
1350 (kMandatedFlags & outputDesc->mProfile->getFlags())) {
1351 continue;
1352 }
jiabin40573322018-11-08 12:08:02 -08001353
Eric Laurent8838a382014-09-08 16:44:28 -07001354 // if a valid format is specified, skip output if not compatible
1355 if (format != AUDIO_FORMAT_INVALID) {
chenhg1794d712018-10-09 15:20:37 -07001356 if (!audio_is_linear_pcm(format)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001357 continue;
1358 }
Eric Laurente6930022016-02-11 10:20:40 -08001359 if (AudioPort::isBetterFormatMatch(
1360 outputDesc->mFormat, bestFormat, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001361 outputForFormat = output;
Eric Laurente6930022016-02-11 10:20:40 -08001362 bestFormat = outputDesc->mFormat;
1363 }
Eric Laurent8838a382014-09-08 16:44:28 -07001364 }
1365
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001366 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001367 if (commonFlags >= maxCommonFlags) {
1368 if (commonFlags == maxCommonFlags) {
Andy Hungc9901522017-11-10 20:07:54 -08001369 if (format != AUDIO_FORMAT_INVALID
1370 && AudioPort::isBetterFormatMatch(
1371 outputDesc->mFormat, bestFormatForFlags, format)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001372 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001373 bestFormatForFlags = outputDesc->mFormat;
1374 }
1375 } else {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001376 outputForFlags = output;
Eric Laurente6930022016-02-11 10:20:40 -08001377 maxCommonFlags = commonFlags;
1378 bestFormatForFlags = outputDesc->mFormat;
1379 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001380 ALOGV("selectOutput() commonFlags for output %d, %04x", output, commonFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001381 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001382 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001383 outputForPrimary = output;
Eric Laurente552edb2014-03-10 17:42:56 -07001384 }
1385 }
1386 }
1387
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001388 if (outputForFlags != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001389 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001390 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001391 if (outputForFormat != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001392 return outputForFormat;
1393 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001394 if (outputForPrimary != AUDIO_IO_HANDLE_NONE) {
Eric Laurente6930022016-02-11 10:20:40 -08001395 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001396 }
1397
1398 return outputs[0];
1399}
1400
Eric Laurent8fc147b2018-07-22 19:13:55 -07001401status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001402{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001403 ALOGV("%s portId %d", __FUNCTION__, portId);
1404
1405 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1406 if (outputDesc == 0) {
1407 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001408 return BAD_VALUE;
1409 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001410 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001411
Eric Laurent8fc147b2018-07-22 19:13:55 -07001412 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001413 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001414
Eric Laurent733ce942017-12-07 12:18:25 -08001415 status_t status = outputDesc->start();
1416 if (status != NO_ERROR) {
1417 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001418 }
1419
Eric Laurent97ac8712018-07-27 18:59:02 -07001420 uint32_t delayMs;
1421 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001422
1423 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001424 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001425 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001426 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001427 if (delayMs != 0) {
1428 usleep(delayMs * 1000);
1429 }
1430
1431 return status;
1432}
1433
Eric Laurent97ac8712018-07-27 18:59:02 -07001434status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1435 const sp<TrackClientDescriptor>& client,
1436 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001437{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001438 // cannot start playback of STREAM_TTS if any other output is being used
1439 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001440
1441 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001442 audio_stream_type_t stream = client->stream();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001443 if (stream == AUDIO_STREAM_TTS) {
1444 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001445 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001446 return INVALID_OPERATION;
1447 } else {
1448 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1449 }
1450 } else {
1451 // some playback other than beacon starts
1452 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1453 }
1454
Eric Laurent77305a62016-07-25 16:39:22 -07001455 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001456 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001457 bool force = !outputDesc->isActive() &&
1458 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001459
François Gaffie11d30102018-11-02 16:09:09 +01001460 DeviceVector devices;
Eric Laurent97ac8712018-07-27 18:59:02 -07001461 AudioMix *policyMix = NULL;
1462 const char *address = NULL;
1463 if (outputDesc->mPolicyMix != NULL) {
1464 policyMix = outputDesc->mPolicyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001465 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001466 address = policyMix->mDeviceAddress.string();
1467 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
François Gaffie11d30102018-11-02 16:09:09 +01001468 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001469 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001470 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07001471 }
François Gaffie11d30102018-11-02 16:09:09 +01001472 devices.add(mAvailableOutputDevices.getDevice(newDeviceType, String8(address)));
Eric Laurent97ac8712018-07-27 18:59:02 -07001473 }
1474
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001475 // requiresMuteCheck is false when we can bypass mute strategy.
1476 // It covers a common case when there is no materially active audio
1477 // and muting would result in unnecessary delay and dropped audio.
1478 const uint32_t outputLatencyMs = outputDesc->latency();
1479 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1480
Eric Laurente552edb2014-03-10 17:42:56 -07001481 // increment usage count for this stream on the requested output:
1482 // NOTE that the usage count is the same for duplicated output and hardware output which is
1483 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001484 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001485
1486 if (client->hasPreferredDevice(true)) {
François Gaffie11d30102018-11-02 16:09:09 +01001487 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1488 if (devices != outputDesc->devices()) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001489 checkStrategyRoute(getStrategy(stream), outputDesc->mIoHandle);
1490 }
1491 }
Eric Laurente552edb2014-03-10 17:42:56 -07001492
Eric Laurent36829f92017-04-07 19:04:42 -07001493 if (stream == AUDIO_STREAM_MUSIC) {
1494 selectOutputForMusicEffects();
1495 }
1496
François Gaffie11d30102018-11-02 16:09:09 +01001497 if (outputDesc->streamActiveCount(stream) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001498 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001499 if (devices.isEmpty()) {
1500 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001501 }
Eric Laurent36829f92017-04-07 19:04:42 -07001502
Eric Laurente552edb2014-03-10 17:42:56 -07001503 routing_strategy strategy = getStrategy(stream);
1504 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001505 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1506 (beaconMuteLatency > 0);
1507 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001508 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001509 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001510 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001511 // An output has a shared device if
1512 // - managed by the same hw module
1513 // - supports the currently selected device
1514 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001515 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001516
Eric Laurent77305a62016-07-25 16:39:22 -07001517 // force a device change if any other output is:
1518 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001519 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001520 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001521 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001522 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001523 // change the device currently selected by the other output.
1524 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001525 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001526 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001527 force = true;
1528 }
1529 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001530 // a notification so that audio focus effect can propagate, or that a mute/unmute
1531 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001532 const uint32_t latencyMs = desc->latency();
1533 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1534
1535 if (shouldWait && isActive && (waitMs < latencyMs)) {
1536 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001538
1539 // Require mute check if another output is on a shared device
1540 // and currently active to have proper drain and avoid pops.
1541 // Note restoring AudioTracks onto this output needs to invoke
1542 // a volume ramp if there is no mute.
1543 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001544 }
1545 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001546
1547 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001548 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001549
Eric Laurente552edb2014-03-10 17:42:56 -07001550 // apply volume rules for current stream and device if necessary
1551 checkAndSetVolume(stream,
François Gaffie11d30102018-11-02 16:09:09 +01001552 mVolumeCurves->getVolumeIndex(stream, outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001553 outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01001554 outputDesc->devices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07001555
1556 // update the outputs if starting an output with a stream that can affect notification
1557 // routing
1558 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001559
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001560 // force reevaluating accessibility routing when ringtone or alarm starts
1561 if (strategy == STRATEGY_SONIFICATION) {
1562 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1563 }
Eric Laurentdc462862016-07-19 12:29:53 -07001564
1565 if (waitMs > muteWaitMs) {
1566 *delayMs = waitMs - muteWaitMs;
1567 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001568
1569 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1570 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1571 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1572 // change occurs after the MixerThread starts and causes a stream volume
1573 // glitch.
1574 //
1575 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001576 }
Eric Laurentdc462862016-07-19 12:29:53 -07001577
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001578 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1579 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1580 setStrategyMute(STRATEGY_SONIFICATION, true, outputDesc);
1581 }
1582
Eric Laurent97ac8712018-07-27 18:59:02 -07001583 // Automatically enable the remote submix input when output is started on a re routing mix
1584 // of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001585 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001586 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1587 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1589 address,
1590 "remote-submix");
1591 }
1592
Eric Laurente552edb2014-03-10 17:42:56 -07001593 return NO_ERROR;
1594}
1595
Eric Laurent8fc147b2018-07-22 19:13:55 -07001596status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001597{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001598 ALOGV("%s portId %d", __FUNCTION__, portId);
1599
1600 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1601 if (outputDesc == 0) {
1602 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001603 return BAD_VALUE;
1604 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001605 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001606
Eric Laurent97ac8712018-07-27 18:59:02 -07001607 ALOGV("stopOutput() output %d, stream %d, session %d",
1608 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001609
Eric Laurent97ac8712018-07-27 18:59:02 -07001610 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001611
Eric Laurent733ce942017-12-07 12:18:25 -08001612 if (status == NO_ERROR ) {
1613 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001614 }
1615 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001616}
1617
Eric Laurent97ac8712018-07-27 18:59:02 -07001618status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1619 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001620{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001621 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001622 audio_stream_type_t stream = client->stream();
1623
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001624 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1625
Eric Laurent592dd7b2018-08-05 18:58:48 -07001626 if (outputDesc->streamActiveCount(stream) > 0) {
1627 if (outputDesc->streamActiveCount(stream) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001628 // Automatically disable the remote submix input when output is stopped on a
1629 // re routing mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01001630 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
Eric Laurent97ac8712018-07-27 18:59:02 -07001631 outputDesc->mPolicyMix != NULL &&
1632 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1633 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1634 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1635 outputDesc->mPolicyMix->mDeviceAddress,
1636 "remote-submix");
1637 }
1638 }
1639 bool forceDeviceUpdate = false;
1640 if (client->hasPreferredDevice(true)) {
1641 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1642 forceDeviceUpdate = true;
1643 }
1644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001646 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001647
Eric Laurente552edb2014-03-10 17:42:56 -07001648 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001649 if (outputDesc->streamActiveCount(stream) == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001650 outputDesc->mStopTime[stream] = systemTime();
François Gaffie11d30102018-11-02 16:09:09 +01001651 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001652 // delay the device switch by twice the latency because stopOutput() is executed when
1653 // the track stop() command is received and at that time the audio track buffer can
1654 // still contain data that needs to be drained. The latency only covers the audio HAL
1655 // and kernel buffers. Also the latency does not always include additional delay in the
1656 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001657 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001658
1659 // force restoring the device selection on other active outputs if it differs from the
1660 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001661 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001662 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001663 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001664 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001665 desc->isActive() &&
1666 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001667 (newDevices != desc->devices())) {
1668 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1669 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001670
François Gaffie11d30102018-11-02 16:09:09 +01001671 setOutputDevices(desc, newDevices2, force, delayMs);
1672
Eric Laurent57de36c2016-09-28 16:59:11 -07001673 // re-apply device specific volume if not done by setOutputDevice()
1674 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001675 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001676 }
Eric Laurente552edb2014-03-10 17:42:56 -07001677 }
1678 }
1679 // update the outputs if stopping one with a stream that can affect notification routing
1680 handleNotificationRoutingForStream(stream);
1681 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001682
1683 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1684 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1685 setStrategyMute(STRATEGY_SONIFICATION, false, outputDesc);
1686 }
1687
Eric Laurent36829f92017-04-07 19:04:42 -07001688 if (stream == AUDIO_STREAM_MUSIC) {
1689 selectOutputForMusicEffects();
1690 }
Eric Laurente552edb2014-03-10 17:42:56 -07001691 return NO_ERROR;
1692 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001693 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001694 return INVALID_OPERATION;
1695 }
1696}
1697
Eric Laurent8fc147b2018-07-22 19:13:55 -07001698void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001699{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001700 ALOGV("%s portId %d", __FUNCTION__, portId);
1701
1702 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1703 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001704 // If an output descriptor is closed due to a device routing change,
1705 // then there are race conditions with releaseOutput from tracks
1706 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1707 // destroyed shortly thereafter.
1708 //
1709 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001710 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001711 return;
1712 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001713
1714 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent8fc147b2018-07-22 19:13:55 -07001716 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1717 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001719 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001720 return;
1721 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001722 if (--outputDesc->mDirectOpenCount == 0) {
1723 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001724 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
1726 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001727 // stopOutput() needs to be successfully called before releaseOutput()
1728 // otherwise there may be inaccurate stream reference counts.
1729 // This is checked in outputDesc->removeClient below.
1730 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001731}
1732
Eric Laurentcaf7f482014-11-25 17:50:47 -08001733status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1734 audio_io_handle_t *input,
1735 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001736 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001737 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001738 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001739 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001740 input_type_t *inputType,
1741 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001742{
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001743 ALOGV("getInputForAttr() source %d, sampling rate %d, format %#x, channel mask %#x,"
Eric Laurentcaf7f482014-11-25 17:50:47 -08001744 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001745 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001746
Eric Laurentad2e7b92017-09-14 20:06:42 -07001747 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001748 audio_source_t halInputSource;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001749 audio_source_t inputSource = attr->source;
Eric Laurentc722f302014-12-10 11:21:49 -08001750 AudioMix *policyMix = NULL;
François Gaffie11d30102018-11-02 16:09:09 +01001751 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001752 sp<AudioInputDescriptor> inputDesc;
1753 sp<RecordClientDescriptor> clientDesc;
1754 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001755 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001756
1757 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1758 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1759 return INVALID_OPERATION;
1760 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001761
Eric Laurentfe231122017-11-17 17:48:06 -08001762 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1763 inputSource = AUDIO_SOURCE_MIC;
1764 }
1765
Paul McLean466dc8e2015-04-17 13:15:36 -06001766 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001767 sp<DeviceDescriptor> explicitRoutingDevice =
1768 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001769
Eric Laurentad2e7b92017-09-14 20:06:42 -07001770 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1771 // possible
1772 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1773 *input != AUDIO_IO_HANDLE_NONE) {
1774 ssize_t index = mInputs.indexOfKey(*input);
1775 if (index < 0) {
1776 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1777 status = BAD_VALUE;
1778 goto error;
1779 }
1780 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001781 RecordClientVector clients = inputDesc->getClientsForSession(session);
1782 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001783 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1784 status = BAD_VALUE;
1785 goto error;
1786 }
1787 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1788 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001789 // corresponds to a new client and is only permitted from the same UID.
1790 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001791 if (clients.size() > 1) {
1792 for (const auto& client : clients) {
1793 // The client map is ordered by key values (portId) and portIds are allocated
1794 // incrementaly. So the first client in this list is the one opened by audio flinger
1795 // when the mmap stream is created and should be ignored as it does not correspond
1796 // to an actual client
1797 if (client == *clients.cbegin()) {
1798 continue;
1799 }
1800 if (uid != client->uid() && !client->isSilenced()) {
1801 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1802 uid, client->portId(), client->uid());
1803 status = INVALID_OPERATION;
1804 goto error;
1805 }
Eric Laurent331679c2018-04-16 17:03:16 -07001806 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001807 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001808 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001809 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001810
Eric Laurent8f42ea12018-08-08 09:08:25 -07001811 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001812 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001813 }
1814
1815 *input = AUDIO_IO_HANDLE_NONE;
1816 *inputType = API_INPUT_INVALID;
1817
Eric Laurentad2e7b92017-09-14 20:06:42 -07001818 halInputSource = inputSource;
1819
Eric Laurentc447ded2015-01-06 08:47:05 -08001820 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001821 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001822 status = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
1823 if (status != NO_ERROR) {
1824 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01001825 }
1826 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
François Gaffie11d30102018-11-02 16:09:09 +01001827 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1828 String8(attr->tags + strlen("addr=")));
Eric Laurent275e8e92014-11-30 15:14:47 -08001829 } else {
François Gaffie11d30102018-11-02 16:09:09 +01001830 if (explicitRoutingDevice != nullptr) {
1831 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07001832 } else {
1833 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
1834 }
François Gaffie11d30102018-11-02 16:09:09 +01001835 if (device == nullptr) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001836 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurentad2e7b92017-09-14 20:06:42 -07001837 status = BAD_VALUE;
1838 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08001839 }
François Gaffie11d30102018-11-02 16:09:09 +01001840 if (policyMix != nullptr) {
1841 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
1842 // there is an external policy, but this input is attached to a mix of recorders,
1843 // meaning it receives audio injected into the framework, so the recorder doesn't
1844 // know about it and is therefore considered "legacy"
1845 *inputType = API_INPUT_LEGACY;
1846 } else if (audio_is_remote_submix_device(device->type())) {
1847 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX, String8("0"));
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001848 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01001849 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07001850 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001851 } else {
1852 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001853 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001854
Eric Laurent599c7582015-12-07 18:05:55 -08001855 }
1856
François Gaffie11d30102018-11-02 16:09:09 +01001857 *input = getInputForDevice(device, session, inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001858 config, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001859 policyMix);
1860 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001861 status = INVALID_OPERATION;
1862 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08001863 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001864
Eric Laurent8f42ea12018-08-08 09:08:25 -07001865exit:
1866
François Gaffie11d30102018-11-02 16:09:09 +01001867 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
1868 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07001869
Eric Laurent8f42ea12018-08-08 09:08:25 -07001870 isSoundTrigger = inputSource == AUDIO_SOURCE_HOTWORD &&
1871 mSoundTriggerSessions.indexOfKey(session) > 0;
1872 *portId = AudioPort::getNextUniqueId();
1873
François Gaffie11d30102018-11-02 16:09:09 +01001874 clientDesc = new RecordClientDescriptor(*portId, uid, session, *attr, *config,
1875 requestedDeviceId, inputSource,flags, isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001876 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07001877 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001878
1879 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
1880 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001881
Eric Laurent599c7582015-12-07 18:05:55 -08001882 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001883
1884error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07001885 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08001886}
1887
1888
François Gaffie11d30102018-11-02 16:09:09 +01001889audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08001890 audio_session_t session,
Eric Laurent599c7582015-12-07 18:05:55 -08001891 audio_source_t inputSource,
Eric Laurentfe231122017-11-17 17:48:06 -08001892 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08001893 audio_input_flags_t flags,
1894 AudioMix *policyMix)
1895{
1896 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1897 audio_source_t halInputSource = inputSource;
1898 bool isSoundTrigger = false;
1899
1900 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1901 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1902 if (index >= 0) {
1903 input = mSoundTriggerSessions.valueFor(session);
1904 isSoundTrigger = true;
1905 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1906 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1907 } else {
1908 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001909 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001910 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08001911 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001912 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001913 }
1914
Andy Hungf129b032015-04-07 13:45:50 -07001915 // find a compatible input profile (not necessarily identical in parameters)
1916 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08001917 // sampling rate and flags may be updated by getInputProfile
1918 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
1919 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07001920 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08001921 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07001922 audio_input_flags_t profileFlags = flags;
1923 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07001924 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01001925 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07001926 profileFlags);
1927 if (profile != 0) {
1928 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001929 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1930 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001931 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1932 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1933 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01001934 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
1935 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
1936 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001937 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001938 }
Eric Laurente552edb2014-03-10 17:42:56 -07001939 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001940 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08001941 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08001942 if (samplingRate == 0) {
1943 samplingRate = profileSamplingRate;
1944 }
Eric Laurente552edb2014-03-10 17:42:56 -07001945
Eric Laurent322b4d22015-04-03 15:57:54 -07001946 if (profile->getModuleHandle() == 0) {
1947 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001948 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001949 }
1950
Eric Laurent3974e3b2017-12-07 17:58:43 -08001951 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08001952 for (size_t i = 0; i < mInputs.size(); ) {
1953 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
1954 if (desc->mProfile != profile) {
1955 continue;
1956 }
1957 // if sound trigger, reuse input if used by other sound trigger on same session
1958 // else
1959 // reuse input if active client app is not in IDLE state
1960 //
1961 RecordClientVector clients = desc->clientsList();
1962 bool doClose = false;
1963 for (const auto& client : clients) {
1964 if (isSoundTrigger != client->isSoundTrigger()) {
1965 continue;
1966 }
1967 if (client->isSoundTrigger()) {
1968 if (session == client->session()) {
1969 return desc->mIoHandle;
1970 }
1971 continue;
1972 }
1973 if (client->active() && client->appState() != APP_STATE_IDLE) {
1974 return desc->mIoHandle;
1975 }
1976 doClose = true;
1977 }
1978 if (doClose) {
1979 closeInput(desc->mIoHandle);
1980 } else {
1981 i++;
1982 }
1983 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001984 }
1985
Eric Laurentfe231122017-11-17 17:48:06 -08001986 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001987
Eric Laurentfe231122017-11-17 17:48:06 -08001988 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
1989 lConfig.sample_rate = profileSamplingRate;
1990 lConfig.channel_mask = profileChannelMask;
1991 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07001992
François Gaffie11d30102018-11-02 16:09:09 +01001993 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001994
1995 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001996 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08001997 (profileSamplingRate != lConfig.sample_rate) ||
1998 !audio_formats_match(profileFormat, lConfig.format) ||
1999 (profileChannelMask != lConfig.channel_mask)) {
2000 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002001 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002002 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002003 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002004 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002005 }
Eric Laurent599c7582015-12-07 18:05:55 -08002006 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002007 }
2008
Eric Laurentc722f302014-12-10 11:21:49 -08002009 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002010
Eric Laurent599c7582015-12-07 18:05:55 -08002011 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002012 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002013
Eric Laurent599c7582015-12-07 18:05:55 -08002014 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002015}
2016
Eric Laurent4eb58f12018-12-07 16:41:02 -08002017status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002018{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002019 ALOGV("%s portId %d", __FUNCTION__, portId);
2020
2021 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2022 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002023 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024 return BAD_VALUE;
2025 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002027 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002028 if (client->active()) {
2029 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2030 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002031 }
2032
Eric Laurent8f42ea12018-08-08 09:08:25 -07002033 audio_session_t session = client->session();
2034
Eric Laurent4eb58f12018-12-07 16:41:02 -08002035 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002036
Eric Laurent4eb58f12018-12-07 16:41:02 -08002037 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002038
Eric Laurent4eb58f12018-12-07 16:41:02 -08002039 status_t status = inputDesc->start();
2040 if (status != NO_ERROR) {
2041 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002042 }
Eric Laurente552edb2014-03-10 17:42:56 -07002043
Eric Laurent4eb58f12018-12-07 16:41:02 -08002044 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002045 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002046 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002047
Eric Laurent8f42ea12018-08-08 09:08:25 -07002048 // indicate active capture to sound trigger service if starting capture from a mic on
2049 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002050 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002051 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002052
Eric Laurent8f42ea12018-08-08 09:08:25 -07002053 if (inputDesc->activeCount() == 1) {
2054 // if input maps to a dynamic policy with an activity listener, notify of state change
2055 if ((inputDesc->mPolicyMix != NULL)
2056 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2057 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2058 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002059 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002060
François Gaffie11d30102018-11-02 16:09:09 +01002061 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2062 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002063 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2064 SoundTrigger::setCaptureState(true);
2065 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002066
Eric Laurent8f42ea12018-08-08 09:08:25 -07002067 // automatically enable the remote submix output when input is started if not
2068 // used by a policy mix of type MIX_TYPE_RECORDERS
2069 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002070 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002071 String8 address = String8("");
2072 if (inputDesc->mPolicyMix == NULL) {
2073 address = String8("0");
2074 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2075 address = inputDesc->mPolicyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002076 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002077 if (address != "") {
2078 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2079 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2080 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002081 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002082 }
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084
Eric Laurent8f42ea12018-08-08 09:08:25 -07002085 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
Eric Laurente552edb2014-03-10 17:42:56 -07002086
Eric Laurente552edb2014-03-10 17:42:56 -07002087 return NO_ERROR;
2088}
2089
Eric Laurent8fc147b2018-07-22 19:13:55 -07002090status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002091{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002092 ALOGV("%s portId %d", __FUNCTION__, portId);
2093
2094 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2095 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002096 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002097 return BAD_VALUE;
2098 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002099 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002100 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002101 if (!client->active()) {
2102 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002103 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002104 }
2105
Eric Laurent8f42ea12018-08-08 09:08:25 -07002106 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002107
Eric Laurent8f42ea12018-08-08 09:08:25 -07002108 inputDesc->stop();
2109 if (inputDesc->isActive()) {
2110 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2111 } else {
2112 // if input maps to a dynamic policy with an activity listener, notify of state change
2113 if ((inputDesc->mPolicyMix != NULL)
2114 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2115 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2116 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002117 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002118
2119 // automatically disable the remote submix output when input is stopped if not
2120 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002121 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002122 String8 address = String8("");
2123 if (inputDesc->mPolicyMix == NULL) {
2124 address = String8("0");
2125 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2126 address = inputDesc->mPolicyMix->mDeviceAddress;
2127 }
2128 if (address != "") {
2129 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2130 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2131 address, "remote-submix");
2132 }
2133 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002134 resetInputDevice(input);
2135
2136 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2137 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002138 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2139 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2141 SoundTrigger::setCaptureState(false);
2142 }
2143 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002144 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002145 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002146}
2147
Eric Laurent8fc147b2018-07-22 19:13:55 -07002148void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002149{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002150 ALOGV("%s portId %d", __FUNCTION__, portId);
2151
2152 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2153 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002154 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002155 return;
2156 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002157 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002158 audio_io_handle_t input = inputDesc->mIoHandle;
2159
Eric Laurent8f42ea12018-08-08 09:08:25 -07002160 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002161
Andy Hung39efb7a2018-09-26 15:39:28 -07002162 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002163
Andy Hung39efb7a2018-09-26 15:39:28 -07002164 if (inputDesc->getClientCount() > 0) {
2165 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002166 return;
2167 }
2168
Eric Laurent05b90f82014-08-27 15:32:29 -07002169 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002170 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002171 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002172}
2173
Eric Laurent8f42ea12018-08-08 09:08:25 -07002174void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002175{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002176 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002177
2178 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002179 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002180 }
2181}
2182
Eric Laurent8f42ea12018-08-08 09:08:25 -07002183void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2184{
2185 stopInput(portId);
2186 releaseInput(portId);
2187}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002188
Eric Laurentd4692962014-05-05 18:13:44 -07002189void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002190 bool patchRemoved = false;
2191
Mikhail Naganov7e22e942017-12-07 10:04:29 -08002192 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002193 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002194 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002195 if (patch_index >= 0) {
2196 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002197 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002198 mAudioPatches.removeItemsAt(patch_index);
2199 patchRemoved = true;
2200 }
Eric Laurentfe231122017-11-17 17:48:06 -08002201 inputDesc->close();
Eric Laurentd4692962014-05-05 18:13:44 -07002202 }
2203 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002204 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002205 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002206
2207 if (patchRemoved) {
2208 mpClientInterface->onAudioPatchListUpdate();
2209 }
Eric Laurentd4692962014-05-05 18:13:44 -07002210}
2211
Eric Laurente0720872014-03-11 09:30:41 -07002212void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002213 int indexMin,
2214 int indexMax)
2215{
2216 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002217 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002218
2219 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002220 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2221 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002222 continue;
2223 }
2224 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002225 }
Eric Laurente552edb2014-03-10 17:42:56 -07002226}
2227
Eric Laurente0720872014-03-11 09:30:41 -07002228status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002229 int index,
2230 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002231{
2232
Nadav Bar7c605f62017-12-25 00:01:52 +02002233 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2234 // app that has MODIFY_PHONE_STATE permission.
2235 if (((index < mVolumeCurves->getVolumeIndexMin(stream)) &&
2236 !(stream == AUDIO_STREAM_VOICE_CALL && index == 0)) ||
François Gaffied1ab2bd2015-12-02 18:20:06 +01002237 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002238 return BAD_VALUE;
2239 }
2240 if (!audio_is_output_device(device)) {
2241 return BAD_VALUE;
2242 }
2243
2244 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002245 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002246
Eric Laurent1fd372e2016-04-06 14:23:53 -07002247 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002248 stream, device, index);
2249
Eric Laurent28d09f02016-03-08 10:43:05 -08002250 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002251 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2252 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002253 continue;
2254 }
2255 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2256 }
Eric Laurente552edb2014-03-10 17:42:56 -07002257
Eric Laurent1fd372e2016-04-06 14:23:53 -07002258 // update volume on all outputs and streams matching the following:
2259 // - The requested stream (or a stream matching for volume control) is active on the output
2260 // - The device (or devices) selected by the strategy corresponding to this stream includes
2261 // the requested device
2262 // - For non default requested device, currently selected device on the output is either the
2263 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002264 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2265 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002266 status_t status = NO_ERROR;
2267 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002268 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01002269 audio_devices_t curDevice = desc->devices().types();
Eric Laurent794fde22016-03-11 09:50:45 -08002270 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
Eric Laurent3839bc02018-07-10 18:33:34 -07002271 if (!(streamsMatchForvolume(stream, (audio_stream_type_t)curStream))) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002272 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002273 }
Eric Laurentdcd4ab12018-06-29 17:45:13 -07002274 if (!(desc->isStreamActive((audio_stream_type_t)curStream) || isInCall())) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002275 continue;
2276 }
Eric Laurent794fde22016-03-11 09:50:45 -08002277 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002278 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2279 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002280 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2281 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002282 continue;
2283 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002284 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002285 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002286 curStreamDevice |= device;
nobuaki tanaka985d15a2017-07-19 13:38:51 +09002287 applyVolume = (Volume::getDeviceForVolume(curDevice) & curStreamDevice) != 0;
Eric Laurente76f29c2016-09-14 17:17:53 -07002288 } else {
2289 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002290 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002291 }
Eric Laurent3839bc02018-07-10 18:33:34 -07002292 // rescale index before applying to curStream as ranges may be different for
2293 // stream and curStream
2294 int idx = rescaleVolumeIndex(index, stream, (audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002295 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002296 //FIXME: workaround for truncated touch sounds
2297 // delayed volume change for system stream to be removed when the problem is
2298 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002299 status_t volStatus =
Eric Laurent3839bc02018-07-10 18:33:34 -07002300 checkAndSetVolume((audio_stream_type_t)curStream, idx, desc, curDevice,
Eric Laurentdc462862016-07-19 12:29:53 -07002301 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002302 if (volStatus != NO_ERROR) {
2303 status = volStatus;
2304 }
2305 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002306 }
Eric Laurente552edb2014-03-10 17:42:56 -07002307 }
2308 return status;
2309}
2310
Eric Laurente0720872014-03-11 09:30:41 -07002311status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002312 int *index,
2313 audio_devices_t device)
2314{
2315 if (index == NULL) {
2316 return BAD_VALUE;
2317 }
2318 if (!audio_is_output_device(device)) {
2319 return BAD_VALUE;
2320 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002321 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002322 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002323 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002324 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2325 }
François Gaffiedfd74092015-03-19 12:10:59 +01002326 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002327
François Gaffied1ab2bd2015-12-02 18:20:06 +01002328 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002329 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2330 return NO_ERROR;
2331}
2332
Eric Laurent36829f92017-04-07 19:04:42 -07002333audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002334{
2335 // select one output among several suitable for global effects.
2336 // The priority is as follows:
2337 // 1: An offloaded output. If the effect ends up not being offloadable,
2338 // AudioFlinger will invalidate the track and the offloaded output
2339 // will be closed causing the effect to be moved to a PCM output.
2340 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002341 // 3: The primary output
2342 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002343
Eric Laurent3b73df72014-03-11 09:06:29 -07002344 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
François Gaffie11d30102018-11-02 16:09:09 +01002345 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
2346 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Eric Laurent36829f92017-04-07 19:04:42 -07002348 if (outputs.size() == 0) {
2349 return AUDIO_IO_HANDLE_NONE;
2350 }
Eric Laurente552edb2014-03-10 17:42:56 -07002351
Eric Laurent36829f92017-04-07 19:04:42 -07002352 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2353 bool activeOnly = true;
2354
2355 while (output == AUDIO_IO_HANDLE_NONE) {
2356 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2357 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2358 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2359
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002360 for (audio_io_handle_t output : outputs) {
2361 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent36829f92017-04-07 19:04:42 -07002362 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2363 continue;
2364 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002365 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2366 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002367 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002368 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002369 }
2370 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002371 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002372 }
2373 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002374 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002375 }
2376 }
2377 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2378 output = outputOffloaded;
2379 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2380 output = outputDeepBuffer;
2381 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2382 output = outputPrimary;
2383 } else {
2384 output = outputs[0];
2385 }
2386 activeOnly = false;
2387 }
2388
2389 if (output != mMusicEffectOutput) {
2390 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2391 mMusicEffectOutput = output;
2392 }
2393
2394 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002395 return output;
2396}
2397
Eric Laurent36829f92017-04-07 19:04:42 -07002398audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2399{
2400 return selectOutputForMusicEffects();
2401}
2402
Eric Laurente0720872014-03-11 09:30:41 -07002403status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002404 audio_io_handle_t io,
2405 uint32_t strategy,
2406 int session,
2407 int id)
2408{
2409 ssize_t index = mOutputs.indexOfKey(io);
2410 if (index < 0) {
2411 index = mInputs.indexOfKey(io);
2412 if (index < 0) {
2413 ALOGW("registerEffect() unknown io %d", io);
2414 return INVALID_OPERATION;
2415 }
2416 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002417 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002418}
2419
Eric Laurentc241b0d2018-11-28 09:08:49 -08002420status_t AudioPolicyManager::unregisterEffect(int id)
2421{
2422 if (mEffects.getEffect(id) == nullptr) {
2423 return INVALID_OPERATION;
2424 }
2425
2426 if (mEffects.isEffectEnabled(id)) {
2427 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2428 setEffectEnabled(id, false);
2429 }
2430 return mEffects.unregisterEffect(id);
2431}
2432
2433status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2434{
2435 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2436 if (effect == nullptr) {
2437 return INVALID_OPERATION;
2438 }
2439
2440 status_t status = mEffects.setEffectEnabled(id, enabled);
2441 if (status == NO_ERROR) {
2442 mInputs.trackEffectEnabled(effect, enabled);
2443 }
2444 return status;
2445}
2446
Eric Laurentc75307b2015-03-17 15:29:32 -07002447bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2448{
Eric Laurent28d09f02016-03-08 10:43:05 -08002449 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002450 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2451 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002452 continue;
2453 }
2454 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2455 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002456 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002457}
2458
2459bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2460{
2461 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2462}
2463
Eric Laurente0720872014-03-11 09:30:41 -07002464bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002465{
2466 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002467 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002468 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002469 return true;
2470 }
2471 }
2472 return false;
2473}
2474
Eric Laurent275e8e92014-11-30 15:14:47 -08002475// Register a list of custom mixes with their attributes and format.
2476// When a mix is registered, corresponding input and output profiles are
2477// added to the remote submix hw module. The profile contains only the
2478// parameters (sampling rate, format...) specified by the mix.
2479// The corresponding input remote submix device is also connected.
2480//
2481// When a remote submix device is connected, the address is checked to select the
2482// appropriate profile and the corresponding input or output stream is opened.
2483//
2484// When capture starts, getInputForAttr() will:
2485// - 1 look for a mix matching the address passed in attribtutes tags if any
2486// - 2 if none found, getDeviceForInputSource() will:
2487// - 2.1 look for a mix matching the attributes source
2488// - 2.2 if none found, default to device selection by policy rules
2489// At this time, the corresponding output remote submix device is also connected
2490// and active playback use cases can be transferred to this mix if needed when reconnecting
2491// after AudioTracks are invalidated
2492//
2493// When playback starts, getOutputForAttr() will:
2494// - 1 look for a mix matching the address passed in attribtutes tags if any
2495// - 2 if none found, look for a mix matching the attributes usage
2496// - 3 if none found, default to device and output selection by policy rules.
2497
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002498status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002499{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002500 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2501 status_t res = NO_ERROR;
2502
2503 sp<HwModule> rSubmixModule;
2504 // examine each mix's route type
2505 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 AudioMix mix = mixes[i];
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002507 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
Eric Laurent97ac8712018-07-27 18:59:02 -07002508 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002509 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002510 break;
2511 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002512 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002513 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002514 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002515 rSubmixModule = mHwModules.getModuleFromName(
2516 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2517 if (rSubmixModule == 0) {
2518 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration",
2519 i);
2520 res = INVALID_OPERATION;
2521 break;
2522 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002523 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002524
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 String8 address = mix.mDeviceAddress;
2526 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2527 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2528 } else {
2529 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2530 }
François Gaffie036e1e92015-03-19 10:16:24 +01002531
Eric Laurent97ac8712018-07-27 18:59:02 -07002532 if (mPolicyMixes.registerMix(address, mix, 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002533 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002534 res = INVALID_OPERATION;
2535 break;
2536 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002537 audio_config_t outputConfig = mix.mFormat;
2538 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002539 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2540 // stereo and let audio flinger do the channel conversion if needed.
2541 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2542 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2543 rSubmixModule->addOutputProfile(address, &outputConfig,
2544 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2545 rSubmixModule->addInputProfile(address, &inputConfig,
2546 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002547
Eric Laurent97ac8712018-07-27 18:59:02 -07002548 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2550 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2551 address.string(), "remote-submix");
2552 } else {
2553 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2554 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2555 address.string(), "remote-submix");
2556 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2558 String8 address = mix.mDeviceAddress;
2559 audio_devices_t device = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002560 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2561 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002562
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002563 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002564 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2565 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2566 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2567 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2568 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2569 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002570 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2571 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002572 if (mPolicyMixes.registerMix(address, mix, desc) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002573 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002574 } else {
2575 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002576 }
2577 break;
2578 }
2579 }
2580
2581 if (res != NO_ERROR) {
2582 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002583 i, device, address.string());
2584 res = INVALID_OPERATION;
2585 break;
2586 } else if (!foundOutput) {
2587 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2588 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002589 res = INVALID_OPERATION;
2590 break;
2591 }
Eric Laurentc722f302014-12-10 11:21:49 -08002592 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002593 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002594 if (res != NO_ERROR) {
2595 unregisterPolicyMixes(mixes);
2596 }
2597 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002598}
2599
2600status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2601{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002602 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002603 status_t res = NO_ERROR;
2604 sp<HwModule> rSubmixModule;
2605 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002606 for (const auto& mix : mixes) {
2607 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002608
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002609 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002610 rSubmixModule = mHwModules.getModuleFromName(
2611 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2612 if (rSubmixModule == 0) {
2613 res = INVALID_OPERATION;
2614 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002615 }
2616 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002617
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002618 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002619
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002620 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2621 res = INVALID_OPERATION;
2622 continue;
2623 }
2624
2625 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2626 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2627 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2628 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2629 address.string(), "remote-submix");
2630 }
2631 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2632 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2633 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2634 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2635 address.string(), "remote-submix");
2636 }
2637 rSubmixModule->removeOutputProfile(address);
2638 rSubmixModule->removeInputProfile(address);
2639
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002640 } if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2641 if (mPolicyMixes.unregisterMix(mix.mDeviceAddress) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002642 res = INVALID_OPERATION;
2643 continue;
2644 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002645 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002646 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002647 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002648}
2649
Mikhail Naganov100f0122018-11-29 11:22:16 -08002650void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
2651{
2652 size_t i = 0;
2653 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
2654 for (const auto& fmt : mManualSurroundFormats) {
2655 if (i++ != 0) dst->append(", ");
2656 std::string sfmt;
2657 FormatConverter::toString(fmt, sfmt);
2658 dst->append(sfmt.size() >= audioFormatPrefixLen ?
2659 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
2660 }
2661}
2662
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002663status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
2664 const Vector<AudioDeviceTypeAddr>& devices) {
2665 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
2666 // uid/device affinity is only for output devices
2667 for (size_t i = 0; i < devices.size(); i++) {
2668 if (!audio_is_output_device(devices[i].mType)) {
2669 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
2670 devices[i].mType);
2671 return BAD_VALUE;
2672 }
2673 }
2674 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
2675 if (res == NO_ERROR) {
2676 // reevaluate outputs for all given devices
2677 for (size_t i = 0; i < devices.size(); i++) {
2678 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2679 devices[i].mType, devices[i].mAddress, String8());
2680 SortedVector<audio_io_handle_t> outputs;
2681 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002682 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002683 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
2684 " addr=%s", devices[i].mType, devices[i].mAddress.string());
2685 return INVALID_OPERATION;
2686 }
2687 }
2688 }
2689 return res;
2690}
2691
2692status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
2693 ALOGV("%s() uid=%d", __FUNCTION__, uid);
2694 Vector<AudioDeviceTypeAddr> devices;
2695 status_t res = mPolicyMixes.getDevicesForUid(uid, devices);
2696 if (res == NO_ERROR) {
2697 // reevaluate outputs for all found devices
2698 for (size_t i = 0; i < devices.size(); i++) {
2699 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
2700 devices[i].mType, devices[i].mAddress, String8());
2701 SortedVector<audio_io_handle_t> outputs;
2702 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01002703 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08002704 ALOGE("%s() error in checkOutputsForDevice for device=%08x addr=%s",
2705 __FUNCTION__, devices[i].mType, devices[i].mAddress.string());
2706 return INVALID_OPERATION;
2707 }
2708 }
2709 }
2710
2711 return res;
2712}
2713
Andy Hungc29d82b2018-10-05 12:23:17 -07002714void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07002715{
Andy Hungc29d82b2018-10-05 12:23:17 -07002716 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
2717 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07002718 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002719 std::string stateLiteral;
2720 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07002721 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002722 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
2723 "communications", "media", "record", "dock", "system",
2724 "HDMI system audio", "encoded surround output", "vibrate ringing" };
2725 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
2726 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08002727 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
2728 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
2729 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
2730 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
2731 dst->append(" (MANUAL: ");
2732 dumpManualSurroundFormats(dst);
2733 dst->append(")");
2734 }
2735 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07002736 }
Andy Hungc29d82b2018-10-05 12:23:17 -07002737 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
2738 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
2739 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
2740 mAvailableOutputDevices.dump(dst, String8("Available output"));
2741 mAvailableInputDevices.dump(dst, String8("Available input"));
2742 mHwModulesAll.dump(dst);
2743 mOutputs.dump(dst);
2744 mInputs.dump(dst);
2745 mVolumeCurves->dump(dst);
2746 mEffects.dump(dst);
2747 mAudioPatches.dump(dst);
2748 mPolicyMixes.dump(dst);
2749 mAudioSources.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07002750}
2751
2752status_t AudioPolicyManager::dump(int fd)
2753{
2754 String8 result;
2755 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07002756 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002757 return NO_ERROR;
2758}
2759
2760// This function checks for the parameters which can be offloaded.
2761// This can be enhanced depending on the capability of the DSP and policy
2762// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002763bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002764{
2765 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002766 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002767 offloadInfo.sample_rate, offloadInfo.channel_mask,
2768 offloadInfo.format,
2769 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2770 offloadInfo.has_video);
2771
Andy Hung2ddee192015-12-18 17:34:44 -08002772 if (mMasterMono) {
2773 return false; // no offloading if mono is set.
2774 }
2775
Eric Laurente552edb2014-03-10 17:42:56 -07002776 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07002777 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
2778 ALOGV("offload disabled by audio.offload.disable");
2779 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002780 }
2781
2782 // Check if stream type is music, then only allow offload as of now.
2783 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2784 {
2785 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2786 return false;
2787 }
2788
2789 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002790 const bool allowOffloadWithVideo =
2791 property_get_bool("audio.offload.video", false /* default_value */);
2792 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002793 ALOGV("isOffloadSupported: has_video == true, returning false");
2794 return false;
2795 }
2796
2797 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07002798 const int min_duration_secs = property_get_int32(
2799 "audio.offload.min.duration.secs", -1 /* default_value */);
2800 if (min_duration_secs >= 0) {
2801 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
2802 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
2803 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07002804 return false;
2805 }
2806 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2807 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2808 return false;
2809 }
2810
2811 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2812 // creating an offloaded track and tearing it down immediately after start when audioflinger
2813 // detects there is an active non offloadable effect.
2814 // FIXME: We should check the audio session here but we do not have it in this context.
2815 // This may prevent offloading in rare situations where effects are left active by apps
2816 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002817 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002818 return false;
2819 }
2820
2821 // See if there is a profile to support this.
2822 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01002823 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002824 offloadInfo.sample_rate,
2825 offloadInfo.format,
2826 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10002827 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
2828 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07002829 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2830 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002831}
2832
Michael Chana94fbb22018-04-24 14:31:19 +10002833bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
2834 const audio_attributes_t& attributes) {
2835 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
2836 audio_attributes_flags_to_audio_output_flags(attributes.flags, output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01002837 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10002838 config.sample_rate,
2839 config.format,
2840 config.channel_mask,
2841 output_flags,
2842 true /* directOnly */);
2843 ALOGV("%s() profile %sfound with name: %s, "
2844 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
2845 __FUNCTION__, profile != 0 ? "" : "NOT ",
2846 (profile != 0 ? profile->getTagName().string() : "null"),
2847 config.sample_rate, config.format, config.channel_mask, output_flags);
2848 return (profile != 0);
2849}
2850
Eric Laurent6a94d692014-05-20 11:18:06 -07002851status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2852 audio_port_type_t type,
2853 unsigned int *num_ports,
2854 struct audio_port *ports,
2855 unsigned int *generation)
2856{
2857 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2858 generation == NULL) {
2859 return BAD_VALUE;
2860 }
2861 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2862 if (ports == NULL) {
2863 *num_ports = 0;
2864 }
2865
2866 size_t portsWritten = 0;
2867 size_t portsMax = *num_ports;
2868 *num_ports = 0;
2869 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002870 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2871 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002872 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002873 for (const auto& dev : mAvailableOutputDevices) {
2874 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002875 continue;
2876 }
2877 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002878 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002879 }
2880 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002881 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002882 }
2883 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002884 for (const auto& dev : mAvailableInputDevices) {
2885 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002886 continue;
2887 }
2888 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002889 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07002890 }
2891 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002892 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002893 }
2894 }
2895 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2896 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2897 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2898 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2899 }
2900 *num_ports += mInputs.size();
2901 }
2902 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002903 size_t numOutputs = 0;
2904 for (size_t i = 0; i < mOutputs.size(); i++) {
2905 if (!mOutputs[i]->isDuplicated()) {
2906 numOutputs++;
2907 if (portsWritten < portsMax) {
2908 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2909 }
2910 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002911 }
Eric Laurent84c70242014-06-23 08:46:27 -07002912 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002913 }
2914 }
2915 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002916 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002917 return NO_ERROR;
2918}
2919
Eric Laurent99fcae42018-05-17 16:59:18 -07002920status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07002921{
Eric Laurent99fcae42018-05-17 16:59:18 -07002922 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
2923 return BAD_VALUE;
2924 }
2925 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
2926 if (dev != 0) {
2927 dev->toAudioPort(port);
2928 return NO_ERROR;
2929 }
2930 dev = mAvailableInputDevices.getDeviceFromId(port->id);
2931 if (dev != 0) {
2932 dev->toAudioPort(port);
2933 return NO_ERROR;
2934 }
2935 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
2936 if (out != 0) {
2937 out->toAudioPort(port);
2938 return NO_ERROR;
2939 }
2940 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
2941 if (in != 0) {
2942 in->toAudioPort(port);
2943 return NO_ERROR;
2944 }
2945 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002946}
2947
Eric Laurent6a94d692014-05-20 11:18:06 -07002948status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2949 audio_patch_handle_t *handle,
2950 uid_t uid)
2951{
2952 ALOGV("createAudioPatch()");
2953
2954 if (handle == NULL || patch == NULL) {
2955 return BAD_VALUE;
2956 }
2957 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2958
Mikhail Naganovac9858b2018-06-15 13:12:37 -07002959 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07002960 return BAD_VALUE;
2961 }
2962 // only one source per audio patch supported for now
2963 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002964 return INVALID_OPERATION;
2965 }
Eric Laurent874c42872014-08-08 15:13:39 -07002966
2967 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002968 return INVALID_OPERATION;
2969 }
Eric Laurent874c42872014-08-08 15:13:39 -07002970 for (size_t i = 0; i < patch->num_sinks; i++) {
2971 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2972 return INVALID_OPERATION;
2973 }
2974 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002975
2976 sp<AudioPatch> patchDesc;
2977 ssize_t index = mAudioPatches.indexOfKey(*handle);
2978
Eric Laurent6a94d692014-05-20 11:18:06 -07002979 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2980 patch->sources[0].role,
2981 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002982#if LOG_NDEBUG == 0
2983 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002984 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002985 patch->sinks[i].role,
2986 patch->sinks[i].type);
2987 }
2988#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002989
2990 if (index >= 0) {
2991 patchDesc = mAudioPatches.valueAt(index);
2992 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2993 mUidCached, patchDesc->mUid, uid);
2994 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2995 return INVALID_OPERATION;
2996 }
2997 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002998 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002999 }
3000
3001 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003002 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003003 if (outputDesc == NULL) {
3004 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3005 return BAD_VALUE;
3006 }
Eric Laurent84c70242014-06-23 08:46:27 -07003007 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3008 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 if (patchDesc != 0) {
3010 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3011 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3012 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3013 return BAD_VALUE;
3014 }
3015 }
Eric Laurent874c42872014-08-08 15:13:39 -07003016 DeviceVector devices;
3017 for (size_t i = 0; i < patch->num_sinks; i++) {
3018 // Only support mix to devices connection
3019 // TODO add support for mix to mix connection
3020 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3021 ALOGV("createAudioPatch() source mix but sink is not a device");
3022 return INVALID_OPERATION;
3023 }
3024 sp<DeviceDescriptor> devDesc =
3025 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3026 if (devDesc == 0) {
3027 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3028 return BAD_VALUE;
3029 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003030
François Gaffie11d30102018-11-02 16:09:09 +01003031 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003032 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003033 NULL, // updatedSamplingRate
3034 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003035 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003036 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003037 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003038 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07003039 ALOGV("createAudioPatch() profile not supported for device %08x",
3040 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003041 return INVALID_OPERATION;
3042 }
3043 devices.add(devDesc);
3044 }
3045 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003046 return INVALID_OPERATION;
3047 }
Eric Laurent874c42872014-08-08 15:13:39 -07003048
Eric Laurent6a94d692014-05-20 11:18:06 -07003049 // TODO: reconfigure output format and channels here
3050 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07003051 devices.types(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003052 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003053 index = mAudioPatches.indexOfKey(*handle);
3054 if (index >= 0) {
3055 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3056 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3057 }
3058 patchDesc = mAudioPatches.valueAt(index);
3059 patchDesc->mUid = uid;
3060 ALOGV("createAudioPatch() success");
3061 } else {
3062 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3063 return INVALID_OPERATION;
3064 }
3065 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3066 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3067 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003068 // only one sink supported when connecting an input device to a mix
3069 if (patch->num_sinks > 1) {
3070 return INVALID_OPERATION;
3071 }
François Gaffie53615e22015-03-19 09:24:12 +01003072 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003073 if (inputDesc == NULL) {
3074 return BAD_VALUE;
3075 }
3076 if (patchDesc != 0) {
3077 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3078 return BAD_VALUE;
3079 }
3080 }
François Gaffie11d30102018-11-02 16:09:09 +01003081 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003082 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003083 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003084 return BAD_VALUE;
3085 }
3086
François Gaffie11d30102018-11-02 16:09:09 +01003087 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003088 patch->sinks[0].sample_rate,
3089 NULL, /*updatedSampleRate*/
3090 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003091 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003092 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003093 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003094 // FIXME for the parameter type,
3095 // and the NONE
3096 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003097 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003098 return INVALID_OPERATION;
3099 }
3100 // TODO: reconfigure output format and channels here
François Gaffie11d30102018-11-02 16:09:09 +01003101 ALOGV("%s() setting device %s on output %d", __func__,
3102 device->toString().c_str(), inputDesc->mIoHandle);
3103 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003104 index = mAudioPatches.indexOfKey(*handle);
3105 if (index >= 0) {
3106 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3107 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3108 }
3109 patchDesc = mAudioPatches.valueAt(index);
3110 patchDesc->mUid = uid;
3111 ALOGV("createAudioPatch() success");
3112 } else {
3113 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3114 return INVALID_OPERATION;
3115 }
3116 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3117 // device to device connection
3118 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003119 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003120 return BAD_VALUE;
3121 }
3122 }
François Gaffie11d30102018-11-02 16:09:09 +01003123 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003124 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003125 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003126 return BAD_VALUE;
3127 }
Eric Laurent874c42872014-08-08 15:13:39 -07003128
Eric Laurent6a94d692014-05-20 11:18:06 -07003129 //update source and sink with our own data as the data passed in the patch may
3130 // be incomplete.
3131 struct audio_patch newPatch = *patch;
François Gaffie11d30102018-11-02 16:09:09 +01003132 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003133
Eric Laurent874c42872014-08-08 15:13:39 -07003134 for (size_t i = 0; i < patch->num_sinks; i++) {
3135 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3136 ALOGV("createAudioPatch() source device but one sink is not a device");
3137 return INVALID_OPERATION;
3138 }
3139
François Gaffie11d30102018-11-02 16:09:09 +01003140 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003141 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003142 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003143 return BAD_VALUE;
3144 }
François Gaffie11d30102018-11-02 16:09:09 +01003145 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
Eric Laurent874c42872014-08-08 15:13:39 -07003146
Eric Laurent3bcf8592015-04-03 12:13:24 -07003147 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003148 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003149 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003150 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffie11d30102018-11-02 16:09:09 +01003151 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3152 (srcDevice->getModuleVersionMajor() < 3) ||
3153 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003154 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003155 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003156 return INVALID_OPERATION;
3157 }
Eric Laurent874c42872014-08-08 15:13:39 -07003158 SortedVector<audio_io_handle_t> outputs =
François Gaffie11d30102018-11-02 16:09:09 +01003159 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003160 // if the sink device is reachable via an opened output stream, request to go via
3161 // this output stream by adding a second source to the patch description
jiabin40573322018-11-08 12:08:02 -08003162 audio_io_handle_t output = selectOutput(outputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003163 if (output != AUDIO_IO_HANDLE_NONE) {
3164 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3165 if (outputDesc->isDuplicated()) {
3166 return INVALID_OPERATION;
3167 }
3168 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003169 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003170 newPatch.num_sources = 2;
3171 }
Eric Laurent83b88082014-06-20 18:31:16 -07003172 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003173 }
3174 // TODO: check from routing capabilities in config file and other conflicting patches
3175
Mikhail Naganovdc769682018-05-04 15:34:08 -07003176 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3177 if (status != NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003178 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3179 status);
3180 return INVALID_OPERATION;
3181 }
3182 } else {
3183 return BAD_VALUE;
3184 }
3185 } else {
3186 return BAD_VALUE;
3187 }
3188 return NO_ERROR;
3189}
3190
3191status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3192 uid_t uid)
3193{
3194 ALOGV("releaseAudioPatch() patch %d", handle);
3195
3196 ssize_t index = mAudioPatches.indexOfKey(handle);
3197
3198 if (index < 0) {
3199 return BAD_VALUE;
3200 }
3201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3202 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3203 mUidCached, patchDesc->mUid, uid);
3204 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3205 return INVALID_OPERATION;
3206 }
3207
3208 struct audio_patch *patch = &patchDesc->mPatch;
3209 patchDesc->mUid = mUidCached;
3210 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003211 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003212 if (outputDesc == NULL) {
3213 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3214 return BAD_VALUE;
3215 }
3216
François Gaffie11d30102018-11-02 16:09:09 +01003217 setOutputDevices(outputDesc,
3218 getNewOutputDevices(outputDesc, true /*fromCache*/),
3219 true,
3220 0,
3221 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003222 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3223 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003224 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003225 if (inputDesc == NULL) {
3226 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3227 return BAD_VALUE;
3228 }
3229 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003230 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003231 true,
3232 NULL);
3233 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003234 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3235 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3236 status, patchDesc->mAfPatchHandle);
3237 removeAudioPatch(patchDesc->mHandle);
3238 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003239 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003240 } else {
3241 return BAD_VALUE;
3242 }
3243 } else {
3244 return BAD_VALUE;
3245 }
3246 return NO_ERROR;
3247}
3248
3249status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3250 struct audio_patch *patches,
3251 unsigned int *generation)
3252{
François Gaffie53615e22015-03-19 09:24:12 +01003253 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003254 return BAD_VALUE;
3255 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003256 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003257 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003258}
3259
Eric Laurente1715a42014-05-20 11:30:42 -07003260status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003261{
Eric Laurente1715a42014-05-20 11:30:42 -07003262 ALOGV("setAudioPortConfig()");
3263
3264 if (config == NULL) {
3265 return BAD_VALUE;
3266 }
3267 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3268 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003269 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3270 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003271 }
3272
Eric Laurenta121f902014-06-03 13:32:54 -07003273 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003274 if (config->type == AUDIO_PORT_TYPE_MIX) {
3275 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003276 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003277 if (outputDesc == NULL) {
3278 return BAD_VALUE;
3279 }
Eric Laurent84c70242014-06-23 08:46:27 -07003280 ALOG_ASSERT(!outputDesc->isDuplicated(),
3281 "setAudioPortConfig() called on duplicated output %d",
3282 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003283 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003284 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003285 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003286 if (inputDesc == NULL) {
3287 return BAD_VALUE;
3288 }
Eric Laurenta121f902014-06-03 13:32:54 -07003289 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003290 } else {
3291 return BAD_VALUE;
3292 }
3293 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3294 sp<DeviceDescriptor> deviceDesc;
3295 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3296 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3297 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3298 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3299 } else {
3300 return BAD_VALUE;
3301 }
3302 if (deviceDesc == NULL) {
3303 return BAD_VALUE;
3304 }
Eric Laurenta121f902014-06-03 13:32:54 -07003305 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003306 } else {
3307 return BAD_VALUE;
3308 }
3309
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003310 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003311 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3312 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003313 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003314 audioPortConfig->toAudioPortConfig(&newConfig, config);
3315 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003316 }
Eric Laurenta121f902014-06-03 13:32:54 -07003317 if (status != NO_ERROR) {
3318 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003319 }
Eric Laurente1715a42014-05-20 11:30:42 -07003320
3321 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003322}
3323
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003324void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3325{
Eric Laurentd60560a2015-04-10 11:31:20 -07003326 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003327 clearAudioPatches(uid);
3328 clearSessionRoutes(uid);
3329}
3330
Eric Laurent6a94d692014-05-20 11:18:06 -07003331void AudioPolicyManager::clearAudioPatches(uid_t uid)
3332{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003333 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003334 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3335 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003336 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003337 }
3338 }
3339}
3340
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003341void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3342 audio_io_handle_t ouptutToSkip)
3343{
François Gaffie11d30102018-11-02 16:09:09 +01003344 DeviceVector devices = getDevicesForStrategy(strategy, false /*fromCache*/);
3345 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003346 for (size_t j = 0; j < mOutputs.size(); j++) {
3347 if (mOutputs.keyAt(j) == ouptutToSkip) {
3348 continue;
3349 }
3350 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3351 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3352 continue;
3353 }
3354 // If the default device for this strategy is on another output mix,
3355 // invalidate all tracks in this strategy to force re connection.
3356 // Otherwise select new device on the output mix.
3357 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003358 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003359 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3360 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3361 }
3362 }
3363 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003364 setOutputDevices(
3365 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003366 }
3367 }
3368}
3369
3370void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3371{
3372 // remove output routes associated with this uid
3373 SortedVector<routing_strategy> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003374 for (size_t i = 0; i < mOutputs.size(); i++) {
3375 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003376 for (const auto& client : outputDesc->getClientIterable()) {
3377 if (client->hasPreferredDevice() && client->uid() == uid) {
3378 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3379 affectedStrategies.add(getStrategy(client->stream()));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003380 }
3381 }
3382 }
3383 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003384 for (const auto& strategy : affectedStrategies) {
3385 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003386 }
3387
3388 // remove input routes associated with this uid
3389 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003390 for (size_t i = 0; i < mInputs.size(); i++) {
3391 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003392 for (const auto& client : inputDesc->getClientIterable()) {
3393 if (client->hasPreferredDevice() && client->uid() == uid) {
3394 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3395 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003396 }
3397 }
3398 }
3399 // reroute inputs if necessary
3400 SortedVector<audio_io_handle_t> inputsToClose;
3401 for (size_t i = 0; i < mInputs.size(); i++) {
3402 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003403 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003404 inputsToClose.add(inputDesc->mIoHandle);
3405 }
3406 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003407 for (const auto& input : inputsToClose) {
3408 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003409 }
3410}
3411
Eric Laurentd60560a2015-04-10 11:31:20 -07003412void AudioPolicyManager::clearAudioSources(uid_t uid)
3413{
3414 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003415 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3416 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003417 stopAudioSource(mAudioSources.keyAt(i));
3418 }
3419 }
3420}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003421
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003422status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3423 audio_io_handle_t *ioHandle,
3424 audio_devices_t *device)
3425{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003426 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3427 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
François Gaffie11d30102018-11-02 16:09:09 +01003428 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003429
François Gaffiedf372692015-03-19 10:43:27 +01003430 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003431}
3432
Eric Laurentd60560a2015-04-10 11:31:20 -07003433status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003434 const audio_attributes_t *attributes,
3435 audio_port_handle_t *portId,
3436 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003437{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003438 ALOGV("%s", __FUNCTION__);
3439 *portId = AUDIO_PORT_HANDLE_NONE;
3440
3441 if (source == NULL || attributes == NULL || portId == NULL) {
3442 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3443 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003444 return BAD_VALUE;
3445 }
3446
Eric Laurentd60560a2015-04-10 11:31:20 -07003447 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3448 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003449 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3450 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003451 return INVALID_OPERATION;
3452 }
3453
François Gaffie11d30102018-11-02 16:09:09 +01003454 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003455 mAvailableInputDevices.getDevice(source->ext.device.type,
François Gaffie11d30102018-11-02 16:09:09 +01003456 String8(source->ext.device.address));
3457 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003458 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003459 return BAD_VALUE;
3460 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003461
3462 *portId = AudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003463
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003464 struct audio_patch dummyPatch = {};
Eric Laurentd60560a2015-04-10 11:31:20 -07003465 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003466
3467 sp<SourceClientDescriptor> sourceDesc =
François Gaffie11d30102018-11-02 16:09:09 +01003468 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
Eric Laurent97ac8712018-07-27 18:59:02 -07003469 streamTypefromAttributesInt(attributes),
3470 getStrategyForAttr(attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003471
3472 status_t status = connectAudioSource(sourceDesc);
3473 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003474 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003475 }
3476 return status;
3477}
3478
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003479status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003480{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003481 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003482
3483 // make sure we only have one patch per source.
3484 disconnectAudioSource(sourceDesc);
3485
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003486 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003487 routing_strategy strategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003488 audio_stream_type_t stream = sourceDesc->stream();
François Gaffie11d30102018-11-02 16:09:09 +01003489 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003490
François Gaffie11d30102018-11-02 16:09:09 +01003491 DeviceVector sinkDevices = getDevicesForStrategy(strategy, true);
3492 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for strategy");
3493 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3494 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3495 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07003496
3497 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003498
François Gaffie11d30102018-11-02 16:09:09 +01003499 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3500 srcDevice->getModuleVersionMajor() >= 3 &&
3501 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3502 srcDevice->getAudioPort()->mGains.size() > 0) {
François Gaffie83d789d2018-05-29 13:29:19 +02003503 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003504 // TODO: may explicitly specify whether we should use HW or SW patch
François Gaffie83d789d2018-05-29 13:29:19 +02003505 // create patch between src device and output device
3506 // create Hwoutput and add to mHwOutputs
Eric Laurentd60560a2015-04-10 11:31:20 -07003507 } else {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003508 audio_attributes_t resultAttr;
3509 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3510 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3511 config.sample_rate = sourceDesc->config().sample_rate;
3512 config.channel_mask = sourceDesc->config().channel_mask;
3513 config.format = sourceDesc->config().format;
3514 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3515 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3516 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3517 &attributes, &stream, sourceDesc->uid(), &config, &flags, &selectedDeviceId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003518 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01003519 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003520 return INVALID_OPERATION;
3521 }
3522 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3523 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01003524 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
Eric Laurentd60560a2015-04-10 11:31:20 -07003525 return INVALID_OPERATION;
3526 }
Eric Laurent733ce942017-12-07 12:18:25 -08003527 status_t status = outputDesc->start();
3528 if (status != NO_ERROR) {
3529 return status;
3530 }
3531
Eric Laurentd60560a2015-04-10 11:31:20 -07003532 // create a special patch with no sink and two sources:
3533 // - the second source indicates to PatchPanel through which output mix this patch should
3534 // be connected as well as the stream type for volume control
3535 // - the sink is defined by whatever output device is currently selected for the output
3536 // though which this patch is routed.
Mikhail Naganovdc769682018-05-04 15:34:08 -07003537 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01003538 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
Mikhail Naganovdc769682018-05-04 15:34:08 -07003539 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
Eric Laurentd60560a2015-04-10 11:31:20 -07003540 &afPatchHandle,
3541 0);
3542 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3543 status, afPatchHandle);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003544 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
Eric Laurentd60560a2015-04-10 11:31:20 -07003545 if (status != NO_ERROR) {
3546 ALOGW("%s patch panel could not connect device patch, error %d",
3547 __FUNCTION__, status);
3548 return INVALID_OPERATION;
3549 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07003550
3551 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3552 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3553 return INVALID_OPERATION;
3554 }
3555 outputDesc->addClient(sourceDesc);
3556
Eric Laurentd60560a2015-04-10 11:31:20 -07003557 uint32_t delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07003558 status = startSource(outputDesc, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003559
3560 if (status != NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003561 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
Eric Laurentd60560a2015-04-10 11:31:20 -07003562 return status;
3563 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003564 sourceDesc->setSwOutput(outputDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003565 if (delayMs != 0) {
3566 usleep(delayMs * 1000);
3567 }
3568 }
3569
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003570 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3571 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
Eric Laurentd60560a2015-04-10 11:31:20 -07003572
3573 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003574}
3575
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003576status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07003577{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003578 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3579 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003580 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003581 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003582 return BAD_VALUE;
3583 }
3584 status_t status = disconnectAudioSource(sourceDesc);
3585
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003586 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003587 return status;
3588}
3589
Andy Hung2ddee192015-12-18 17:34:44 -08003590status_t AudioPolicyManager::setMasterMono(bool mono)
3591{
3592 if (mMasterMono == mono) {
3593 return NO_ERROR;
3594 }
3595 mMasterMono = mono;
3596 // if enabling mono we close all offloaded devices, which will invalidate the
3597 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3598 // for recreating the new AudioTrack as non-offloaded PCM.
3599 //
3600 // If disabling mono, we leave all tracks as is: we don't know which clients
3601 // and tracks are able to be recreated as offloaded. The next "song" should
3602 // play back offloaded.
3603 if (mMasterMono) {
3604 Vector<audio_io_handle_t> offloaded;
3605 for (size_t i = 0; i < mOutputs.size(); ++i) {
3606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3607 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3608 offloaded.push(desc->mIoHandle);
3609 }
3610 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003611 for (const auto& handle : offloaded) {
3612 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08003613 }
3614 }
3615 // update master mono for all remaining outputs
3616 for (size_t i = 0; i < mOutputs.size(); ++i) {
3617 updateMono(mOutputs.keyAt(i));
3618 }
3619 return NO_ERROR;
3620}
3621
3622status_t AudioPolicyManager::getMasterMono(bool *mono)
3623{
3624 *mono = mMasterMono;
3625 return NO_ERROR;
3626}
3627
Eric Laurentac9cef52017-06-09 15:46:26 -07003628float AudioPolicyManager::getStreamVolumeDB(
3629 audio_stream_type_t stream, int index, audio_devices_t device)
3630{
3631 return computeVolume(stream, index, device);
3632}
3633
jiabin81772902018-04-02 17:52:27 -07003634status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
3635 audio_format_t *surroundFormats,
3636 bool *surroundFormatsEnabled,
3637 bool reported)
3638{
3639 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
3640 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
3641 return BAD_VALUE;
3642 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003643 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
3644 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07003645
3646 size_t formatsWritten = 0;
3647 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003648 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07003649 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003650 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07003651 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08003652 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
3653 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
3654 FormatVector supportedFormats =
3655 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
3656 for (size_t j = 0; j < supportedFormats.size(); j++) {
3657 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
3658 formats.insert(supportedFormats[j]);
3659 } else {
3660 for (const auto& pair : mConfig.getSurroundFormats()) {
3661 if (pair.second.count(supportedFormats[j]) != 0) {
3662 formats.insert(pair.first);
3663 break;
3664 }
3665 }
3666 }
3667 }
jiabin81772902018-04-02 17:52:27 -07003668 }
3669 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003670 for (const auto& pair : mConfig.getSurroundFormats()) {
3671 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07003672 }
3673 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003674 *numSurroundFormats = formats.size();
3675 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
3676 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07003677 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07003678 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07003679 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08003680 bool formatEnabled = true;
3681 switch (forceUse) {
3682 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
3683 formatEnabled = mManualSurroundFormats.count(format) != 0;
3684 break;
3685 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
3686 formatEnabled = false;
3687 break;
3688 default: // AUTO or ALWAYS => true
3689 break;
jiabin81772902018-04-02 17:52:27 -07003690 }
3691 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
3692 }
jiabin81772902018-04-02 17:52:27 -07003693 }
3694 return NO_ERROR;
3695}
3696
3697status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
3698{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003699 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003700 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
3701 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003702 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07003703 return BAD_VALUE;
3704 }
3705
Mikhail Naganov100f0122018-11-29 11:22:16 -08003706 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
3707 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003708 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07003709 return INVALID_OPERATION;
3710 }
3711
Mikhail Naganov100f0122018-11-29 11:22:16 -08003712 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07003713 return NO_ERROR;
3714 }
3715
Mikhail Naganov100f0122018-11-29 11:22:16 -08003716 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07003717 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003718 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003719 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003720 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07003721 }
3722 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003723 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07003724 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003725 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07003726 }
3727 }
3728
3729 sp<SwAudioOutputDescriptor> outputDesc;
3730 bool profileUpdated = false;
Mikhail Naganov708e0382018-05-30 09:53:04 -07003731 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003732 AUDIO_DEVICE_OUT_HDMI);
3733 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
3734 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003735 String8 address = hdmiOutputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003736 String8 name = hdmiOutputDevices[i]->getName();
3737 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3738 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3739 address.c_str(),
3740 name.c_str());
3741 if (status != NO_ERROR) {
3742 continue;
3743 }
3744 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
3745 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3746 address.c_str(),
3747 name.c_str());
3748 profileUpdated |= (status == NO_ERROR);
3749 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08003750 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
Mikhail Naganov708e0382018-05-30 09:53:04 -07003751 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
jiabin81772902018-04-02 17:52:27 -07003752 AUDIO_DEVICE_IN_HDMI);
3753 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
3754 // Simulate reconnection to update enabled surround sound formats.
François Gaffieaca677c2018-05-03 10:47:50 +02003755 String8 address = hdmiInputDevices[i]->address();
jiabin81772902018-04-02 17:52:27 -07003756 String8 name = hdmiInputDevices[i]->getName();
3757 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3758 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3759 address.c_str(),
3760 name.c_str());
3761 if (status != NO_ERROR) {
3762 continue;
3763 }
3764 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
3765 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3766 address.c_str(),
3767 name.c_str());
3768 profileUpdated |= (status == NO_ERROR);
3769 }
3770
jiabin81772902018-04-02 17:52:27 -07003771 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07003772 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08003773 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07003774 }
3775
3776 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
3777}
3778
Eric Laurentf32108e2018-10-04 17:22:04 -07003779void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003780{
Eric Laurent4eb58f12018-12-07 16:41:02 -08003781 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003782
Eric Laurenta9f86652018-11-28 17:23:11 -08003783 for (size_t i = 0; i < mInputs.size(); i++) {
3784 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3785 RecordClientVector clients = inputDesc->clientsList(false /*activeOnly*/);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003786 for (const auto& client : clients) {
3787 if (uid == client->uid()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003788 client->setAppState(state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08003789 }
3790 }
3791 }
3792}
3793
jiabin6012f912018-11-02 17:06:30 -07003794bool AudioPolicyManager::isHapticPlaybackSupported()
3795{
3796 for (const auto& hwModule : mHwModules) {
3797 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
3798 for (const auto &outProfile : outputProfiles) {
3799 struct audio_port audioPort;
3800 outProfile->toAudioPort(&audioPort);
3801 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
3802 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
3803 return true;
3804 }
3805 }
3806 }
3807 }
3808 return false;
3809}
3810
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003811status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003812{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003813 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003814
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003815 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003816 if (patchDesc == 0) {
3817 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003818 sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003819 return BAD_VALUE;
3820 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003821 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
Eric Laurentd60560a2015-04-10 11:31:20 -07003822
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003823 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003824 if (swOutputDesc != 0) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003825 status_t status = stopSource(swOutputDesc, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08003826 if (status == NO_ERROR) {
3827 swOutputDesc->stop();
3828 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003829 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3830 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003831 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003832 if (hwOutputDesc != 0) {
3833 // release patch between src device and output device
3834 // close Hwoutput and remove from mHwOutputs
3835 } else {
3836 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3837 }
3838 }
3839 return NO_ERROR;
3840}
3841
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003842sp<SourceClientDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
Eric Laurentd60560a2015-04-10 11:31:20 -07003843 audio_io_handle_t output, routing_strategy strategy)
3844{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003845 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07003846 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003847 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3848 audio_attributes_t attributes = sourceDesc->attributes();
Eric Laurent97ac8712018-07-27 18:59:02 -07003849 routing_strategy sourceStrategy = getStrategyForAttr(&attributes);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003850 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07003851 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3852 source = sourceDesc;
3853 break;
3854 }
3855 }
3856 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003857}
3858
Eric Laurente552edb2014-03-10 17:42:56 -07003859// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003860// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003861// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003862uint32_t AudioPolicyManager::nextAudioPortGeneration()
3863{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08003864 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003865}
3866
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003867// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3868static const char *kConfigLocationList[] =
3869 {"/odm/etc", "/vendor/etc", "/system/etc"};
3870static const int kConfigLocationListSize =
3871 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3872
3873static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3874 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07003875 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003876 status_t ret;
3877
Petri Gyntherf497f292018-04-17 18:46:10 -07003878 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false) &&
3879 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
3880 // A2DP offload supported but disabled: try to use special XML file
3881 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
3882 }
3883 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3884
3885 for (const char* fileName : fileNames) {
3886 for (int i = 0; i < kConfigLocationListSize; i++) {
Petri Gyntherf497f292018-04-17 18:46:10 -07003887 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
3888 "%s/%s", kConfigLocationList[i], fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07003889 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07003890 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003891 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07003892 return ret;
3893 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003894 }
3895 }
3896 return ret;
3897}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003898
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003899AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
3900 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07003901 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07003902 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003903 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07003904 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003905 mA2dpSuspended(false),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003906 mVolumeCurves(new VolumeCurvesCollection()),
3907 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices,
Mikhail Naganovbcbcb1b2017-12-13 13:03:35 -08003908 mDefaultOutputDevice, static_cast<VolumeCurvesCollection*>(mVolumeCurves.get())),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003909 mAudioPortGeneration(1),
3910 mBeaconMuteRefCount(0),
3911 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003912 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003913 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003914 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08003915 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07003916{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003917}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003918
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003919AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
3920 : AudioPolicyManager(clientInterface, false /*forTesting*/)
3921{
3922 loadConfig();
3923 initialize();
3924}
François Gaffied1ab2bd2015-12-02 18:20:06 +01003925
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003926// This check is to catch any legacy platform updating to Q without having
3927// switched to XML since its deprecation on O.
3928// TODO: after Q release, remove this check and flag as XML is now the only
3929// option and all legacy platform should have transitioned to XML.
3930#ifndef USE_XML_AUDIO_POLICY_CONF
3931#error Audio policy no longer supports legacy .conf configuration format
François Gaffied1ab2bd2015-12-02 18:20:06 +01003932#endif
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07003933
3934void AudioPolicyManager::loadConfig() {
3935 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003936 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003937 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01003938 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003939}
3940
3941status_t AudioPolicyManager::initialize() {
3942 mVolumeCurves->initializeVolumeCurves(getConfig().isSpeakerDrcEnabled());
François Gaffied1ab2bd2015-12-02 18:20:06 +01003943
3944 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003945 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3946 if (!engineInstance) {
3947 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003948 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003949 }
3950 // Retrieve the Policy Manager Interface
3951 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3952 if (mEngine == NULL) {
3953 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003954 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01003955 }
3956 mEngine->setObserver(this);
3957 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08003958 if (status != NO_ERROR) {
3959 LOG_FATAL("Policy engine not initialized(err=%d)", status);
3960 return status;
3961 }
François Gaffie2110e042015-03-24 08:41:51 +01003962
Eric Laurent3a4311c2014-03-17 12:00:47 -07003963 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003964 // open all output streams needed to access attached devices
Mikhail Naganovd4120142017-12-06 15:49:22 -08003965 for (const auto& hwModule : mHwModulesAll) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003966 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
Mikhail Naganovd4120142017-12-06 15:49:22 -08003967 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
3968 ALOGW("could not open HW module %s", hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003969 continue;
3970 }
Mikhail Naganovd4120142017-12-06 15:49:22 -08003971 mHwModules.push_back(hwModule);
Eric Laurente552edb2014-03-10 17:42:56 -07003972 // open all output streams needed to access attached devices
3973 // except for direct output streams that are only opened when they are actually
3974 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003975 // This also validates mAvailableOutputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08003976 for (const auto& outProfile : hwModule->getOutputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08003977 if (!outProfile->canOpenNewIo()) {
3978 ALOGE("Invalid Output profile max open count %u for profile %s",
3979 outProfile->maxOpenCount, outProfile->getTagName().c_str());
3980 continue;
3981 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003982 if (!outProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003983 ALOGW("Output profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003984 continue;
3985 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003986 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003987 mTtsOutputAvailable = true;
3988 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003989
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003990 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003991 continue;
3992 }
François Gaffie11d30102018-11-02 16:09:09 +01003993 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3994 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
3995 sp<DeviceDescriptor> supportedDevice = 0;
3996 if (supportedDevices.contains(mDefaultOutputDevice)) {
3997 supportedDevice = mDefaultOutputDevice;
Eric Laurent83b88082014-06-20 18:31:16 -07003998 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003999 // choose first device present in profile's SupportedDevices also part of
4000 // mAvailableOutputDevices.
4001 if (availProfileDevices.isEmpty()) {
4002 continue;
4003 }
4004 supportedDevice = availProfileDevices.itemAt(0);
Eric Laurente552edb2014-03-10 17:42:56 -07004005 }
François Gaffie11d30102018-11-02 16:09:09 +01004006 if (!mAvailableOutputDevices.contains(supportedDevice)) {
Eric Laurentd78f1532014-09-16 16:38:20 -07004007 continue;
4008 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004009 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4010 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004011 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004012 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4013 AUDIO_STREAM_DEFAULT,
4014 AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurentd78f1532014-09-16 16:38:20 -07004015 if (status != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004016 ALOGW("Cannot open output stream for devices %s on hw module %s",
4017 supportedDevice->toString().c_str(), hwModule->getName());
4018 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004019 }
François Gaffie11d30102018-11-02 16:09:09 +01004020 for (const auto &device : availProfileDevices) {
4021 // give a valid ID to an attached device once confirmed it is reachable
4022 if (!device->isAttached()) {
4023 device->attach(hwModule);
4024 }
4025 }
4026 if (mPrimaryOutput == 0 &&
4027 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4028 mPrimaryOutput = outputDesc;
4029 }
4030 addOutput(output, outputDesc);
4031 setOutputDevices(outputDesc,
4032 DeviceVector(supportedDevice),
4033 true,
4034 0,
4035 NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07004036 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004037 // open input streams needed to access attached devices to validate
4038 // mAvailableInputDevices list
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004039 for (const auto& inProfile : hwModule->getInputProfiles()) {
Eric Laurent3974e3b2017-12-07 17:58:43 -08004040 if (!inProfile->canOpenNewIo()) {
4041 ALOGE("Invalid Input profile max open count %u for profile %s",
4042 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4043 continue;
4044 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004045 if (!inProfile->hasSupportedDevices()) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004046 ALOGW("Input profile contains no device on module %s", hwModule->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07004047 continue;
4048 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004049 // chose first device present in profile's SupportedDevices also part of
François Gaffie11d30102018-11-02 16:09:09 +01004050 // available input devices
4051 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4052 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4053 if (availProfileDevices.isEmpty()) {
4054 ALOGE("%s: Input device list is empty!", __FUNCTION__);
Eric Laurentd78f1532014-09-16 16:38:20 -07004055 continue;
4056 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08004057 sp<AudioInputDescriptor> inputDesc =
Eric Laurentfe231122017-11-17 17:48:06 -08004058 new AudioInputDescriptor(inProfile, mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07004059
Eric Laurentd78f1532014-09-16 16:38:20 -07004060 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004061 status_t status = inputDesc->open(nullptr,
François Gaffie11d30102018-11-02 16:09:09 +01004062 availProfileDevices.itemAt(0),
Eric Laurentfe231122017-11-17 17:48:06 -08004063 AUDIO_SOURCE_MIC,
4064 AUDIO_INPUT_FLAG_NONE,
4065 &input);
François Gaffie11d30102018-11-02 16:09:09 +01004066 if (status != NO_ERROR) {
4067 ALOGW("Cannot open input stream for device %s on hw module %s",
4068 availProfileDevices.toString().c_str(),
Mikhail Naganovd4120142017-12-06 15:49:22 -08004069 hwModule->getName());
François Gaffie11d30102018-11-02 16:09:09 +01004070 continue;
Eric Laurentd78f1532014-09-16 16:38:20 -07004071 }
François Gaffie11d30102018-11-02 16:09:09 +01004072 for (const auto &device : availProfileDevices) {
4073 // give a valid ID to an attached device once confirmed it is reachable
4074 if (!device->isAttached()) {
4075 device->attach(hwModule);
4076 device->importAudioPort(inProfile, true);
4077 }
4078 }
4079 inputDesc->close();
Eric Laurent3a4311c2014-03-17 12:00:47 -07004080 }
4081 }
4082 // make sure all attached devices have been allocated a unique ID
François Gaffie11d30102018-11-02 16:09:09 +01004083 auto checkAndSetAvailable = [this](auto& devices) {
4084 for (const auto &device : devices) {
4085 if (!device->isAttached()) {
4086 ALOGW("device %s is unreachable", device->toString().c_str());
4087 devices.remove(device);
4088 continue;
4089 }
4090 // Device is now validated and can be appended to the available devices of the engine
4091 mEngine->setDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092 }
François Gaffie11d30102018-11-02 16:09:09 +01004093 };
4094 checkAndSetAvailable(mAvailableOutputDevices);
4095 checkAndSetAvailable(mAvailableInputDevices);
4096
Eric Laurent3a4311c2014-03-17 12:00:47 -07004097 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004098 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4099 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4100 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004101 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004102 }
jiabin9ff780e2018-03-19 18:19:52 -07004103 // If microphones address is empty, set it according to device type
4104 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
François Gaffieaca677c2018-05-03 10:47:50 +02004105 if (mAvailableInputDevices[i]->address().isEmpty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004106 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004107 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004108 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin20729a72019-01-04 16:01:55 -08004109 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
jiabin9ff780e2018-03-19 18:19:52 -07004110 }
4111 }
4112 }
Eric Laurente552edb2014-03-10 17:42:56 -07004113
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004114 if (mPrimaryOutput == 0) {
4115 ALOGE("Failed to open primary output");
4116 status = NO_INIT;
4117 }
Eric Laurente552edb2014-03-10 17:42:56 -07004118
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004119 // Silence ALOGV statements
4120 property_set("log.tag." LOG_TAG, "D");
4121
Eric Laurente552edb2014-03-10 17:42:56 -07004122 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004123 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004124}
4125
Eric Laurente0720872014-03-11 09:30:41 -07004126AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004127{
Eric Laurente552edb2014-03-10 17:42:56 -07004128 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004129 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004130 }
4131 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004132 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004133 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004134 mAvailableOutputDevices.clear();
4135 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004136 mOutputs.clear();
4137 mInputs.clear();
4138 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004139 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004140 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004141}
4142
Eric Laurente0720872014-03-11 09:30:41 -07004143status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004144{
Eric Laurent87ffa392015-05-22 10:32:38 -07004145 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004146}
4147
Eric Laurente552edb2014-03-10 17:42:56 -07004148// ---
4149
Eric Laurent98e38192018-02-15 18:31:53 -08004150void AudioPolicyManager::addOutput(audio_io_handle_t output,
4151 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004152{
Eric Laurent1c333e22014-05-20 10:48:17 -07004153 mOutputs.add(output, outputDesc);
Eric Laurent98e38192018-02-15 18:31:53 -08004154 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004155 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004156 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004157 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004158}
4159
François Gaffie53615e22015-03-19 09:24:12 +01004160void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4161{
4162 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004163 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004164}
4165
Eric Laurent98e38192018-02-15 18:31:53 -08004166void AudioPolicyManager::addInput(audio_io_handle_t input,
4167 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004168{
Eric Laurent1c333e22014-05-20 10:48:17 -07004169 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004171}
Eric Laurente552edb2014-03-10 17:42:56 -07004172
François Gaffie11d30102018-11-02 16:09:09 +01004173status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004174 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004175 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004176{
François Gaffie11d30102018-11-02 16:09:09 +01004177 audio_devices_t deviceType = device->type();
4178 const String8 &address = device->address();
Eric Laurentc75307b2015-03-17 15:29:32 -07004179 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004180
François Gaffie11d30102018-11-02 16:09:09 +01004181 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004182 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004183 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004184 }
Eric Laurente552edb2014-03-10 17:42:56 -07004185
Eric Laurent3b73df72014-03-11 09:06:29 -07004186 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004187 // first list already open outputs that can be routed to this device
4188 for (size_t i = 0; i < mOutputs.size(); i++) {
4189 desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01004190 if (!desc->isDuplicated() && desc->supportsDevice(device)) {
4191 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4192 mOutputs.keyAt(i), device->toString().c_str());
4193 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004194 }
4195 }
4196 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004197 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004198 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004199 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4200 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004201 if (profile->supportsDevice(device)) {
4202 profiles.add(profile);
4203 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4204 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004205 }
4206 }
4207 }
4208
Eric Laurent7b279bb2015-12-14 10:18:23 -08004209 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004210
Eric Laurente552edb2014-03-10 17:42:56 -07004211 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004212 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004213 return BAD_VALUE;
4214 }
4215
4216 // open outputs for matching profiles if needed. Direct outputs are also opened to
4217 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4218 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004219 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004220
4221 // nothing to do if one output is already opened for this profile
4222 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004223 for (j = 0; j < outputs.size(); j++) {
4224 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004225 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004226 // matching profile: save the sample rates, format and channel masks supported
4227 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004228 if (audio_device_is_digital(deviceType)) {
4229 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004230 }
Eric Laurente552edb2014-03-10 17:42:56 -07004231 break;
4232 }
4233 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004234 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004235 continue;
4236 }
4237
Eric Laurent3974e3b2017-12-07 17:58:43 -08004238 if (!profile->canOpenNewIo()) {
4239 ALOGW("Max Output number %u already opened for this profile %s",
4240 profile->maxOpenCount, profile->getTagName().c_str());
4241 continue;
4242 }
4243
Eric Laurent83efe1c2017-07-09 16:51:08 -07004244 ALOGV("opening output for device %08x with params %s profile %p name %s",
François Gaffie11d30102018-11-02 16:09:09 +01004245 deviceType, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004246 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004247 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004248 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004249 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004250
Eric Laurentfe231122017-11-17 17:48:06 -08004251 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004252 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004253 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004254 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004255 mpClientInterface->setParameters(output, String8(param));
4256 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004257 }
François Gaffie11d30102018-11-02 16:09:09 +01004258 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004259 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004260 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004261 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004262 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004263 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004264 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004265 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004266 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4267 profile->pickAudioProfile(
4268 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004269 config.offload_info.sample_rate = config.sample_rate;
4270 config.offload_info.channel_mask = config.channel_mask;
4271 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004272
François Gaffie11d30102018-11-02 16:09:09 +01004273 status_t status = desc->open(&config, DeviceVector(device),
4274 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004275 AUDIO_OUTPUT_FLAG_NONE, &output);
4276 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004277 output = AUDIO_IO_HANDLE_NONE;
4278 }
Eric Laurentd4692962014-05-05 18:13:44 -07004279 }
4280
Eric Laurentcf2c0212014-07-25 16:20:43 -07004281 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004282 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004283 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004284 sp<AudioPolicyMix> policyMix;
4285 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004286 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4287 address.string());
4288 }
François Gaffie036e1e92015-03-19 10:16:24 +01004289 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004290 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004291
Eric Laurent87ffa392015-05-22 10:32:38 -07004292 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4293 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004294 // no duplicated output for direct outputs and
4295 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004296 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004297
Eric Laurentd4692962014-05-05 18:13:44 -07004298 //TODO: configure audio effect output stage here
4299
4300 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004301 sp<SwAudioOutputDescriptor> dupOutputDesc =
4302 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4303 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4304 &duplicatedOutput);
4305 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004306 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004307 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004308 } else {
4309 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004310 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004311 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004312 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004313 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004314 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004315 }
Eric Laurente552edb2014-03-10 17:42:56 -07004316 }
4317 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004318 } else {
4319 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004320 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004321 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004322 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004323 profiles.removeAt(profile_index);
4324 profile_index--;
4325 } else {
4326 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004327 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004328 if (audio_device_is_digital(deviceType)) {
4329 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004330 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004331
François Gaffie11d30102018-11-02 16:09:09 +01004332 if (device_distinguishes_on_address(deviceType)) {
4333 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4334 device->toString().c_str());
4335 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4336 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004337 }
Eric Laurente552edb2014-03-10 17:42:56 -07004338 ALOGV("checkOutputsForDevice(): adding output %d", output);
4339 }
4340 }
4341
4342 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004343 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004344 return BAD_VALUE;
4345 }
Eric Laurentd4692962014-05-05 18:13:44 -07004346 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004347 // check if one opened output is not needed any more after disconnecting one device
4348 for (size_t i = 0; i < mOutputs.size(); i++) {
4349 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004350 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004351 // exact match on device
François Gaffie11d30102018-11-02 16:09:09 +01004352 if (device_distinguishes_on_address(deviceType) &&
4353 (desc->supportedDevices().types() == deviceType)) {
4354 outputs.add(mOutputs.keyAt(i));
4355 } else if (!(desc->supportedDevices().types() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004356 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4357 mOutputs.keyAt(i));
4358 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004359 }
Eric Laurente552edb2014-03-10 17:42:56 -07004360 }
4361 }
Eric Laurentd4692962014-05-05 18:13:44 -07004362 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004363 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004364 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4365 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004366 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004367 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004368 "clearing direct output profile %zu on module %s",
4369 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004370 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004371 }
4372 }
4373 }
4374 }
4375 return NO_ERROR;
4376}
4377
François Gaffie11d30102018-11-02 16:09:09 +01004378status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004379 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004380 SortedVector<audio_io_handle_t>& inputs)
Eric Laurentd4692962014-05-05 18:13:44 -07004381{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004382 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004383
François Gaffie11d30102018-11-02 16:09:09 +01004384 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004385 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004386 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004387 }
4388
Eric Laurentd4692962014-05-05 18:13:44 -07004389 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4390 // first list already open inputs that can be routed to this device
4391 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4392 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004393 if (desc->mProfile->supportsDeviceTypes(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -07004394 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4395 inputs.add(mInputs.keyAt(input_index));
4396 }
4397 }
4398
4399 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004400 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004401 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004402 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004403 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004404 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004405 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004406
François Gaffie11d30102018-11-02 16:09:09 +01004407 if (profile->supportsDevice(device)) {
4408 profiles.add(profile);
4409 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4410 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004411 }
4412 }
4413 }
4414
4415 if (profiles.isEmpty() && inputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004416 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004417 return BAD_VALUE;
4418 }
4419
4420 // open inputs for matching profiles if needed. Direct inputs are also opened to
4421 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4422 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4423
Eric Laurent1c333e22014-05-20 10:48:17 -07004424 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004425
Eric Laurentd4692962014-05-05 18:13:44 -07004426 // nothing to do if one input is already opened for this profile
4427 size_t input_index;
4428 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4429 desc = mInputs.valueAt(input_index);
4430 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004431 if (audio_device_is_digital(device->type())) {
4432 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004433 }
Eric Laurentd4692962014-05-05 18:13:44 -07004434 break;
4435 }
4436 }
4437 if (input_index != mInputs.size()) {
4438 continue;
4439 }
4440
Eric Laurent3974e3b2017-12-07 17:58:43 -08004441 if (!profile->canOpenNewIo()) {
4442 ALOGW("Max Input number %u already opened for this profile %s",
4443 profile->maxOpenCount, profile->getTagName().c_str());
4444 continue;
4445 }
4446
Eric Laurentfe231122017-11-17 17:48:06 -08004447 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004448 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004449 status_t status = desc->open(nullptr,
4450 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004451 AUDIO_SOURCE_MIC,
4452 AUDIO_INPUT_FLAG_NONE,
4453 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004454
Eric Laurentcf2c0212014-07-25 16:20:43 -07004455 if (status == NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01004456 const String8& address = device->address();
Eric Laurentd4692962014-05-05 18:13:44 -07004457 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004458 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004459 mpClientInterface->setParameters(input, String8(param));
4460 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004461 }
François Gaffie11d30102018-11-02 16:09:09 +01004462 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004463 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004464 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004465 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004466 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004467 }
4468
4469 if (input != 0) {
4470 addInput(input, desc);
4471 }
4472 } // endif input != 0
4473
Eric Laurentcf2c0212014-07-25 16:20:43 -07004474 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004475 ALOGW("%s could not open input for device %s", __func__,
4476 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004477 profiles.removeAt(profile_index);
4478 profile_index--;
4479 } else {
4480 inputs.add(input);
François Gaffie11d30102018-11-02 16:09:09 +01004481 if (audio_device_is_digital(device->type())) {
4482 device->importAudioPort(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004483 }
Eric Laurentd4692962014-05-05 18:13:44 -07004484 ALOGV("checkInputsForDevice(): adding input %d", input);
4485 }
4486 } // end scan profiles
4487
4488 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004489 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004490 return BAD_VALUE;
4491 }
4492 } else {
4493 // Disconnect
4494 // check if one opened input is not needed any more after disconnecting one device
4495 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4496 desc = mInputs.valueAt(input_index);
François Gaffie11d30102018-11-02 16:09:09 +01004497 if (!(desc->mProfile->supportsDeviceTypes(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004498 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4499 mInputs.keyAt(input_index));
4500 inputs.add(mInputs.keyAt(input_index));
4501 }
4502 }
4503 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004504 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004505 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004506 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004507 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004508 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
François Gaffie11d30102018-11-02 16:09:09 +01004509 if (profile->supportsDeviceTypes(device->type())) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004510 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4511 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004512 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004513 }
4514 }
4515 }
4516 } // end disconnect
4517
4518 return NO_ERROR;
4519}
4520
4521
Eric Laurente0720872014-03-11 09:30:41 -07004522void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004523{
4524 ALOGV("closeOutput(%d)", output);
4525
Eric Laurentc75307b2015-03-17 15:29:32 -07004526 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004527 if (outputDesc == NULL) {
4528 ALOGW("closeOutput() unknown output %d", output);
4529 return;
4530 }
François Gaffie036e1e92015-03-19 10:16:24 +01004531 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004532
Eric Laurente552edb2014-03-10 17:42:56 -07004533 // look for duplicated outputs connected to the output being removed.
4534 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004536 if (dupOutputDesc->isDuplicated() &&
4537 (dupOutputDesc->mOutput1 == outputDesc ||
4538 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent733ce942017-12-07 12:18:25 -08004539 sp<SwAudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004540 if (dupOutputDesc->mOutput1 == outputDesc) {
4541 outputDesc2 = dupOutputDesc->mOutput2;
4542 } else {
4543 outputDesc2 = dupOutputDesc->mOutput1;
4544 }
4545 // As all active tracks on duplicated output will be deleted,
4546 // and as they were also referenced on the other output, the reference
4547 // count for their stream type must be adjusted accordingly on
4548 // the other output.
Andy Hungaf036da2018-09-21 10:46:21 -07004549 const bool wasActive = outputDesc2->isActive();
4550 for (const auto &clientPair : dupOutputDesc->getActiveClients()) {
4551 outputDesc2->changeStreamActiveCount(clientPair.first, -clientPair.second);
Eric Laurente552edb2014-03-10 17:42:56 -07004552 }
Eric Laurent733ce942017-12-07 12:18:25 -08004553 // stop() will be a no op if the output is still active but is needed in case all
4554 // active streams refcounts where cleared above
4555 if (wasActive) {
4556 outputDesc2->stop();
4557 }
Eric Laurente552edb2014-03-10 17:42:56 -07004558 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4559 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4560
4561 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004562 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004563 }
4564 }
4565
Eric Laurent05b90f82014-08-27 15:32:29 -07004566 nextAudioPortGeneration();
4567
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004568 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004569 if (index >= 0) {
4570 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004571 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004572 mAudioPatches.removeItemsAt(index);
4573 mpClientInterface->onAudioPatchListUpdate();
4574 }
4575
Eric Laurentfe231122017-11-17 17:48:06 -08004576 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004577
François Gaffie53615e22015-03-19 09:24:12 +01004578 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004579 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10004580
4581 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4582 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01004583 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10004584 bool directOutputOpen = false;
4585 for (size_t i = 0; i < mOutputs.size(); i++) {
4586 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4587 directOutputOpen = true;
4588 break;
4589 }
4590 }
4591 if (!directOutputOpen) {
4592 ALOGV("no direct outputs open, reset MSD patch");
4593 setMsdPatch();
4594 }
4595 }
Eric Laurent05b90f82014-08-27 15:32:29 -07004596}
4597
4598void AudioPolicyManager::closeInput(audio_io_handle_t input)
4599{
4600 ALOGV("closeInput(%d)", input);
4601
4602 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4603 if (inputDesc == NULL) {
4604 ALOGW("closeInput() unknown input %d", input);
4605 return;
4606 }
4607
Eric Laurent6a94d692014-05-20 11:18:06 -07004608 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004609
François Gaffie11d30102018-11-02 16:09:09 +01004610 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004611 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004612 if (index >= 0) {
4613 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004614 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004615 mAudioPatches.removeItemsAt(index);
4616 mpClientInterface->onAudioPatchListUpdate();
4617 }
4618
Eric Laurentfe231122017-11-17 17:48:06 -08004619 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07004620 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004621
François Gaffie11d30102018-11-02 16:09:09 +01004622 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4623 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07004624 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4625 SoundTrigger::setCaptureState(false);
4626 }
Eric Laurente552edb2014-03-10 17:42:56 -07004627}
4628
François Gaffie11d30102018-11-02 16:09:09 +01004629SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4630 const DeviceVector &devices,
4631 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004632{
4633 SortedVector<audio_io_handle_t> outputs;
4634
François Gaffie11d30102018-11-02 16:09:09 +01004635 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07004636 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01004637 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004638 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01004639 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
4640 if ((devices.types() & openOutputs.valueAt(i)->supportedDevices().types()) ==
4641 devices.types()) {
4642 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004643 outputs.add(openOutputs.keyAt(i));
4644 }
4645 }
4646 return outputs;
4647}
4648
Mikhail Naganov37977152018-07-11 15:54:44 -07004649void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
4650{
4651 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
4652 // output is suspended before any tracks are moved to it
4653 checkA2dpSuspend();
4654 checkOutputForAllStrategies();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004655 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07004656 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00004657 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11004658 setMsdPatch();
4659 }
Mikhail Naganov37977152018-07-11 15:54:44 -07004660}
4661
Eric Laurente0720872014-03-11 09:30:41 -07004662void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004663{
François Gaffie11d30102018-11-02 16:09:09 +01004664 DeviceVector oldDevices = getDevicesForStrategy(strategy, true /*fromCache*/);
4665 DeviceVector newDevices = getDevicesForStrategy(strategy, false /*fromCache*/);
4666 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
4667 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07004668
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004669 // also take into account external policy-related changes: add all outputs which are
4670 // associated with policies in the "before" and "after" output vectors
4671 ALOGVV("checkOutputForStrategy(): policy related outputs");
4672 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004673 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004674 if (desc != 0 && desc->mPolicyMix != NULL) {
4675 srcOutputs.add(desc->mIoHandle);
4676 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4677 }
4678 }
4679 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004680 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004681 if (desc != 0 && desc->mPolicyMix != NULL) {
4682 dstOutputs.add(desc->mIoHandle);
4683 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4684 }
4685 }
4686
Mikhail Naganov9de8bd12018-07-23 16:41:31 -07004687 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004688 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
4689 // audio from invalidated tracks will be rendered when unmuting
4690 uint32_t maxLatency = 0;
4691 for (audio_io_handle_t srcOut : srcOutputs) {
4692 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4693 if (desc != 0 && maxLatency < desc->latency()) {
4694 maxLatency = desc->latency();
4695 }
4696 }
François Gaffie11d30102018-11-02 16:09:09 +01004697 ALOGV("%s: strategy %d, moving from output %s to output %s", __func__, strategy,
4698 (srcOutputs.isEmpty()? "none" : std::to_string(srcOutputs[0]).c_str()),
4699 (dstOutputs.isEmpty()? "none" : std::to_string(dstOutputs[0]).c_str()));
Eric Laurente552edb2014-03-10 17:42:56 -07004700 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004701 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07004702 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
4703 if (desc != 0 && isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004704 setStrategyMute(strategy, true, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004705 setStrategyMute(strategy, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
4706 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004707 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004708 sp<SourceClientDescriptor> source =
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004709 getSourceForStrategyOnOutput(srcOut, strategy);
Eric Laurentd60560a2015-04-10 11:31:20 -07004710 if (source != 0){
4711 connectAudioSource(source);
4712 }
Eric Laurente552edb2014-03-10 17:42:56 -07004713 }
4714
4715 // Move effects associated to this strategy from previous output to new output
4716 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004717 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004718 }
4719 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004720 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004721 if (getStrategy((audio_stream_type_t)i) == strategy) {
4722 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004723 }
4724 }
4725 }
4726}
4727
Eric Laurente0720872014-03-11 09:30:41 -07004728void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004729{
François Gaffie2110e042015-03-24 08:41:51 +01004730 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004731 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004732 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004733 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004734 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004735 checkOutputForStrategy(STRATEGY_SONIFICATION);
4736 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004737 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004738 checkOutputForStrategy(STRATEGY_MEDIA);
4739 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004740 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004741}
4742
Eric Laurente0720872014-03-11 09:30:41 -07004743void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004744{
François Gaffie53615e22015-03-19 09:24:12 +01004745 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08004746 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004747 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004748 return;
4749 }
4750
Eric Laurent3a4311c2014-03-17 12:00:47 -07004751 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004752 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4753 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4754 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004755
4756 // if suspended, restore A2DP output if:
4757 // ((SCO device is NOT connected) ||
4758 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4759 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004760 //
Eric Laurentf732e072016-08-03 19:30:28 -07004761 // if not suspended, suspend A2DP output if:
4762 // (SCO device is connected) &&
4763 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4764 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004765 //
4766 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004767 if (!isScoConnected ||
4768 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4769 AUDIO_POLICY_FORCE_BT_SCO) &&
4770 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4771 AUDIO_POLICY_FORCE_BT_SCO) &&
4772 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004773 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004774
4775 mpClientInterface->restoreOutput(a2dpOutput);
4776 mA2dpSuspended = false;
4777 }
4778 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004779 if (isScoConnected &&
4780 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4781 AUDIO_POLICY_FORCE_BT_SCO) ||
4782 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4783 AUDIO_POLICY_FORCE_BT_SCO) ||
4784 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004785 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004786
4787 mpClientInterface->suspendOutput(a2dpOutput);
4788 mA2dpSuspended = true;
4789 }
4790 }
4791}
4792
Eric Laurent97ac8712018-07-27 18:59:02 -07004793template <class IoDescriptor, class Filter>
4794sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4795 IoDescriptor& desc, Filter filter, bool& active, const DeviceVector& devices)
4796{
4797 auto activeClients = desc->clientsList(true /*activeOnly*/);
4798 auto activeClientsWithRoute =
4799 desc->clientsList(true /*activeOnly*/, filter, true /*preferredDevice*/);
4800 active = activeClients.size() > 0;
4801 if (active && activeClients.size() == activeClientsWithRoute.size()) {
4802 return devices.getDeviceFromId(activeClientsWithRoute[0]->preferredDeviceId());
4803 }
4804 return nullptr;
4805}
4806
4807template <class IoCollection, class Filter>
4808sp<DeviceDescriptor> AudioPolicyManager::findPreferredDevice(
4809 IoCollection& ioCollection, Filter filter, const DeviceVector& devices)
4810{
4811 sp<DeviceDescriptor> device;
4812 for (size_t i = 0; i < ioCollection.size(); i++) {
4813 auto desc = ioCollection.valueAt(i);
4814 bool active;
4815 sp<DeviceDescriptor> curDevice = findPreferredDevice(desc, filter, active, devices);
4816 if (active && curDevice == nullptr) {
4817 return nullptr;
4818 } else if (curDevice != nullptr) {
4819 device = curDevice;
4820 }
4821 }
4822 return device;
4823}
4824
François Gaffie11d30102018-11-02 16:09:09 +01004825DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
4826 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004827{
François Gaffie11d30102018-11-02 16:09:09 +01004828 DeviceVector devices;
4829
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004830 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (index >= 0) {
4832 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4833 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004834 ALOGV("%s device %s forced by patch %d", __func__,
4835 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
4836 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 }
4838 }
4839
Eric Laurent97ac8712018-07-27 18:59:02 -07004840 // Honor explicit routing requests only if no client using default routing is active on this
4841 // input: a specific app can not force routing for other apps by setting a preferred device.
4842 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01004843 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07004844 findPreferredDevice(outputDesc, STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01004845 if (device != nullptr) {
4846 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07004847 }
4848
Eric Laurente552edb2014-03-10 17:42:56 -07004849 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004850 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004851 // use device for strategy enforced audible
4852 // 2: we are in call or the strategy phone is active on the output:
4853 // use device for strategy phone
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004854 // 3: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004855 // use device for strategy sonification
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004856 // 4: the strategy for enforced audible is active but not enforced on the output:
4857 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004858 // 5: the strategy accessibility is active on the output:
4859 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004860 // 6: the strategy "respectful" sonification is active on the output:
4861 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004862 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004863 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004864 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004865 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004866 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004867 // use device for strategy t-t-s
Eric Laurent484e9272018-06-07 17:29:23 -07004868
4869 // FIXME: extend use of isStrategyActiveOnSameModule() to all strategies
4870 // with a refined rule considering mutually exclusive devices (using same backend)
4871 // as opposed to all streams on the same audio HAL module.
François Gaffiead3183e2015-03-18 16:55:35 +01004872 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004873 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffie11d30102018-11-02 16:09:09 +01004874 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004875 } else if (isInCall() ||
Eric Laurent484e9272018-06-07 17:29:23 -07004876 isStrategyActiveOnSameModule(outputDesc, STRATEGY_PHONE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004877 devices = getDevicesForStrategy(STRATEGY_PHONE, fromCache);
Yung Ti Su3e7eb5e2018-06-13 11:48:42 +08004878 } else if (isStrategyActiveOnSameModule(outputDesc, STRATEGY_SONIFICATION)) {
François Gaffie11d30102018-11-02 16:09:09 +01004879 devices = getDevicesForStrategy(STRATEGY_SONIFICATION, fromCache);
Jean-Michel Trivi178683b2017-08-30 18:07:06 -07004880 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
François Gaffie11d30102018-11-02 16:09:09 +01004881 devices = getDevicesForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004882 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
François Gaffie11d30102018-11-02 16:09:09 +01004883 devices = getDevicesForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004884 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
François Gaffie11d30102018-11-02 16:09:09 +01004885 devices = getDevicesForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004886 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
François Gaffie11d30102018-11-02 16:09:09 +01004887 devices = getDevicesForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004888 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
François Gaffie11d30102018-11-02 16:09:09 +01004889 devices = getDevicesForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004890 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
François Gaffie11d30102018-11-02 16:09:09 +01004891 devices = getDevicesForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004892 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
François Gaffie11d30102018-11-02 16:09:09 +01004893 devices = getDevicesForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004894 }
4895
François Gaffie11d30102018-11-02 16:09:09 +01004896 ALOGV("getNewOutputDevice() selected devices %s", devices.toString().c_str());
4897 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07004898}
4899
François Gaffie11d30102018-11-02 16:09:09 +01004900sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
4901 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004902{
François Gaffie11d30102018-11-02 16:09:09 +01004903 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07004904
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004905 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004906 if (index >= 0) {
4907 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4908 if (patchDesc->mUid != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01004909 ALOGV("getNewInputDevice() device %s forced by patch %d",
4910 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
4911 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 }
4913 }
4914
Eric Laurent97ac8712018-07-27 18:59:02 -07004915 // Honor explicit routing requests only if no client using default routing is active on this
4916 // input: a specific app can not force routing for other apps by setting a preferred device.
4917 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01004918 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
4919 if (device != nullptr) {
4920 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07004921 }
4922
Eric Laurentdc95a252018-04-12 12:46:56 -07004923 // If we are not in call and no client is active on this input, this methods returns
4924 // AUDIO_DEVICE_NONE, causing the patch on the input stream to be released.
Eric Laurent4eb58f12018-12-07 16:41:02 -08004925 audio_source_t source = inputDesc->source();
Eric Laurentdc95a252018-04-12 12:46:56 -07004926 if (source == AUDIO_SOURCE_DEFAULT && isInCall()) {
4927 source = AUDIO_SOURCE_VOICE_COMMUNICATION;
4928 }
4929 if (source != AUDIO_SOURCE_DEFAULT) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08004930 device = getDeviceAndMixForInputSource(source);
4931 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004932
Eric Laurente552edb2014-03-10 17:42:56 -07004933 return device;
4934}
4935
Eric Laurent794fde22016-03-11 09:50:45 -08004936bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4937 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004938 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004939}
4940
Eric Laurente0720872014-03-11 09:30:41 -07004941uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004942 return (uint32_t)getStrategy(stream);
4943}
4944
Eric Laurente0720872014-03-11 09:30:41 -07004945audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004946 // By checking the range of stream before calling getStrategy, we avoid
4947 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4948 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004949 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 return AUDIO_DEVICE_NONE;
4951 }
François Gaffie11d30102018-11-02 16:09:09 +01004952 DeviceVector activeDevices;
4953 DeviceVector devices;
Eric Laurent794fde22016-03-11 09:50:45 -08004954 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4955 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004956 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 }
Eric Laurent794fde22016-03-11 09:50:45 -08004958 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
François Gaffie11d30102018-11-02 16:09:09 +01004959 DeviceVector curDevices =
4960 getDevicesForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
4961 devices.merge(curDevices);
4962 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004963 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent794fde22016-03-11 09:50:45 -08004964 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
François Gaffie11d30102018-11-02 16:09:09 +01004965 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08004966 }
4967 }
Eric Laurente552edb2014-03-10 17:42:56 -07004968 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004969
Eric Laurentb0688d62018-08-14 15:49:18 -07004970 // Favor devices selected on active streams if any to report correct device in case of
4971 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01004972 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07004973 devices = activeDevices;
4974 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004975 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4976 and doesn't really need to.*/
François Gaffie11d30102018-11-02 16:09:09 +01004977 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
4978 if (!speakerSafeDevices.isEmpty()) {
4979 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
4980 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004981 }
François Gaffie11d30102018-11-02 16:09:09 +01004982 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004983}
4984
François Gaffie2110e042015-03-24 08:41:51 +01004985routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4986{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004987 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004988 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004989}
4990
Eric Laurent97ac8712018-07-27 18:59:02 -07004991routing_strategy AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004992 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004993 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004994 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004995 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004996 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004997 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004998 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004999 // usage to strategy mapping
Eric Laurent97ac8712018-07-27 18:59:02 -07005000 return mEngine->getStrategyForUsage(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005001}
5002
Eric Laurente0720872014-03-11 09:30:41 -07005003void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005004 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005005 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07005006 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
5007 updateDevicesAndOutputs();
5008 break;
5009 default:
5010 break;
5011 }
5012}
5013
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005014uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005015
5016 // skip beacon mute management if a dedicated TTS output is available
5017 if (mTtsOutputAvailable) {
5018 return 0;
5019 }
5020
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005021 switch(event) {
5022 case STARTING_OUTPUT:
5023 mBeaconMuteRefCount++;
5024 break;
5025 case STOPPING_OUTPUT:
5026 if (mBeaconMuteRefCount > 0) {
5027 mBeaconMuteRefCount--;
5028 }
5029 break;
5030 case STARTING_BEACON:
5031 mBeaconPlayingRefCount++;
5032 break;
5033 case STOPPING_BEACON:
5034 if (mBeaconPlayingRefCount > 0) {
5035 mBeaconPlayingRefCount--;
5036 }
5037 break;
5038 }
5039
5040 if (mBeaconMuteRefCount > 0) {
5041 // any playback causes beacon to be muted
5042 return setBeaconMute(true);
5043 } else {
5044 // no other playback: unmute when beacon starts playing, mute when it stops
5045 return setBeaconMute(mBeaconPlayingRefCount == 0);
5046 }
5047}
5048
5049uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5050 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5051 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5052 // keep track of muted state to avoid repeating mute/unmute operations
5053 if (mBeaconMuted != mute) {
5054 // mute/unmute AUDIO_STREAM_TTS on all outputs
5055 ALOGV("\t muting %d", mute);
5056 uint32_t maxLatency = 0;
5057 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005059 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07005060 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005061 0 /*delay*/, AUDIO_DEVICE_NONE);
5062 const uint32_t latency = desc->latency() * 2;
5063 if (latency > maxLatency) {
5064 maxLatency = latency;
5065 }
5066 }
5067 mBeaconMuted = mute;
5068 return maxLatency;
5069 }
5070 return 0;
5071}
5072
François Gaffie11d30102018-11-02 16:09:09 +01005073DeviceVector AudioPolicyManager::getDevicesForStrategy(routing_strategy strategy, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005074{
Eric Laurent97ac8712018-07-27 18:59:02 -07005075 // Honor explicit routing requests only if all active clients have a preferred route in which
5076 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005077 sp<DeviceDescriptor> device = findPreferredDevice(mOutputs, strategy, mAvailableOutputDevices);
5078 if (device != nullptr) {
5079 return DeviceVector(device);
Paul McLeanaa981192015-03-21 09:55:15 -07005080 }
5081
Eric Laurente552edb2014-03-10 17:42:56 -07005082 if (fromCache) {
François Gaffie11d30102018-11-02 16:09:09 +01005083 ALOGVV("%s from cache strategy %d, device %s", __func__, strategy,
5084 mDevicesForStrategy[strategy].toString().c_str());
5085 return mDevicesForStrategy[strategy];
Eric Laurente552edb2014-03-10 17:42:56 -07005086 }
François Gaffie11d30102018-11-02 16:09:09 +01005087 return mAvailableOutputDevices.getDevicesFromTypeMask(mEngine->getDeviceForStrategy(strategy));
Eric Laurente552edb2014-03-10 17:42:56 -07005088}
5089
Eric Laurente0720872014-03-11 09:30:41 -07005090void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005091{
5092 for (int i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005093 mDevicesForStrategy[i] = getDevicesForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07005094 }
5095 mPreviousOutputs = mOutputs;
5096}
5097
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005098uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005099 audio_devices_t prevDeviceType,
Eric Laurente552edb2014-03-10 17:42:56 -07005100 uint32_t delayMs)
5101{
5102 // mute/unmute strategies using an incompatible device combination
5103 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5104 // if unmuting, unmute only after the specified delay
5105 if (outputDesc->isDuplicated()) {
5106 return 0;
5107 }
5108
5109 uint32_t muteWaitMs = 0;
François Gaffie11d30102018-11-02 16:09:09 +01005110 audio_devices_t deviceType = outputDesc->devices().types();
5111 bool shouldMute = outputDesc->isActive() && (popcount(deviceType) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005112
5113 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005114 audio_devices_t curDeviceType =
5115 getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
5116 curDeviceType = curDeviceType & outputDesc->supportedDevices().types();
5117 bool mute = shouldMute && (curDeviceType & deviceType) && (curDeviceType != deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005118 bool doMute = false;
5119
5120 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
5121 doMute = true;
5122 outputDesc->mStrategyMutedByDevice[i] = true;
5123 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
5124 doMute = true;
5125 outputDesc->mStrategyMutedByDevice[i] = false;
5126 }
Eric Laurent99401132014-05-07 19:48:15 -07005127 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005128 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005129 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005130 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005131 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005132 continue;
5133 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07005134 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
François Gaffie11d30102018-11-02 16:09:09 +01005135 mute ? "muting" : "unmuting", i, curDeviceType);
Eric Laurentc75307b2015-03-17 15:29:32 -07005136 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01005137 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07005138 if (mute) {
5139 // FIXME: should not need to double latency if volume could be applied
5140 // immediately by the audioflinger mixer. We must account for the delay
5141 // between now and the next time the audioflinger thread for this output
5142 // will process a buffer (which corresponds to one buffer size,
5143 // usually 1/2 or 1/4 of the latency).
5144 if (muteWaitMs < desc->latency() * 2) {
5145 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005146 }
5147 }
5148 }
5149 }
5150 }
5151 }
5152
Eric Laurent99401132014-05-07 19:48:15 -07005153 // temporary mute output if device selection changes to avoid volume bursts due to
5154 // different per device volumes
François Gaffie11d30102018-11-02 16:09:09 +01005155 if (outputDesc->isActive() && (deviceType != prevDeviceType)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005156 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5157 // temporary mute duration is conservatively set to 4 times the reported latency
5158 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5159 if (muteWaitMs < tempMuteWaitMs) {
5160 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005161 }
Eric Laurentdc462862016-07-19 12:29:53 -07005162
Eric Laurent99401132014-05-07 19:48:15 -07005163 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005164 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005165 // make sure that we do not start the temporary mute period too early in case of
5166 // delayed device change
5167 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005168 setStrategyMute((routing_strategy)i, false, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005169 delayMs + tempMuteDurationMs, deviceType);
Eric Laurent99401132014-05-07 19:48:15 -07005170 }
5171 }
5172 }
5173
Eric Laurente552edb2014-03-10 17:42:56 -07005174 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5175 if (muteWaitMs > delayMs) {
5176 muteWaitMs -= delayMs;
5177 usleep(muteWaitMs * 1000);
5178 return muteWaitMs;
5179 }
5180 return 0;
5181}
5182
François Gaffie11d30102018-11-02 16:09:09 +01005183uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5184 const DeviceVector &devices,
5185 bool force,
5186 int delayMs,
5187 audio_patch_handle_t *patchHandle,
5188 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005189{
François Gaffie11d30102018-11-02 16:09:09 +01005190 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005191 uint32_t muteWaitMs;
5192
5193 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005194 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5195 nullptr /* patchHandle */, requiresMuteCheck);
5196 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5197 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005198 return muteWaitMs;
5199 }
Eric Laurente552edb2014-03-10 17:42:56 -07005200
5201 // filter devices according to output selected
François Gaffie11d30102018-11-02 16:09:09 +01005202 DeviceVector filteredDevices = devices.filter(outputDesc->supportedDevices().types());
Eric Laurente552edb2014-03-10 17:42:56 -07005203
François Gaffie11d30102018-11-02 16:09:09 +01005204 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5205 // output profile
5206 if (!devices.isEmpty() && filteredDevices.isEmpty()) {
5207 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5208 return 0;
5209 }
Eric Laurente552edb2014-03-10 17:42:56 -07005210
François Gaffie11d30102018-11-02 16:09:09 +01005211 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005212
François Gaffie11d30102018-11-02 16:09:09 +01005213 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5214
5215 if (!filteredDevices.isEmpty()) {
5216 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005217 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005218
5219 // if the outputs are not materially active, there is no need to mute.
5220 if (requiresMuteCheck) {
François Gaffie11d30102018-11-02 16:09:09 +01005221 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices.types(), delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005222 } else {
5223 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5224 muteWaitMs = 0;
5225 }
Eric Laurente552edb2014-03-10 17:42:56 -07005226
5227 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005228 // the requested device is AUDIO_DEVICE_NONE
5229 // OR the requested device is the same as current device
5230 // AND force is not specified
5231 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005232 // Doing this check here allows the caller to call setOutputDevices() without conditions
5233 if ((!filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5234 !force && outputDesc->getPatchHandle() != 0) {
5235 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5236 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005237 return muteWaitMs;
5238 }
5239
François Gaffie11d30102018-11-02 16:09:09 +01005240 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005241
Eric Laurente552edb2014-03-10 17:42:56 -07005242 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005243 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005244 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005245 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005246 PatchBuilder patchBuilder;
5247 patchBuilder.addSource(outputDesc);
5248 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5249 for (const auto &filteredDevice : filteredDevices) {
5250 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005251 }
5252
François Gaffie11d30102018-11-02 16:09:09 +01005253 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005254 }
Eric Laurente552edb2014-03-10 17:42:56 -07005255
5256 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005257 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005258
5259 return muteWaitMs;
5260}
5261
Eric Laurentc75307b2015-03-17 15:29:32 -07005262status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 int delayMs,
5264 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005265{
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 ssize_t index;
5267 if (patchHandle) {
5268 index = mAudioPatches.indexOfKey(*patchHandle);
5269 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005270 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 }
5272 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005273 return INVALID_OPERATION;
5274 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5276 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005277 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005278 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 removeAudioPatch(patchDesc->mHandle);
5280 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005281 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005282 return status;
5283}
5284
5285status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005286 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 bool force,
5288 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005289{
5290 status_t status = NO_ERROR;
5291
Eric Laurent1f2f2232014-06-02 12:01:23 -07005292 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005293 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5294 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005295
François Gaffie11d30102018-11-02 16:09:09 +01005296 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005297 PatchBuilder patchBuilder;
5298 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005299 // AUDIO_SOURCE_HOTWORD is for internal use only:
5300 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005301 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5302 auto result = usecase;
5303 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5304 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5305 }
5306 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005308 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005309 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005310 }
5311 }
5312 return status;
5313}
5314
Eric Laurent6a94d692014-05-20 11:18:06 -07005315status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5316 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005317{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005318 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 ssize_t index;
5320 if (patchHandle) {
5321 index = mAudioPatches.indexOfKey(*patchHandle);
5322 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005323 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005324 }
5325 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005326 return INVALID_OPERATION;
5327 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5329 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005330 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005331 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 removeAudioPatch(patchDesc->mHandle);
5333 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005334 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005335 return status;
5336}
5337
François Gaffie11d30102018-11-02 16:09:09 +01005338sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005339 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005340 audio_format_t& format,
5341 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005342 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005343{
5344 // Choose an input profile based on the requested capture parameters: select the first available
5345 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005346 //
5347 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5348 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005349
Glenn Kasten730b9262018-03-29 15:01:26 -07005350 sp<IOProfile> firstInexact;
5351 uint32_t updatedSamplingRate = 0;
5352 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5353 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005354 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005355 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005356 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005357 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005358 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005359 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005360 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005361 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005362 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005363 &channelMask /*updatedChannelMask*/,
5364 // FIXME ugly cast
5365 (audio_output_flags_t) flags,
5366 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005367 return profile;
5368 }
François Gaffie11d30102018-11-02 16:09:09 +01005369 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005370 samplingRate,
5371 &updatedSamplingRate,
5372 format,
5373 &updatedFormat,
5374 channelMask,
5375 &updatedChannelMask,
5376 // FIXME ugly cast
5377 (audio_output_flags_t) flags,
5378 false /*exactMatchRequiredForInputFlags*/)) {
5379 firstInexact = profile;
5380 }
5381
Eric Laurente552edb2014-03-10 17:42:56 -07005382 }
5383 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005384 if (firstInexact != nullptr) {
5385 samplingRate = updatedSamplingRate;
5386 format = updatedFormat;
5387 channelMask = updatedChannelMask;
5388 return firstInexact;
5389 }
Eric Laurente552edb2014-03-10 17:42:56 -07005390 return NULL;
5391}
5392
François Gaffie11d30102018-11-02 16:09:09 +01005393sp<DeviceDescriptor> AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
5394 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005395{
Eric Laurent97ac8712018-07-27 18:59:02 -07005396 // Honor explicit routing requests only if all active clients have a preferred route in which
5397 // case the last active client route is used
François Gaffie11d30102018-11-02 16:09:09 +01005398 sp<DeviceDescriptor> device =
Eric Laurent97ac8712018-07-27 18:59:02 -07005399 findPreferredDevice(mInputs, inputSource, mAvailableInputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005400 if (device != nullptr) {
5401 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005402 }
5403
François Gaffie11d30102018-11-02 16:09:09 +01005404 sp<DeviceDescriptor> selectedDeviceFromMix =
5405 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, mAvailableInputDevices,
5406 policyMix);
5407 return (selectedDeviceFromMix != nullptr) ?
5408 selectedDeviceFromMix : getDeviceForInputSource(inputSource);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005409}
5410
François Gaffie11d30102018-11-02 16:09:09 +01005411sp<DeviceDescriptor> AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005412{
François Gaffie11d30102018-11-02 16:09:09 +01005413 audio_devices_t device = mEngine->getDeviceForInputSource(inputSource);
5414 return mAvailableInputDevices.getDevice(device);
Eric Laurente552edb2014-03-10 17:42:56 -07005415}
5416
Eric Laurente0720872014-03-11 09:30:41 -07005417float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005418 int index,
5419 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005420{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005421 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005422
5423 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5424 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5425 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5426 // the ringtone volume
5427 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5428 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5429 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5430 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5431 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5432 }
5433
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005434 // in-call: always cap volume by voice volume + some low headroom
5435 if ((stream != AUDIO_STREAM_VOICE_CALL) &&
Eric Laurent7731b5a2018-04-06 15:47:22 -07005436 (isInCall() || mOutputs.isStreamActiveLocally(AUDIO_STREAM_VOICE_CALL))) {
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005437 switch (stream) {
5438 case AUDIO_STREAM_SYSTEM:
5439 case AUDIO_STREAM_RING:
5440 case AUDIO_STREAM_MUSIC:
5441 case AUDIO_STREAM_ALARM:
5442 case AUDIO_STREAM_NOTIFICATION:
5443 case AUDIO_STREAM_ENFORCED_AUDIBLE:
5444 case AUDIO_STREAM_DTMF:
5445 case AUDIO_STREAM_ACCESSIBILITY: {
Eric Laurent7731b5a2018-04-06 15:47:22 -07005446 int voiceVolumeIndex =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005447 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_VOICE_CALL, device);
Eric Laurent7731b5a2018-04-06 15:47:22 -07005448 const float maxVoiceVolDb =
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005449 computeVolume(AUDIO_STREAM_VOICE_CALL, voiceVolumeIndex, device)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005450 + IN_CALL_EARPIECE_HEADROOM_DB;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005451 if (volumeDB > maxVoiceVolDb) {
5452 ALOGV("computeVolume() stream %d at vol=%f overriden by stream %d at vol=%f",
5453 stream, volumeDB, AUDIO_STREAM_VOICE_CALL, maxVoiceVolDb);
5454 volumeDB = maxVoiceVolDb;
5455 }
5456 } break;
5457 default:
5458 break;
5459 }
5460 }
5461
Eric Laurente552edb2014-03-10 17:42:56 -07005462 // if a headset is connected, apply the following rules to ring tones and notifications
5463 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005464 // - always attenuate notifications volume by 6dB
5465 // - attenuate ring tones volume by 6dB unless music is not playing and
5466 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005467 // - if music is playing, always limit the volume to current music volume,
5468 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005469 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005470 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5471 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5472 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005473 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
Jakub Pawlowski00f928c2018-03-22 13:20:03 -07005474 AUDIO_DEVICE_OUT_USB_HEADSET |
5475 AUDIO_DEVICE_OUT_HEARING_AID)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005476 ((stream_strategy == STRATEGY_SONIFICATION)
5477 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005478 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005479 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005480 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005481 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005482 // when the phone is ringing we must consider that music could have been paused just before
5483 // by the music application and behave as if music was active if the last music track was
5484 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005485 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005486 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005487 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005488 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005489 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005490 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5491 musicDevice),
5492 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005493 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5494 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005495 if (volumeDB > minVolDB) {
5496 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005497 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005498 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005499 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5500 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5501 // on A2DP, also ensure notification volume is not too low compared to media when
5502 // intended to be played
5503 if ((volumeDB > -96.0f) &&
5504 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5505 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5506 stream, device,
5507 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5508 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5509 }
5510 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005511 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5512 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005513 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005514 }
5515 }
5516
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005517 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005518}
5519
Eric Laurent3839bc02018-07-10 18:33:34 -07005520int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5521 audio_stream_type_t srcStream,
5522 audio_stream_type_t dstStream)
5523{
5524 if (srcStream == dstStream) {
5525 return srcIndex;
5526 }
5527 float minSrc = (float)mVolumeCurves->getVolumeIndexMin(srcStream);
5528 float maxSrc = (float)mVolumeCurves->getVolumeIndexMax(srcStream);
5529 float minDst = (float)mVolumeCurves->getVolumeIndexMin(dstStream);
5530 float maxDst = (float)mVolumeCurves->getVolumeIndexMax(dstStream);
5531
5532 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5533}
5534
Eric Laurente0720872014-03-11 09:30:41 -07005535status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005536 int index,
5537 const sp<AudioOutputDescriptor>& outputDesc,
5538 audio_devices_t device,
5539 int delayMs,
5540 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005541{
Eric Laurente552edb2014-03-10 17:42:56 -07005542 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005543 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005544 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005546 return NO_ERROR;
5547 }
François Gaffie2110e042015-03-24 08:41:51 +01005548 audio_policy_forced_cfg_t forceUseForComm =
5549 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005550 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005551 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5552 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005553 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005554 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005555 return INVALID_OPERATION;
5556 }
5557
Eric Laurentc75307b2015-03-17 15:29:32 -07005558 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005559 device = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005561
Eric Laurentffbc80f2015-03-18 18:30:19 -07005562 float volumeDb = computeVolume(stream, index, device);
HW Leeda7581e2018-05-22 18:31:34 +08005563 if (outputDesc->isFixedVolume(device) ||
5564 // Force VoIP volume to max for bluetooth SCO
5565 ((stream == AUDIO_STREAM_VOICE_CALL || stream == AUDIO_STREAM_BLUETOOTH_SCO) &&
5566 (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005567 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005568 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005569
Eric Laurentffbc80f2015-03-18 18:30:19 -07005570 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005571
Eric Laurent3b73df72014-03-11 09:06:29 -07005572 if (stream == AUDIO_STREAM_VOICE_CALL ||
5573 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005574 float voiceVolume;
5575 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005576 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005577 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005578 } else {
5579 voiceVolume = 1.0;
5580 }
5581
Eric Laurent18fba842016-03-31 14:41:26 -07005582 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005583 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5584 mLastVoiceVolume = voiceVolume;
5585 }
5586 }
5587
5588 return NO_ERROR;
5589}
5590
Eric Laurentc75307b2015-03-17 15:29:32 -07005591void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5592 audio_devices_t device,
5593 int delayMs,
5594 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005595{
Eric Laurentc75307b2015-03-17 15:29:32 -07005596 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005597
Eric Laurent794fde22016-03-11 09:50:45 -08005598 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005599 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005600 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005602 device,
5603 delayMs,
5604 force);
5605 }
5606}
5607
Eric Laurente0720872014-03-11 09:30:41 -07005608void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005609 bool on,
5610 const sp<AudioOutputDescriptor>& outputDesc,
5611 int delayMs,
5612 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005613{
Eric Laurent72249d52015-06-08 11:12:15 -07005614 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5615 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005616 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005617 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005618 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005619 }
5620 }
5621}
5622
Eric Laurente0720872014-03-11 09:30:41 -07005623void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005624 bool on,
5625 const sp<AudioOutputDescriptor>& outputDesc,
5626 int delayMs,
5627 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005628{
Eric Laurente552edb2014-03-10 17:42:56 -07005629 if (device == AUDIO_DEVICE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005630 device = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07005631 }
5632
Eric Laurentc75307b2015-03-17 15:29:32 -07005633 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5634 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005635
5636 if (on) {
5637 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005638 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005639 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005640 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005641 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005642 }
5643 }
5644 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5645 outputDesc->mMuteCount[stream]++;
5646 } else {
5647 if (outputDesc->mMuteCount[stream] == 0) {
5648 ALOGV("setStreamMute() unmuting non muted stream!");
5649 return;
5650 }
5651 if (--outputDesc->mMuteCount[stream] == 0) {
5652 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005653 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005654 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005655 device,
5656 delayMs);
5657 }
5658 }
5659}
5660
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005661audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5662{
5663 // flags to stream type mapping
5664 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5665 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5666 }
5667 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5668 return AUDIO_STREAM_BLUETOOTH_SCO;
5669 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005670 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5671 return AUDIO_STREAM_TTS;
5672 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005673
Ari Hausman-Cohen5c00d012018-06-26 17:09:11 -07005674 return audio_usage_to_stream_type(attr->usage);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005675}
Eric Laurente83b55d2014-11-14 10:06:21 -08005676
François Gaffie53615e22015-03-19 09:24:12 +01005677bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5678{
Eric Laurente83b55d2014-11-14 10:06:21 -08005679 // has flags that map to a strategy?
5680 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5681 return true;
5682 }
5683
5684 // has known usage?
5685 switch (paa->usage) {
5686 case AUDIO_USAGE_UNKNOWN:
5687 case AUDIO_USAGE_MEDIA:
5688 case AUDIO_USAGE_VOICE_COMMUNICATION:
5689 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5690 case AUDIO_USAGE_ALARM:
5691 case AUDIO_USAGE_NOTIFICATION:
5692 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5693 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5694 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5695 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5696 case AUDIO_USAGE_NOTIFICATION_EVENT:
5697 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5698 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5699 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5700 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005701 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005702 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005703 break;
5704 default:
5705 return false;
5706 }
5707 return true;
5708}
5709
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005710bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005711 routing_strategy strategy, uint32_t inPastMs,
5712 nsecs_t sysTime) const
5713{
5714 if ((sysTime == 0) && (inPastMs != 0)) {
5715 sysTime = systemTime();
5716 }
Eric Laurent794fde22016-03-11 09:50:45 -08005717 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005718 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurent97ac8712018-07-27 18:59:02 -07005719 (STRATEGY_NONE == strategy)) &&
François Gaffiead3183e2015-03-18 16:55:35 +01005720 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5721 return true;
5722 }
5723 }
5724 return false;
5725}
5726
François Gaffie11d30102018-11-02 16:09:09 +01005727bool AudioPolicyManager::isStrategyActiveOnSameModule(const sp<SwAudioOutputDescriptor>& outputDesc,
5728 routing_strategy strategy, uint32_t inPastMs,
5729 nsecs_t sysTime) const
Eric Laurent484e9272018-06-07 17:29:23 -07005730{
5731 for (size_t i = 0; i < mOutputs.size(); i++) {
5732 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5733 if (outputDesc->sharesHwModuleWith(desc)
5734 && isStrategyActive(desc, strategy, inPastMs, sysTime)) {
5735 return true;
5736 }
5737 }
5738 return false;
5739}
5740
François Gaffie2110e042015-03-24 08:41:51 +01005741audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5742{
5743 return mEngine->getForceUse(usage);
5744}
5745
5746bool AudioPolicyManager::isInCall()
5747{
5748 return isStateInCall(mEngine->getPhoneState());
5749}
5750
5751bool AudioPolicyManager::isStateInCall(int state)
5752{
5753 return is_state_in_call(state);
5754}
5755
Eric Laurentd60560a2015-04-10 11:31:20 -07005756void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5757{
5758 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005759 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5760 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5761 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5762 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005763 }
5764 }
5765
5766 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5767 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5768 bool release = false;
5769 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5770 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5771 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5772 source->ext.device.type == deviceDesc->type()) {
5773 release = true;
5774 }
5775 }
5776 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5777 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5778 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5779 sink->ext.device.type == deviceDesc->type()) {
5780 release = true;
5781 }
5782 }
5783 if (release) {
5784 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5785 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5786 }
5787 }
5788}
5789
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005790void AudioPolicyManager::modifySurroundFormats(
5791 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005792 std::unordered_set<audio_format_t> enforcedSurround(
5793 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005794 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
5795 for (const auto& pair : mConfig.getSurroundFormats()) {
5796 allSurround.insert(pair.first);
5797 for (const auto& subformat : pair.second) allSurround.insert(subformat);
5798 }
Phil Burk09bc4612016-02-24 15:58:15 -08005799
5800 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5801 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005802 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 // This is the resulting set of formats depending on the surround mode:
5804 // 'all surround' = allSurround
5805 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
5806 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
5807 // 'manual surround' = mManualSurroundFormats
5808 // AUTO: formats v 'enforced surround'
5809 // ALWAYS: formats v 'all surround' v 'enforced surround'
5810 // NEVER: formats ^ 'non-surround'
5811 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08005812
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005813 std::unordered_set<audio_format_t> formatSet;
5814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
5815 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005816 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005817 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005818 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005819 formatSet.insert(*formatIter);
5820 }
5821 }
5822 } else {
5823 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
5824 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005825 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005826
jiabin81772902018-04-02 17:52:27 -07005827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005828 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005829 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
5830 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
5831 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08005832 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005833 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
5834 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5835 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07005836 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005837 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08005838 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005839 for (const auto& format : formatSet) {
5840 formatsPtr->push(format);
5841 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005842}
5843
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005844void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005845 ChannelsVector &channelMasks = *channelMasksPtr;
5846 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5847 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5848
5849 // If NEVER, then remove support for channelMasks > stereo.
5850 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5851 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5852 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5853 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5854 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5855 channelMasks.removeAt(maskIndex);
5856 } else {
5857 maskIndex++;
5858 }
5859 }
jiabin81772902018-04-02 17:52:27 -07005860 // If ALWAYS or MANUAL, then make sure we at least support 5.1
5861 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
5862 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005863 bool supports5dot1 = false;
5864 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005865 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005866 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5867 supports5dot1 = true;
5868 break;
5869 }
5870 }
5871 // If not then add 5.1 support.
5872 if (!supports5dot1) {
5873 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005874 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07005875 }
Phil Burk09bc4612016-02-24 15:58:15 -08005876 }
5877}
5878
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005879void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07005880 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005881 AudioProfileVector &profiles)
5882{
5883 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005884 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07005885
François Gaffie112b0af2015-11-19 16:13:25 +01005886 // Format MUST be checked first to update the list of AudioProfile
5887 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005888 reply = mpClientInterface->getParameters(
5889 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07005890 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005891 AudioParameter repliedParameters(reply);
5892 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005893 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005894 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5895 return;
5896 }
Phil Burk09bc4612016-02-24 15:58:15 -08005897 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005898 if (device == AUDIO_DEVICE_OUT_HDMI
5899 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005900 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005901 }
Phil Burk09bc4612016-02-24 15:58:15 -08005902 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005903 }
François Gaffie112b0af2015-11-19 16:13:25 +01005904
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005905 for (audio_format_t format : profiles.getSupportedFormats()) {
Eric Laurent20eb3a42016-01-26 18:39:17 -08005906 ChannelsVector channelMasks;
5907 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005908 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005909 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005910
5911 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005912 reply = mpClientInterface->getParameters(
5913 ioHandle,
5914 requestedParameters.toString() + ";" +
5915 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005916 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005917 AudioParameter repliedParameters(reply);
5918 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005919 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005920 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005921 }
5922 }
5923 if (profiles.hasDynamicChannelsFor(format)) {
5924 reply = mpClientInterface->getParameters(ioHandle,
5925 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005926 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005927 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005928 AudioParameter repliedParameters(reply);
5929 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005930 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005931 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08005932 if (device == AUDIO_DEVICE_OUT_HDMI
5933 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08005934 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07005935 }
François Gaffie112b0af2015-11-19 16:13:25 +01005936 }
5937 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005938 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005939 }
5940}
Eric Laurentd60560a2015-04-10 11:31:20 -07005941
Mikhail Naganovdc769682018-05-04 15:34:08 -07005942status_t AudioPolicyManager::installPatch(const char *caller,
5943 audio_patch_handle_t *patchHandle,
5944 AudioIODescriptorInterface *ioDescriptor,
5945 const struct audio_patch *patch,
5946 int delayMs)
5947{
5948 ssize_t index = mAudioPatches.indexOfKey(
5949 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
5950 *patchHandle : ioDescriptor->getPatchHandle());
5951 sp<AudioPatch> patchDesc;
5952 status_t status = installPatch(
5953 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
5954 if (status == NO_ERROR) {
5955 ioDescriptor->setPatchHandle(patchDesc->mHandle);
5956 }
5957 return status;
5958}
5959
5960status_t AudioPolicyManager::installPatch(const char *caller,
5961 ssize_t index,
5962 audio_patch_handle_t *patchHandle,
5963 const struct audio_patch *patch,
5964 int delayMs,
5965 uid_t uid,
5966 sp<AudioPatch> *patchDescPtr)
5967{
5968 sp<AudioPatch> patchDesc;
5969 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5970 if (index >= 0) {
5971 patchDesc = mAudioPatches.valueAt(index);
5972 afPatchHandle = patchDesc->mAfPatchHandle;
5973 }
5974
5975 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
5976 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
5977 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
5978 if (status == NO_ERROR) {
5979 if (index < 0) {
5980 patchDesc = new AudioPatch(patch, uid);
5981 addAudioPatch(patchDesc->mHandle, patchDesc);
5982 } else {
5983 patchDesc->mPatch = *patch;
5984 }
5985 patchDesc->mAfPatchHandle = afPatchHandle;
5986 if (patchHandle) {
5987 *patchHandle = patchDesc->mHandle;
5988 }
5989 nextAudioPortGeneration();
5990 mpClientInterface->onAudioPatchListUpdate();
5991 }
5992 if (patchDescPtr) *patchDescPtr = patchDesc;
5993 return status;
5994}
5995
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08005996} // namespace android