blob: ad4ec284260b447a789319d2e36746dc2e04062d [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"
Cheney Nie5985452019-02-24 01:39:15 +080036#define AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME \
37 "audio_policy_configuration_bluetooth_legacy_hal.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010038
Eric Laurent16c66dd2019-05-01 17:54:10 -070039#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070040#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080042#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080043#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110044#include <vector>
Glenn Kasten76a13442020-07-01 12:10:59 -070045#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070046#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070047#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070049#include <private/android_filesystem_config.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070050#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganovedc0ae12020-04-14 14:47:01 -070052#include <system/audio_config.h>
Eric Laurentd4692962014-05-05 18:13:44 -070053#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010054#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010056#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070057
Eric Laurent3b73df72014-03-11 09:06:29 -070058namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurentdc462862016-07-19 12:29:53 -070060//FIXME: workaround for truncated touch sounds
61// to be removed when the problem is handled by system UI
62#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070063
64// Largest difference in dB on earpiece in call between the voice volume and another
65// media / notification / system volume.
66constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
67
Mikhail Naganov15be9d22017-11-08 14:18:13 +110068// Compressed formats for MSD module, ordered from most preferred to least preferred.
69static const std::vector<audio_format_t> compressedFormatsOrder = {{
70 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
71 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
72// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
73static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
74 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
75 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
76 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
77
jiabin4562b3b2019-07-29 10:13:34 -070078template <typename T>
79bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
80{
81 if (left.size() != right.size()) {
82 return false;
83 }
84 for (size_t index = 0; index < right.size(); index++) {
85 if (left[index] != right[index]) {
86 return false;
87 }
88 }
89 return true;
90}
91
92template <typename T>
93bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
94{
95 return !(left == right);
96}
97
Eric Laurente552edb2014-03-10 17:42:56 -070098// ----------------------------------------------------------------------------
99// AudioPolicyInterface implementation
100// ----------------------------------------------------------------------------
101
Eric Laurente0720872014-03-11 09:30:41 -0700102status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800103 audio_policy_dev_state_t state,
104 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800105 const char *device_name,
106 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700107{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800108 status_t status = setDeviceConnectionStateInt(device, state, device_address,
109 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800110 nextAudioPortGeneration();
111 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800112}
113
François Gaffie11d30102018-11-02 16:09:09 +0100114void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
115 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200116{
jiabin6713a382019-09-12 16:29:15 -0700117 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200118 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovbb3b1602019-07-08 15:28:43 -0700119 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100120 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200121 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
122}
123
François Gaffie11d30102018-11-02 16:09:09 +0100124status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800125 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800126 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800127 const char *device_name,
128 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800129{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800130 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
131 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700132
133 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100134 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700135
François Gaffie11d30102018-11-02 16:09:09 +0100136 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800137 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100138 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganova30ec142020-03-24 09:32:34 -0700139 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
140}
Paul McLeane743a472015-01-28 11:07:31 -0800141
Mikhail Naganova30ec142020-03-24 09:32:34 -0700142status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
143 audio_policy_dev_state_t state)
144{
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // handle output devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700146 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700147 SortedVector <audio_io_handle_t> outputs;
148
François Gaffie11d30102018-11-02 16:09:09 +0100149 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150
Eric Laurente552edb2014-03-10 17:42:56 -0700151 // save a copy of the opened output descriptors before any output is opened or closed
152 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
153 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700154 switch (state)
155 {
156 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800157 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700158 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100159 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700160 return INVALID_OPERATION;
161 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800162 ALOGV("%s() connecting device %s format %x",
Mikhail Naganova30ec142020-03-24 09:32:34 -0700163 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700164
Eric Laurente552edb2014-03-10 17:42:56 -0700165 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200166 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700167 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700168 }
169
François Gaffie44481e72016-04-20 07:49:57 +0200170 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
171 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100172 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200173
François Gaffie11d30102018-11-02 16:09:09 +0100174 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
175 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200176
Francois Gaffie716e1432019-01-14 16:58:59 +0100177 mHwModules.cleanUpForDevice(device);
178
François Gaffie11d30102018-11-02 16:09:09 +0100179 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700180 return INVALID_OPERATION;
181 }
François Gaffie2110e042015-03-24 08:41:51 +0100182
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700183 // outputs should never be empty here
184 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
185 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100186 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800187
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700189 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100192 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700193 return INVALID_OPERATION;
194 }
195
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700197
Paul McLeane743a472015-01-28 11:07:31 -0800198 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100199 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100202 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100204 mOutputs.clearSessionRoutesForDevice(device);
205
François Gaffie11d30102018-11-02 16:09:09 +0100206 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100207
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 // Reset active device codec
209 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
210
Eric Laurente552edb2014-03-10 17:42:56 -0700211 } break;
212
213 default:
François Gaffie11d30102018-11-02 16:09:09 +0100214 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700215 return BAD_VALUE;
216 }
217
Eric Laurent736a1022019-03-27 18:28:46 -0700218 // Propagate device availability to Engine
219 setEngineDeviceConnectionState(device, state);
220
Eric Laurentae970022019-01-29 14:25:04 -0800221 // No need to evaluate playback routing when connecting a remote submix
222 // output device used by a dynamic policy of type recorder as no
223 // playback use case is affected.
224 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganova30ec142020-03-24 09:32:34 -0700225 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800226 for (audio_io_handle_t output : outputs) {
227 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800228 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
229 if (policyMix != nullptr
230 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganova30ec142020-03-24 09:32:34 -0700231 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800232 doCheckForDeviceAndOutputChanges = false;
233 break;
234 }
235 }
236 }
237
238 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700239 // outputs must be closed after checkOutputForAllStrategies() is executed
240 if (!outputs.isEmpty()) {
241 for (audio_io_handle_t output : outputs) {
242 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100243 // close unused outputs after device disconnection or direct outputs that have
244 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700245 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
246 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800247 (desc->mDirectOpenCount == 0))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700248 closeOutput(output);
249 }
Eric Laurente552edb2014-03-10 17:42:56 -0700250 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700251 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
252 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700254 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800255 };
256
257 if (doCheckForDeviceAndOutputChanges) {
258 checkForDeviceAndOutputChanges(checkCloseOutputs);
259 } else {
260 checkCloseOutputs();
261 }
Eric Laurente552edb2014-03-10 17:42:56 -0700262
Eric Laurent87ffa392015-05-22 10:32:38 -0700263 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100264 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
265 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700266 }
François Gaffie11d30102018-11-02 16:09:09 +0100267 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700268 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
270 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100271 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700272 // do not force device change on duplicated output because if device is 0, it will
273 // also force a device 0 for the two outputs it is duplicated to which may override
274 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100275 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100276 && !desc->isDuplicated()
Mikhail Naganova30ec142020-03-24 09:32:34 -0700277 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700278 // always force when disconnecting (a non-duplicated device)
279 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100280 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700281 }
Eric Laurente552edb2014-03-10 17:42:56 -0700282 }
283
Eric Laurentd60560a2015-04-10 11:31:20 -0700284 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100285 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700286 }
287
Eric Laurent72aa32f2014-05-30 18:51:48 -0700288 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700289 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } // end if is output device
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // handle input devices
Mikhail Naganova30ec142020-03-24 09:32:34 -0700293 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100294 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 switch (state)
296 {
297 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700298 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100300 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700301 return INVALID_OPERATION;
302 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700303
304 if (mAvailableInputDevices.add(device) < 0) {
305 return NO_MEMORY;
306 }
307
François Gaffie44481e72016-04-20 07:49:57 +0200308 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
309 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100310 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200311
Eric Laurent0dd51852019-04-19 18:18:58 -0700312 if (checkInputsForDevice(device, state) != NO_ERROR) {
313 mAvailableInputDevices.remove(device);
314
François Gaffie11d30102018-11-02 16:09:09 +0100315 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100316
317 mHwModules.cleanUpForDevice(device);
318
Eric Laurentd4692962014-05-05 18:13:44 -0700319 return INVALID_OPERATION;
320 }
321
Eric Laurentd4692962014-05-05 18:13:44 -0700322 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700323
324 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700330
François Gaffie11d30102018-11-02 16:09:09 +0100331 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700332
333 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100334 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700335
François Gaffie11d30102018-11-02 16:09:09 +0100336 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700337
338 checkInputsForDevice(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700339 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700340
341 default:
François Gaffie11d30102018-11-02 16:09:09 +0100342 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700343 return BAD_VALUE;
344 }
345
Eric Laurent736a1022019-03-27 18:28:46 -0700346 // Propagate device availability to Engine
347 setEngineDeviceConnectionState(device, state);
348
Eric Laurent0dd51852019-04-19 18:18:58 -0700349 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700350 // As the input device list can impact the output device selection, update
351 // getDeviceForStrategy() cache
352 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700353
Eric Laurent87ffa392015-05-22 10:32:38 -0700354 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100355 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
356 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700357 }
358
Eric Laurentd60560a2015-04-10 11:31:20 -0700359 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100360 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700361 }
362
Eric Laurentb52c1522014-05-20 11:27:36 -0700363 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700364 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700365 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700366
François Gaffie11d30102018-11-02 16:09:09 +0100367 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700368 return BAD_VALUE;
369}
370
Eric Laurent736a1022019-03-27 18:28:46 -0700371void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
372 audio_policy_dev_state_t state) {
373
374 // the Engine does not have to know about remote submix devices used by dynamic audio policies
375 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
376 return;
377 }
378 mEngine->setDeviceConnectionState(device, state);
379}
380
381
Eric Laurente0720872014-03-11 09:30:41 -0700382audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100383 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700384{
Eric Laurent634b7142016-04-20 13:48:02 -0700385 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800386 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
387 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700388 (strlen(device_address) != 0)/*matchAddress*/);
389
390 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100391 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700392 device, device_address);
393 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
394 }
François Gaffie53615e22015-03-19 09:24:12 +0100395
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 DeviceVector *deviceVector;
397
Eric Laurente552edb2014-03-10 17:42:56 -0700398 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700400 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700401 deviceVector = &mAvailableInputDevices;
402 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700404 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700405 }
Eric Laurent634b7142016-04-20 13:48:02 -0700406
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800407 return (deviceVector->getDevice(
408 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700409 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800410}
411
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800412status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
413 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800414 const char *device_name,
415 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800416{
417 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700418 String8 reply;
419 AudioParameter param;
420 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800421
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800422 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
423 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800424
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800425 // connect/disconnect only 1 device at a time
426 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
427
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800428 // Check if the device is currently connected
jiabin12dc6b02019-10-01 09:38:30 -0700429 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800430 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 // Nothing to do: device is not connected
432 return NO_ERROR;
433 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800434 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800435
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700436 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800437 // configure codecs.
438 // Handle two specific cases by sending a set parameter to
439 // configure A2DP codecs. No need to toggle device state.
440 // Case 1: A2DP active device switches from primary to primary
441 // module
442 // Case 2: A2DP device config changes on primary module.
jiabin12dc6b02019-10-01 09:38:30 -0700443 if (audio_is_a2dp_out_device(device)) {
444 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800445 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
446 if (availablePrimaryOutputDevices().contains(devDesc) &&
447 (module != 0 && module->getHandle() == primaryHandle)) {
448 reply = mpClientInterface->getParameters(
449 AUDIO_IO_HANDLE_NONE,
450 String8(AudioParameter::keyReconfigA2dpSupported));
451 AudioParameter repliedParameters(reply);
452 repliedParameters.getInt(
453 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
454 if (isReconfigA2dpSupported) {
455 const String8 key(AudioParameter::keyReconfigA2dp);
456 param.add(key, String8("true"));
457 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
458 devDesc->setEncodedFormat(encodedFormat);
459 return NO_ERROR;
460 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700461 }
462 }
cnx421bd2dcc42020-07-11 14:58:44 +0800463 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
464 for (size_t i = 0; i < mOutputs.size(); i++) {
465 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
466 // mute media strategies and delay device switch by the largest
467 // This avoid sending the music tail into the earpiece or headset.
468 setStrategyMute(musicStrategy, true, desc);
469 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
470 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
471 nullptr, true /*fromCache*/).types());
472 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800473 // Toggle the device state: UNAVAILABLE -> AVAILABLE
474 // This will force reading again the device configuration
475 status = setDeviceConnectionState(device,
476 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800477 device_address, device_name,
478 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800479 if (status != NO_ERROR) {
480 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
481 status);
482 return status;
483 }
484
485 status = setDeviceConnectionState(device,
486 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800488 if (status != NO_ERROR) {
489 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
490 status);
491 return status;
492 }
493
494 return NO_ERROR;
495}
496
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800497status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
498 std::vector<audio_format_t> *formats)
499{
500 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800501 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800502 std::unordered_set<audio_format_t> formatSet;
503 sp<HwModule> primaryModule =
504 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Lata5b023eb2019-07-03 11:20:36 -0700505 if (primaryModule == nullptr) {
506 ALOGE("%s() unable to get primary module", __func__);
507 return NO_INIT;
508 }
jiabin12dc6b02019-10-01 09:38:30 -0700509 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
510 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800511 for (const auto& device : declaredDevices) {
512 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800513 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800514 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800515 return status;
516}
517
François Gaffie11d30102018-11-02 16:09:09 +0100518uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700519{
520 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100521 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700522 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523
jiabin12dc6b02019-10-01 09:38:30 -0700524 if(!hasPrimaryOutput() ||
525 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700526 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700527 }
François Gaffie11d30102018-11-02 16:09:09 +0100528 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
529
Francois Gaffie716e1432019-01-14 16:58:59 +0100530 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100531 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100532 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100533
534 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100535 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700536
537 // release existing RX patch if any
538 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100539 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700540 mCallRxPatch.clear();
541 }
542 // release TX patch if any
543 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100544 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700545 mCallTxPatch.clear();
546 }
547
François Gaffie9eb18552018-11-05 10:33:26 +0100548 auto telephonyRxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700549 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100550 auto telephonyTxModule =
jiabin12dc6b02019-10-01 09:38:30 -0700551 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100552 // retrieve Rx Source and Tx Sink device descriptors
553 sp<DeviceDescriptor> rxSourceDevice =
554 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
555 String8(),
556 AUDIO_FORMAT_DEFAULT);
557 sp<DeviceDescriptor> txSinkDevice =
558 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
559 String8(),
560 AUDIO_FORMAT_DEFAULT);
561
562 // RX and TX Telephony device are declared by Primary Audio HAL
563 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
564 (telephonyRxModule->getHalVersionMajor() >= 3)) {
565 if (rxSourceDevice == 0 || txSinkDevice == 0) {
566 // RX / TX Telephony device(s) is(are) not currently available
567 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
568 return muteWaitMs;
569 }
François Gaffiead447b72019-11-18 15:50:22 +0100570 // createAudioPatchInternal now supports both HW / SW bridging
571 createRxPatch = true;
572 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100573 } else {
574 // If the RX device is on the primary HW module, then use legacy routing method for
575 // voice calls via setOutputDevice() on primary output.
576 // Otherwise, create two audio patches for TX and RX path.
577 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
578 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700579 // If the TX device is also on the primary HW module, setOutputDevice() will take care
580 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100581 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
582 (txSinkDevice != 0);
583 }
584 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
585 // Otherwise, create two audio patches for TX and RX path.
586 if (!createRxPatch) {
587 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700588 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100589 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800590
591 // If the TX device is on the primary HW module but RX device is
592 // on other HW module, SinkMetaData of telephony input should handle it
593 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700594 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700595 if (createTxPatch) { // create TX path audio patch
François Gaffiead447b72019-11-18 15:50:22 +0100596 // terminate active capture if on the same HW module as the call TX source device
597 // FIXME: would be better to refine to only inputs whose profile connects to the
598 // call TX device but this information is not in the audio patch and logic here must be
599 // symmetric to the one in startInput()
600 for (const auto& activeDesc : mInputs.getActiveInputs()) {
601 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
602 closeActiveClients(activeDesc);
603 }
604 }
François Gaffie9eb18552018-11-05 10:33:26 +0100605 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800606 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700607
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800608 return muteWaitMs;
609}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800611sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100612 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700613 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700614
François Gaffie11d30102018-11-02 16:09:09 +0100615 if (device == nullptr) {
616 return nullptr;
617 }
François Gaffiead447b72019-11-18 15:50:22 +0100618
619 // @TODO: still ignoring the address, or not dealing platform with mutliple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800620 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100621 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800622 addSource(mAvailableInputDevices.getDevice(
623 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800624 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100625 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800626 addSink(mAvailableOutputDevices.getDevice(
627 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800628 }
629
François Gaffiead447b72019-11-18 15:50:22 +0100630 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
631 status_t status =
632 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
633 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
634 if (status != NO_ERROR || index < 0) {
635 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
636 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800637 }
François Gaffiead447b72019-11-18 15:50:22 +0100638 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800639}
640
Mikhail Naganov100f0122018-11-29 11:22:16 -0800641bool AudioPolicyManager::isDeviceOfModule(
642 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
643 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
644 if (module != 0) {
645 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
646 .indexOf(devDesc) != NAME_NOT_FOUND
647 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
648 .indexOf(devDesc) != NAME_NOT_FOUND;
649 }
650 return false;
651}
652
Eric Laurente0720872014-03-11 09:30:41 -0700653void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700654{
655 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100656 // store previous phone state for management of sonification strategy below
657 int oldState = mEngine->getPhoneState();
658
659 if (mEngine->setPhoneState(state) != NO_ERROR) {
660 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700661 return;
662 }
François Gaffie2110e042015-03-24 08:41:51 +0100663 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700664 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700665 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700666 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800667 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700668 }
669
François Gaffie2110e042015-03-24 08:41:51 +0100670 /**
671 * Switching to or from incall state or switching between telephony and VoIP lead to force
672 * routing command.
673 */
674 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
675 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700676
677 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700678 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700679
Eric Laurente552edb2014-03-10 17:42:56 -0700680 int delayMs = 0;
681 if (isStateInCall(state)) {
682 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100683 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
684 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700685 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700686 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700687 // mute media and sonification strategies and delay device switch by the largest
688 // latency of any output where either strategy is active.
689 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100690 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
691 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
692 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700693 (delayMs < (int)desc->latency()*2)) {
694 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700695 }
François Gaffiec005e562018-11-06 15:04:49 +0100696 setStrategyMute(musicStrategy, true, desc);
697 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
698 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
699 nullptr, true /*fromCache*/).types());
700 setStrategyMute(sonificationStrategy, true, desc);
701 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
702 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
703 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700704 }
705 }
706
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100708 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700709 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100710 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700711 // force routing command to audio hardware when ending call
712 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100713 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
714 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700715 }
Eric Laurente552edb2014-03-10 17:42:56 -0700716
Eric Laurent87ffa392015-05-22 10:32:38 -0700717 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100718 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700719 } else if (oldState == AUDIO_MODE_IN_CALL) {
720 if (mCallRxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100721 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700722 mCallRxPatch.clear();
723 }
724 if (mCallTxPatch != 0) {
François Gaffiead447b72019-11-18 15:50:22 +0100725 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700726 mCallTxPatch.clear();
727 }
François Gaffie11d30102018-11-02 16:09:09 +0100728 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700729 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100730 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700731 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700732 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700733
734 // reevaluate routing on all outputs in case tracks have been started during the call
735 for (size_t i = 0; i < mOutputs.size(); i++) {
736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100737 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700738 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100739 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700740 }
741 }
742
Eric Laurente552edb2014-03-10 17:42:56 -0700743 if (isStateInCall(state)) {
744 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700745 // force reevaluating accessibility routing when call starts
746 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700747 }
748
749 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100750 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
751 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700752}
753
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700754audio_mode_t AudioPolicyManager::getPhoneState() {
755 return mEngine->getPhoneState();
756}
757
Eric Laurente0720872014-03-11 09:30:41 -0700758void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100759 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700760{
François Gaffie2110e042015-03-24 08:41:51 +0100761 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700762 if (config == mEngine->getForceUse(usage)) {
763 return;
764 }
Eric Laurente552edb2014-03-10 17:42:56 -0700765
François Gaffie2110e042015-03-24 08:41:51 +0100766 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
767 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
768 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700769 }
François Gaffie2110e042015-03-24 08:41:51 +0100770 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
771 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
772 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700773
774 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700775 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800776
Eric Laurent22fcda22019-05-17 16:28:47 -0700777 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
778 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
779 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
780 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
781 }
782
Eric Laurentdc462862016-07-19 12:29:53 -0700783 //FIXME: workaround for truncated touch sounds
784 // to be removed when the problem is handled by system UI
785 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700786 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
787 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
788 }
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -0700789
790 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -0700791
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800792 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100793 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700794 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100795 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800796 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700797 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800798 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700799 }
Eric Laurente552edb2014-03-10 17:42:56 -0700800 }
Eric Laurente552edb2014-03-10 17:42:56 -0700801}
802
Eric Laurente0720872014-03-11 09:30:41 -0700803void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700804{
805 ALOGV("setSystemProperty() property %s, value %s", property, value);
806}
807
Michael Chana94fbb22018-04-24 14:31:19 +1000808// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
809// search to profiles for direct outputs.
810sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100811 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000812 uint32_t samplingRate,
813 audio_format_t format,
814 audio_channel_mask_t channelMask,
815 audio_output_flags_t flags,
816 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700817{
Michael Chana94fbb22018-04-24 14:31:19 +1000818 if (directOnly) {
819 // only retain flags that will drive the direct output profile selection
820 // if explicitly requested
821 static const uint32_t kRelevantFlags =
822 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lata97a47182019-07-03 11:15:33 -0700823 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000824 flags =
825 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
826 }
Eric Laurent861a6282015-05-18 15:40:16 -0700827
828 sp<IOProfile> profile;
829
Mikhail Naganovd4120142017-12-06 15:49:22 -0800830 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800831 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100832 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700833 samplingRate, NULL /*updatedSamplingRate*/,
834 format, NULL /*updatedFormat*/,
835 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700836 flags)) {
837 continue;
838 }
839 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100840 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700841 continue;
842 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800843 // reject profiles if connected device does not support codec
jiabin12dc6b02019-10-01 09:38:30 -0700844 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800845 continue;
846 }
Michael Chana94fbb22018-04-24 14:31:19 +1000847 if (!directOnly) return curProfile;
848 // when searching for direct outputs, if several profiles are compatible, give priority
849 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100850 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700851 continue;
852 }
853 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100854 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700855 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700856 }
Eric Laurente552edb2014-03-10 17:42:56 -0700857 }
858 }
Eric Laurent861a6282015-05-18 15:40:16 -0700859 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700860}
861
Eric Laurentf4e63452017-11-06 19:31:46 +0000862audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700863{
François Gaffiec005e562018-11-06 15:04:49 +0100864 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800865
866 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
867 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
868 // format, flags, etc. This may result in some discrepancy for functions that utilize
869 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
870 // and AudioSystem::getOutputSamplingRate().
871
François Gaffie11d30102018-11-02 16:09:09 +0100872 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700873 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700874
François Gaffie11d30102018-11-02 16:09:09 +0100875 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
876 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000877 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700878}
879
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700880status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
881 const audio_attributes_t *srcAttr,
882 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700883{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700884 if (srcAttr != NULL) {
885 if (!isValidAttributes(srcAttr)) {
886 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
887 __func__,
888 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
889 srcAttr->tags);
890 return BAD_VALUE;
891 }
892 *dstAttr = *srcAttr;
893 } else {
894 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
895 ALOGE("%s: invalid stream type", __func__);
896 return BAD_VALUE;
897 }
François Gaffiec005e562018-11-06 15:04:49 +0100898 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700899 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700900
901 // Only honor audibility enforced when required. The client will be
902 // forced to reconnect if the forced usage changes.
903 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
904 dstAttr->flags &= ~AUDIO_FLAG_AUDIBILITY_ENFORCED;
905 }
906
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700907 return NO_ERROR;
908}
909
Kevin Rocard153f92d2018-12-18 18:33:28 -0800910status_t AudioPolicyManager::getOutputForAttrInt(
911 audio_attributes_t *resultAttr,
912 audio_io_handle_t *output,
913 audio_session_t session,
914 const audio_attributes_t *attr,
915 audio_stream_type_t *stream,
916 uid_t uid,
917 const audio_config_t *config,
918 audio_output_flags_t *flags,
919 audio_port_handle_t *selectedDeviceId,
920 bool *isRequestedDeviceForExclusiveUse,
921 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700922{
François Gaffiec005e562018-11-06 15:04:49 +0100923 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100924 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100925 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100926 const sp<DeviceDescriptor> requestedDevice =
927 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
928
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700929 status_t status = getAudioAttributes(resultAttr, attr, *stream);
930 if (status != NO_ERROR) {
931 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700932 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700933 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
934 resultAttr->flags |= it->second;
935 }
François Gaffiec005e562018-11-06 15:04:49 +0100936 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700937
François Gaffiec005e562018-11-06 15:04:49 +0100938 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
939 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700940
Kevin Rocard153f92d2018-12-18 18:33:28 -0800941 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
942 // otherwise, fallback to the dynamic policies, if none match, query the engine.
943 // Secondary outputs are always found by dynamic policies as the engine do not support them
944 sp<SwAudioOutputDescriptor> policyDesc;
Kevin Rocard94114a22019-04-01 19:38:23 -0700945 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, policyDesc, secondaryDescs);
946 if (status != OK) {
947 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800948 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700949
Kevin Rocard153f92d2018-12-18 18:33:28 -0800950 // Explicit routing is higher priority then any dynamic policy primary output
951 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && policyDesc != nullptr;
952
953 // FIXME: in case of RENDER policy, the output capabilities should be checked
954 if ((usePrimaryOutputFromPolicyMixes || !secondaryDescs->empty())
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800955 && !audio_is_linear_pcm(config->format)) {
956 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800957 return BAD_VALUE;
958 }
959 if (usePrimaryOutputFromPolicyMixes) {
960 *output = policyDesc->mIoHandle;
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800961 sp<AudioPolicyMix> mix = policyDesc->mPolicyMix.promote();
François Gaffiec005e562018-11-06 15:04:49 +0100962 sp<DeviceDescriptor> deviceDesc =
963 mAvailableOutputDevices.getDevice(mix->mDeviceType,
964 mix->mDeviceAddress,
965 AUDIO_FORMAT_DEFAULT);
966 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
967 ALOGV("getOutputForAttr() returns output %d", *output);
968 return NO_ERROR;
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700969 }
François Gaffiec005e562018-11-06 15:04:49 +0100970 // Virtual sources must always be dynamicaly or explicitly routed
971 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
972 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
973 return BAD_VALUE;
974 }
975 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
976 // in order to let the choice of the order to future vendor engine
977 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -0700978
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700979 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +0200980 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -0700981 }
982
Nadav Barb2f18162018-07-18 13:01:53 +0300983 // Set incall music only if device was explicitly set, and fallback to the device which is
984 // chosen by the engine if not.
985 // FIXME: provide a more generic approach which is not device specific and move this back
986 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +0200987 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin12dc6b02019-10-01 09:38:30 -0700988 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +0100989 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +0300990 audio_is_linear_pcm(config->format) &&
991 isInCall()) {
Francois Gaffie716e1432019-01-14 16:58:59 +0100992 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +0300993 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +0100994 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +0300995 }
996 }
997
François Gaffiec005e562018-11-06 15:04:49 +0100998 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
999 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1000 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001001
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001002 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001003 if (!msdDevices.isEmpty()) {
1004 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001005 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1006 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1007 ALOGV("%s() Using MSD devices %s instead of devices %s",
1008 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1009 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001010 } else {
1011 *output = AUDIO_IO_HANDLE_NONE;
1012 }
1013 }
1014 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001015 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001016 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001017 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001018 if (*output == AUDIO_IO_HANDLE_NONE) {
1019 return INVALID_OPERATION;
1020 }
Paul McLeanaa981192015-03-21 09:55:15 -07001021
François Gaffiec005e562018-11-06 15:04:49 +01001022 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001023
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001024 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1025
1026 return NO_ERROR;
1027}
1028
1029status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1030 audio_io_handle_t *output,
1031 audio_session_t session,
1032 audio_stream_type_t *stream,
1033 uid_t uid,
1034 const audio_config_t *config,
1035 audio_output_flags_t *flags,
1036 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001037 audio_port_handle_t *portId,
1038 std::vector<audio_io_handle_t> *secondaryOutputs)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001039{
1040 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1041 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1042 return INVALID_OPERATION;
1043 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001044 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001045 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001046 bool isRequestedDeviceForExclusiveUse = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001047 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputDescs;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001048 const sp<DeviceDescriptor> requestedDevice =
1049 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1050
1051 // Prevent from storing invalid requested device id in clients
1052 const audio_port_handle_t sanitizedRequestedPortId =
1053 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1054 *selectedDeviceId = sanitizedRequestedPortId;
1055
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001056 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001057 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1058 &secondaryOutputDescs);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001059 if (status != NO_ERROR) {
1060 return status;
1061 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001062 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1063 for (auto& secondaryDesc : secondaryOutputDescs) {
1064 secondaryOutputs->push_back(secondaryDesc->mIoHandle);
1065 weakSecondaryOutputDescs.push_back(secondaryDesc);
1066 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001067
Eric Laurent8fc147b2018-07-22 19:13:55 -07001068 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001069 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001070 .format = config->format,
Nick Desaulnierscb137d02019-10-15 18:30:45 -07001071 };
jiabindff2a4f2019-09-10 14:29:54 -07001072 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001073
Eric Laurent8fc147b2018-07-22 19:13:55 -07001074 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001075 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001076 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001077 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001078 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001079 *flags, isRequestedDeviceForExclusiveUse,
1080 std::move(weakSecondaryOutputDescs));
Eric Laurent8fc147b2018-07-22 19:13:55 -07001081 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Andy Hung39efb7a2018-09-26 15:39:28 -07001082 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001083
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001084 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1085 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001086
Eric Laurente83b55d2014-11-14 10:06:21 -08001087 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001088}
1089
François Gaffie11d30102018-11-02 16:09:09 +01001090audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1091 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001092 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001093 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001094 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001095 audio_output_flags_t *flags,
1096 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001097{
Andy Hungc88b0642018-04-27 15:42:35 -07001098 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001099 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001100
jiabine375d412019-02-26 12:54:53 -08001101 // Discard haptic channel mask when forcing muting haptic channels.
1102 audio_channel_mask_t channelMask = forceMutingHaptic
1103 ? (config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL) : config->channel_mask;
1104
Eric Laurente552edb2014-03-10 17:42:56 -07001105 // open a direct output if required by specified parameters
1106 //force direct flag if offload flag is set: offloading implies a direct output stream
1107 // and all common behaviors are driven by checking only the direct flag
1108 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001109 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1110 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001111 }
Nadav Bar766fb022018-01-07 12:18:03 +02001112 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1113 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001114 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001115 // only allow deep buffering for music stream type
1116 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001117 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001118 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001119 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001120 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1121 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001122 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001123 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001124 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001125 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001126 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001127 audio_is_linear_pcm(config->format) &&
1128 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001129 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001130 AUDIO_OUTPUT_FLAG_DIRECT);
1131 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001132 }
Eric Laurente552edb2014-03-10 17:42:56 -07001133
Nadav Bar766fb022018-01-07 12:18:03 +02001134
Eric Laurentb732cf52014-09-24 19:08:21 -07001135 sp<IOProfile> profile;
1136
1137 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001138 // and not explicitly requested
Nadav Bar766fb022018-01-07 12:18:03 +02001139 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Eric Laurentfe231122017-11-17 17:48:06 -08001140 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
jiabine375d412019-02-26 12:54:53 -08001141 audio_channel_count_from_out_mask(channelMask) <= 2) {
Eric Laurentb732cf52014-09-24 19:08:21 -07001142 goto non_direct_output;
1143 }
1144
Andy Hung2ddee192015-12-18 17:34:44 -08001145 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1146 // This prevents creating an offloaded track and tearing it down immediately after start
1147 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -07001148 // FIXME: We should check the audio session here but we do not have it in this context.
1149 // This may prevent offloading in rare situations where effects are left active by apps
1150 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001151
Nadav Bar766fb022018-01-07 12:18:03 +02001152 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -08001153 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
François Gaffie11d30102018-11-02 16:09:09 +01001154 profile = getProfileForOutput(devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001155 config->sample_rate,
1156 config->format,
jiabine375d412019-02-26 12:54:53 -08001157 channelMask,
Michael Chana94fbb22018-04-24 14:31:19 +10001158 (audio_output_flags_t)*flags,
1159 true /* directOnly */);
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
1161
Eric Laurent1c333e22014-05-20 10:48:17 -07001162 if (profile != 0) {
Andy Hungc88b0642018-04-27 15:42:35 -07001163 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1164 for (size_t i = 0; i < mOutputs.size(); i++) {
1165 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1166 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1167 // reuse direct output if currently open by the same client
1168 // and configured with same parameters
jiabineaf09f02019-08-19 15:08:30 -07001169 if ((config->sample_rate == desc->getSamplingRate()) &&
1170 (config->format == desc->getFormat()) &&
1171 (channelMask == desc->getChannelMask()) &&
Andy Hungc88b0642018-04-27 15:42:35 -07001172 (session == desc->mDirectClientSession)) {
1173 desc->mDirectOpenCount++;
François Gaffie11d30102018-11-02 16:09:09 +01001174 ALOGI("%s reusing direct output %d for session %d", __func__,
Andy Hungc88b0642018-04-27 15:42:35 -07001175 mOutputs.keyAt(i), session);
1176 return mOutputs.keyAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001177 }
1178 }
1179 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08001180
1181 if (!profile->canOpenNewIo()) {
1182 goto non_direct_output;
Eric Laurente552edb2014-03-10 17:42:56 -07001183 }
Eric Laurent861a6282015-05-18 15:40:16 -07001184
Eric Laurent3974e3b2017-12-07 17:58:43 -08001185 sp<SwAudioOutputDescriptor> outputDesc =
1186 new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurent53b810e2017-12-10 17:25:10 -08001187
François Gaffie11d30102018-11-02 16:09:09 +01001188 String8 address = getFirstDeviceAddress(devices);
Eric Laurent53b810e2017-12-10 17:25:10 -08001189
Dean Wheatley3023b382018-08-09 07:42:40 +10001190 // MSD patch may be using the only output stream that can service this request. Release
1191 // MSD patch to prioritize this request over any active output on MSD.
1192 AudioPatchCollection msdPatches = getMsdPatches();
1193 for (size_t i = 0; i < msdPatches.size(); i++) {
1194 const auto& patch = msdPatches[i];
1195 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1196 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1197 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
jiabin12dc6b02019-10-01 09:38:30 -07001198 devices.containsDeviceWithType(sink->ext.device.type) &&
Dean Wheatley3023b382018-08-09 07:42:40 +10001199 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1200 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
François Gaffiead447b72019-11-18 15:50:22 +01001201 releaseAudioPatch(patch->getHandle(), mUidCached);
Dean Wheatley3023b382018-08-09 07:42:40 +10001202 break;
1203 }
1204 }
1205 }
1206
François Gaffie11d30102018-11-02 16:09:09 +01001207 status = outputDesc->open(config, devices, stream, *flags, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07001208
1209 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001210 if (status != NO_ERROR ||
jiabineaf09f02019-08-19 15:08:30 -07001211 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1212 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1213 (channelMask != 0 && channelMask != outputDesc->getChannelMask())) {
François Gaffie11d30102018-11-02 16:09:09 +01001214 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1215 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
jiabineaf09f02019-08-19 15:08:30 -07001216 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1217 channelMask, outputDesc->getChannelMask());
Eric Laurentcf2c0212014-07-25 16:20:43 -07001218 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08001219 outputDesc->close();
Eric Laurente552edb2014-03-10 17:42:56 -07001220 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001221 // fall back to mixer output if possible when the direct output could not be open
Eric Laurentfe231122017-11-17 17:48:06 -08001222 if (audio_is_linear_pcm(config->format) &&
1223 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001224 goto non_direct_output;
1225 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001226 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001227 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001228 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001229 outputDesc->mDirectClientSession = session;
1230
Eric Laurente552edb2014-03-10 17:42:56 -07001231 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001232 mPreviousOutputs = mOutputs;
François Gaffie11d30102018-11-02 16:09:09 +01001233 ALOGV("%s returns new direct output %d", __func__, output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001234 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001235 return output;
1236 }
1237
Eric Laurentb732cf52014-09-24 19:08:21 -07001238non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001239
1240 // A request for HW A/V sync cannot fallback to a mixed output because time
1241 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001242 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001243 return AUDIO_IO_HANDLE_NONE;
1244 }
1245
Eric Laurente552edb2014-03-10 17:42:56 -07001246 // ignoring channel mask due to downmix capability in mixer
1247
1248 // open a non direct output
1249
1250 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001251 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001252 // get which output is suitable for the specified stream. The actual
1253 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001254 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001255
Eric Laurent8838a382014-09-08 16:44:28 -07001256 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001257 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabine375d412019-02-26 12:54:53 -08001258 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
Eric Laurente552edb2014-03-10 17:42:56 -07001259 }
François Gaffie11d30102018-11-02 16:09:09 +01001260 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001261 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001262 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001263
Eric Laurente552edb2014-03-10 17:42:56 -07001264 return output;
1265}
1266
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001267sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001268 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1269 mAvailableInputDevices);
1270 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1271}
1272
1273DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1274 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1275 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001276}
1277
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001278const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1279 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001280 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1281 if (msdModule != 0) {
1282 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1283 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1284 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1285 const struct audio_port_config *source = &patch->mPatch.sources[j];
1286 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1287 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffiead447b72019-11-18 15:50:22 +01001288 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001289 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001290 }
1291 }
1292 }
1293 return msdPatches;
1294}
1295
François Gaffie11d30102018-11-02 16:09:09 +01001296status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001297 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1298{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001299 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001300 if (msdModule == nullptr) {
1301 ALOGE("%s() unable to get MSD module", __func__);
1302 return NO_INIT;
1303 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001304 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001305 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001306 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001307 return NO_INIT;
1308 }
1309 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1310 if (inputProfiles.isEmpty()) {
1311 ALOGE("%s() no input profiles for MSD module", __func__);
1312 return NO_INIT;
1313 }
1314 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1315 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001316 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001317 return NO_INIT;
1318 }
1319 AudioProfileVector msdProfiles;
1320 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1321 for (const auto &inProfile : inputProfiles) {
1322 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001323 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 }
1325 }
1326 AudioProfileVector deviceProfiles;
1327 for (const auto &outProfile : outputProfiles) {
1328 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabinb9733bc2019-09-10 14:27:34 -07001329 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001330 }
1331 }
1332 struct audio_config_base bestSinkConfig;
jiabinb9733bc2019-09-10 14:27:34 -07001333 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabinb9733bc2019-09-10 14:27:34 -07001335 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001336 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001337 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1338 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001339 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001340 }
1341 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1342 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1343 sinkConfig->format = bestSinkConfig.format;
1344 // For encoded streams force direct flag to prevent downstream mixing.
1345 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1346 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001347 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1348 // For formats compatible with IEC61937 encapsulation, assume that
1349 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1350 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1351 // raw and IEC61937 framed streams.
1352 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1353 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1354 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001355 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1356 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1357 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1358 sourceConfig->format = bestSinkConfig.format;
1359 // Copy input stream directly without any processing (e.g. resampling).
1360 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1361 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1362 if (hwAvSync) {
1363 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1364 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1365 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1366 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1367 }
1368 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1369 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1370 sinkConfig->config_mask |= config_mask;
1371 sourceConfig->config_mask |= config_mask;
1372 return NO_ERROR;
1373}
1374
François Gaffie11d30102018-11-02 16:09:09 +01001375PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001376{
1377 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001378 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001379 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1380 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1381 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1382 // For now, we just forcefully try with HwAvSync first.
1383 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1384 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1385 getBestMsdAudioProfileFor(
1386 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1387 if (res == NO_ERROR) {
1388 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1389 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1390 }
1391 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1392 " supporting PCM format conversion.", __func__);
1393 return patchBuilder;
1394}
1395
François Gaffie11d30102018-11-02 16:09:09 +01001396status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1397 sp<DeviceDescriptor> device = outputDevice;
1398 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001399 // Use media strategy for unspecified output device. This should only
1400 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1401 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001402 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1403 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001404 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1405 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001406 }
François Gaffie11d30102018-11-02 16:09:09 +01001407 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1408 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001409 const struct audio_patch* patch = patchBuilder.patch();
1410 const AudioPatchCollection msdPatches = getMsdPatches();
1411 if (!msdPatches.isEmpty()) {
1412 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1413 "The current MSD prototype only supports one output patch");
1414 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1415 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1416 return NO_ERROR;
1417 }
François Gaffiead447b72019-11-18 15:50:22 +01001418 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001419 }
1420 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1421 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1422 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1423 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001424 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1425 device->toString().c_str(), patch->sources[0].format,
1426 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001427 return status;
1428}
1429
Eric Laurente0720872014-03-11 09:30:41 -07001430audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001431 audio_output_flags_t flags,
jiabin40573322018-11-08 12:08:02 -08001432 audio_format_t format,
1433 audio_channel_mask_t channelMask,
1434 uint32_t samplingRate)
Eric Laurente552edb2014-03-10 17:42:56 -07001435{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001436 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1437 "%s called with format %#x", __func__, format);
1438
1439 // Flags disqualifying an output: the match must happen before calling selectOutput()
1440 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1441 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1442
1443 // Flags expressing a functional request: must be honored in priority over
1444 // other criteria
1445 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1446 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1447 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1448 // Flags expressing a performance request: have lower priority than serving
1449 // requested sampling rate or channel mask
1450 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1451 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1452 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1453
1454 const audio_output_flags_t functionalFlags =
1455 (audio_output_flags_t)(flags & kFunctionalFlags);
1456 const audio_output_flags_t performanceFlags =
1457 (audio_output_flags_t)(flags & kPerformanceFlags);
1458
1459 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1460
Eric Laurente552edb2014-03-10 17:42:56 -07001461 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001462 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001463 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001464 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001465 // 2: the output with the highest number of requested functional flags
1466 // 3: the output supporting the exact channel mask
1467 // 4: the output with a higher channel count than requested
1468 // 5: the output with a higher sampling rate than requested
1469 // 6: the output with the highest number of requested performance flags
1470 // 7: the output with the bit depth the closest to the requested one
1471 // 8: the primary output
1472 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001473
Eric Laurent16c66dd2019-05-01 17:54:10 -07001474 // matching criteria values in priority order for best matching output so far
1475 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001476
Eric Laurent16c66dd2019-05-01 17:54:10 -07001477 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1478 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1479 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001480
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001481 for (audio_io_handle_t output : outputs) {
1482 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001483 // matching criteria values in priority order for current output
1484 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001485
Eric Laurent16c66dd2019-05-01 17:54:10 -07001486 if (outputDesc->isDuplicated()) {
1487 continue;
1488 }
1489 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1490 continue;
1491 }
Eric Laurent8838a382014-09-08 16:44:28 -07001492
Eric Laurent16c66dd2019-05-01 17:54:10 -07001493 // If haptic channel is specified, use the haptic output if present.
1494 // When using haptic output, same audio format and sample rate are required.
1495 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabineaf09f02019-08-19 15:08:30 -07001496 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001497 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1498 continue;
1499 }
1500 if (outputHapticChannelCount >= hapticChannelCount
jiabineaf09f02019-08-19 15:08:30 -07001501 && format == outputDesc->getFormat()
1502 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001503 currentMatchCriteria[0] = outputHapticChannelCount;
1504 }
1505
1506 // functional flags match
1507 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1508
1509 // channel mask and channel count match
jiabineaf09f02019-08-19 15:08:30 -07001510 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1511 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001512 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1513 channelCount <= outputChannelCount) {
1514 if ((audio_channel_mask_get_representation(channelMask) ==
jiabineaf09f02019-08-19 15:08:30 -07001515 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1516 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001517 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001518 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001519 currentMatchCriteria[3] = outputChannelCount;
1520 }
1521
1522 // sampling rate match
1523 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabineaf09f02019-08-19 15:08:30 -07001524 samplingRate <= outputDesc->getSamplingRate()) {
1525 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001526 }
1527
1528 // performance flags match
1529 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1530
1531 // format match
1532 if (format != AUDIO_FORMAT_INVALID) {
1533 currentMatchCriteria[6] =
jiabindff2a4f2019-09-10 14:29:54 -07001534 PolicyAudioPort::kFormatDistanceMax -
1535 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001536 }
1537
1538 // primary output match
1539 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1540
1541 // compare match criteria by priority then value
1542 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1543 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1544 bestMatchCriteria = currentMatchCriteria;
1545 bestOutput = output;
1546
1547 std::stringstream result;
1548 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1549 std::ostream_iterator<int>(result, " "));
1550 ALOGV("%s new bestOutput %d criteria %s",
1551 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001552 }
1553 }
1554
Eric Laurent16c66dd2019-05-01 17:54:10 -07001555 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001556}
1557
Eric Laurent8fc147b2018-07-22 19:13:55 -07001558status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001559{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001560 ALOGV("%s portId %d", __FUNCTION__, portId);
1561
1562 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1563 if (outputDesc == 0) {
1564 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 return BAD_VALUE;
1566 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001567 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001568
Eric Laurent8fc147b2018-07-22 19:13:55 -07001569 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001570 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001571
Eric Laurent733ce942017-12-07 12:18:25 -08001572 status_t status = outputDesc->start();
1573 if (status != NO_ERROR) {
1574 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001575 }
1576
Eric Laurent97ac8712018-07-27 18:59:02 -07001577 uint32_t delayMs;
1578 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001579
1580 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001581 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001582 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001583 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001584 if (delayMs != 0) {
1585 usleep(delayMs * 1000);
1586 }
1587
1588 return status;
1589}
1590
Eric Laurent97ac8712018-07-27 18:59:02 -07001591status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1592 const sp<TrackClientDescriptor>& client,
1593 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001594{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001595 // cannot start playback of STREAM_TTS if any other output is being used
1596 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001597
1598 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001599 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001600 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001601 auto clientStrategy = client->strategy();
1602 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001603 if (stream == AUDIO_STREAM_TTS) {
1604 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001605 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001606 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001607 return INVALID_OPERATION;
1608 } else {
1609 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1610 }
1611 } else {
1612 // some playback other than beacon starts
1613 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1614 }
1615
Eric Laurent77305a62016-07-25 16:39:22 -07001616 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001617 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001618 bool force = !outputDesc->isActive() &&
1619 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001620
François Gaffie11d30102018-11-02 16:09:09 +01001621 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001622 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001623 const char *address = NULL;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001624 if (policyMix != NULL) {
François Gaffie11d30102018-11-02 16:09:09 +01001625 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001626 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001627 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001628 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001629 } else {
1630 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001631 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001632 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1633 AUDIO_FORMAT_DEFAULT);
1634 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1635 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001636 }
1637
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001638 // requiresMuteCheck is false when we can bypass mute strategy.
1639 // It covers a common case when there is no materially active audio
1640 // and muting would result in unnecessary delay and dropped audio.
1641 const uint32_t outputLatencyMs = outputDesc->latency();
1642 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1643
Eric Laurente552edb2014-03-10 17:42:56 -07001644 // increment usage count for this stream on the requested output:
1645 // NOTE that the usage count is the same for duplicated output and hardware output which is
1646 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001647 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001648
1649 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001650 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1651 client->isPreferredDeviceForExclusiveUse()) {
1652 // Preferred device may be exclusive, use only if no other active clients on this output
1653 devices = DeviceVector(
1654 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1655 } else {
1656 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1657 }
François Gaffie11d30102018-11-02 16:09:09 +01001658 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001659 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001660 }
1661 }
Eric Laurente552edb2014-03-10 17:42:56 -07001662
François Gaffiec005e562018-11-06 15:04:49 +01001663 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001664 selectOutputForMusicEffects();
1665 }
1666
François Gaffie1c878552018-11-22 16:53:21 +01001667 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001668 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001669 if (devices.isEmpty()) {
1670 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001671 }
François Gaffiec005e562018-11-06 15:04:49 +01001672 bool shouldWait =
1673 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1674 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1675 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001676 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001677 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001678 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001679 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001680 // An output has a shared device if
1681 // - managed by the same hw module
1682 // - supports the currently selected device
1683 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001684 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001685
Eric Laurent77305a62016-07-25 16:39:22 -07001686 // force a device change if any other output is:
1687 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001688 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001689 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001690 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001691 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001692 // change the device currently selected by the other output.
1693 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001694 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001695 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001696 force = true;
1697 }
1698 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001699 // a notification so that audio focus effect can propagate, or that a mute/unmute
1700 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001701 const uint32_t latencyMs = desc->latency();
1702 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1703
1704 if (shouldWait && isActive && (waitMs < latencyMs)) {
1705 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001706 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001707
1708 // Require mute check if another output is on a shared device
1709 // and currently active to have proper drain and avoid pops.
1710 // Note restoring AudioTracks onto this output needs to invoke
1711 // a volume ramp if there is no mute.
1712 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001713 }
1714 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001715
1716 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001717 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001718
Eric Laurente552edb2014-03-10 17:42:56 -07001719 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001720 auto &curves = getVolumeCurves(client->attributes());
1721 checkAndSetVolume(curves, client->volumeSource(),
1722 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001723 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001724 outputDesc->devices().types(), 0 /*delay*/,
1725 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001726
1727 // update the outputs if starting an output with a stream that can affect notification
1728 // routing
1729 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001730
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001731 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001732 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001733 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1734 }
Eric Laurentdc462862016-07-19 12:29:53 -07001735
1736 if (waitMs > muteWaitMs) {
1737 *delayMs = waitMs - muteWaitMs;
1738 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001739
1740 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1741 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1742 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1743 // change occurs after the MixerThread starts and causes a stream volume
1744 // glitch.
1745 //
1746 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001747 }
Eric Laurentdc462862016-07-19 12:29:53 -07001748
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001749 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin12dc6b02019-10-01 09:38:30 -07001750 mEngine->getForceUse(
1751 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001752 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001753 }
1754
Eric Laurent97ac8712018-07-27 18:59:02 -07001755 // Automatically enable the remote submix input when output is started on a re routing mix
1756 // of type MIX_TYPE_RECORDERS
jiabin12dc6b02019-10-01 09:38:30 -07001757 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1758 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001759 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1760 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1761 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001762 "remote-submix",
1763 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001764 }
1765
Eric Laurente552edb2014-03-10 17:42:56 -07001766 return NO_ERROR;
1767}
1768
Eric Laurent8fc147b2018-07-22 19:13:55 -07001769status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001770{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001771 ALOGV("%s portId %d", __FUNCTION__, portId);
1772
1773 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1774 if (outputDesc == 0) {
1775 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001776 return BAD_VALUE;
1777 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001778 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001779
Eric Laurent97ac8712018-07-27 18:59:02 -07001780 ALOGV("stopOutput() output %d, stream %d, session %d",
1781 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001782
Eric Laurent97ac8712018-07-27 18:59:02 -07001783 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001784
Eric Laurent733ce942017-12-07 12:18:25 -08001785 if (status == NO_ERROR ) {
1786 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001787 }
1788 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001789}
1790
Eric Laurent97ac8712018-07-27 18:59:02 -07001791status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1792 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001793{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001794 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001795 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001796 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001797
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001798 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1799
François Gaffie1c878552018-11-22 16:53:21 +01001800 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1801 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001802 // Automatically disable the remote submix input when output is stopped on a
1803 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001804 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin12dc6b02019-10-01 09:38:30 -07001805 if (isSingleDeviceType(
1806 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001807 policyMix != NULL &&
1808 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001809 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1810 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001811 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001812 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001813 }
1814 }
1815 bool forceDeviceUpdate = false;
1816 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001817 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001818 forceDeviceUpdate = true;
1819 }
1820
Eric Laurente552edb2014-03-10 17:42:56 -07001821 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001822 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001825 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001826 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001827 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001828 // delay the device switch by twice the latency because stopOutput() is executed when
1829 // the track stop() command is received and at that time the audio track buffer can
1830 // still contain data that needs to be drained. The latency only covers the audio HAL
1831 // and kernel buffers. Also the latency does not always include additional delay in the
1832 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001833 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001834
1835 // force restoring the device selection on other active outputs if it differs from the
1836 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001837 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001838 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001839 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001840 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001841 desc->isActive() &&
1842 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001843 (newDevices != desc->devices())) {
1844 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1845 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001846
François Gaffie11d30102018-11-02 16:09:09 +01001847 setOutputDevices(desc, newDevices2, force, delayMs);
1848
Eric Laurent57de36c2016-09-28 16:59:11 -07001849 // re-apply device specific volume if not done by setOutputDevice()
1850 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001851 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001852 }
Eric Laurente552edb2014-03-10 17:42:56 -07001853 }
1854 }
1855 // update the outputs if stopping one with a stream that can affect notification routing
1856 handleNotificationRoutingForStream(stream);
1857 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001858
1859 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1860 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001861 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001862 }
1863
François Gaffiec005e562018-11-06 15:04:49 +01001864 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001865 selectOutputForMusicEffects();
1866 }
Eric Laurente552edb2014-03-10 17:42:56 -07001867 return NO_ERROR;
1868 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001869 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001870 return INVALID_OPERATION;
1871 }
1872}
1873
Eric Laurent8fc147b2018-07-22 19:13:55 -07001874void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001875{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001876 ALOGV("%s portId %d", __FUNCTION__, portId);
1877
1878 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1879 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001880 // If an output descriptor is closed due to a device routing change,
1881 // then there are race conditions with releaseOutput from tracks
1882 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1883 // destroyed shortly thereafter.
1884 //
1885 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001886 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001887 return;
1888 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001889
1890 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001891
Eric Laurent8fc147b2018-07-22 19:13:55 -07001892 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1893 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001894 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001895 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001896 return;
1897 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001898 if (--outputDesc->mDirectOpenCount == 0) {
1899 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001900 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001901 }
1902 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001903 // stopOutput() needs to be successfully called before releaseOutput()
1904 // otherwise there may be inaccurate stream reference counts.
1905 // This is checked in outputDesc->removeClient below.
1906 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001907}
1908
Eric Laurentcaf7f482014-11-25 17:50:47 -08001909status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1910 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001911 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001912 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001913 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001914 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001915 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001916 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001917 input_type_t *inputType,
1918 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001919{
François Gaffiec005e562018-11-06 15:04:49 +01001920 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1921 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1922 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001923
Eric Laurentad2e7b92017-09-14 20:06:42 -07001924 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001925 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001926 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001927 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001928 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001929 sp<AudioInputDescriptor> inputDesc;
1930 sp<RecordClientDescriptor> clientDesc;
1931 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001932 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001933
1934 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1935 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1936 return INVALID_OPERATION;
1937 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001938
Francois Gaffie716e1432019-01-14 16:58:59 +01001939 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1940 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08001941 }
1942
Paul McLean466dc8e2015-04-17 13:15:36 -06001943 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01001944 sp<DeviceDescriptor> explicitRoutingDevice =
1945 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06001946
Eric Laurentad2e7b92017-09-14 20:06:42 -07001947 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1948 // possible
1949 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1950 *input != AUDIO_IO_HANDLE_NONE) {
1951 ssize_t index = mInputs.indexOfKey(*input);
1952 if (index < 0) {
1953 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1954 status = BAD_VALUE;
1955 goto error;
1956 }
1957 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001958 RecordClientVector clients = inputDesc->getClientsForSession(session);
1959 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07001960 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1961 status = BAD_VALUE;
1962 goto error;
1963 }
1964 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1965 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07001966 // corresponds to a new client and is only permitted from the same UID.
1967 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07001968 if (clients.size() > 1) {
1969 for (const auto& client : clients) {
1970 // The client map is ordered by key values (portId) and portIds are allocated
1971 // incrementaly. So the first client in this list is the one opened by audio flinger
1972 // when the mmap stream is created and should be ignored as it does not correspond
1973 // to an actual client
1974 if (client == *clients.cbegin()) {
1975 continue;
1976 }
1977 if (uid != client->uid() && !client->isSilenced()) {
1978 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1979 uid, client->portId(), client->uid());
1980 status = INVALID_OPERATION;
1981 goto error;
1982 }
Eric Laurent331679c2018-04-16 17:03:16 -07001983 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001984 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07001985 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01001986 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07001987
Eric Laurent8f42ea12018-08-08 09:08:25 -07001988 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001989 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001990 }
1991
1992 *input = AUDIO_IO_HANDLE_NONE;
1993 *inputType = API_INPUT_INVALID;
1994
Francois Gaffie716e1432019-01-14 16:58:59 +01001995 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07001996
Francois Gaffie716e1432019-01-14 16:58:59 +01001997 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
1998 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
1999 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002000 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002001 ALOGW("%s could not find input mix for attr %s",
2002 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002003 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002004 }
jiabinc1de2df2019-05-07 14:26:40 -07002005 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2006 String8(attr->tags + strlen("addr=")),
2007 AUDIO_FORMAT_DEFAULT);
2008 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002009 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002010 __func__, attributes.source, attributes.tags);
2011 status = BAD_VALUE;
2012 goto error;
2013 }
2014
Kevin Rocard25f9b052019-02-27 15:08:54 -08002015 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2016 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2017 } else {
2018 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2019 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002020 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002021 if (explicitRoutingDevice != nullptr) {
2022 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002023 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002024 // Prevent from storing invalid requested device id in clients
2025 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002026 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002027 }
François Gaffie11d30102018-11-02 16:09:09 +01002028 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002029 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002030 status = BAD_VALUE;
2031 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002032 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002033 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002034 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2035 // there is an external policy, but this input is attached to a mix of recorders,
2036 // meaning it receives audio injected into the framework, so the recorder doesn't
2037 // know about it and is therefore considered "legacy"
2038 *inputType = API_INPUT_LEGACY;
2039 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002040 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002041 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002042 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002043 } else {
2044 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002045 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002046
Eric Laurent599c7582015-12-07 18:05:55 -08002047 }
2048
François Gaffiec005e562018-11-06 15:04:49 +01002049 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002050 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002051 status = INVALID_OPERATION;
2052 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002053 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002054
Eric Laurent8f42ea12018-08-08 09:08:25 -07002055exit:
2056
François Gaffiec005e562018-11-06 15:04:49 +01002057 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2058 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002059
Francois Gaffie716e1432019-01-14 16:58:59 +01002060 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002061 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabindff2a4f2019-09-10 14:29:54 -07002062 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002063
Mikhail Naganov2996f672019-04-18 12:29:59 -07002064 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002065 requestedDeviceId, attributes.source, flags,
2066 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002067 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002068 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002069
2070 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2071 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002072
Eric Laurent599c7582015-12-07 18:05:55 -08002073 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002074
2075error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002076 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002077}
2078
2079
François Gaffie11d30102018-11-02 16:09:09 +01002080audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002081 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002082 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002083 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002084 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002085 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002086{
2087 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002088 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002089 bool isSoundTrigger = false;
2090
François Gaffiec005e562018-11-06 15:04:49 +01002091 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002092 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2093 if (index >= 0) {
2094 input = mSoundTriggerSessions.valueFor(session);
2095 isSoundTrigger = true;
2096 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2097 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2098 } else {
2099 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002100 }
François Gaffiec005e562018-11-06 15:04:49 +01002101 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002102 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002103 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002104 }
2105
Andy Hungf129b032015-04-07 13:45:50 -07002106 // find a compatible input profile (not necessarily identical in parameters)
2107 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002108 // sampling rate and flags may be updated by getInputProfile
2109 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2110 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002111 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002112 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002113 audio_input_flags_t profileFlags = flags;
2114 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002115 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002116 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002117 profileFlags);
2118 if (profile != 0) {
2119 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002120 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2121 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002122 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2123 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2124 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002125 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2126 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2127 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002128 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002129 }
Eric Laurente552edb2014-03-10 17:42:56 -07002130 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002131 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002132 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002133 if (samplingRate == 0) {
2134 samplingRate = profileSamplingRate;
2135 }
Eric Laurente552edb2014-03-10 17:42:56 -07002136
Eric Laurent322b4d22015-04-03 15:57:54 -07002137 if (profile->getModuleHandle() == 0) {
2138 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002139 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002140 }
2141
Eric Laurent3974e3b2017-12-07 17:58:43 -08002142 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002143 for (size_t i = 0; i < mInputs.size(); ) {
2144 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2145 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002146 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002147 continue;
2148 }
2149 // if sound trigger, reuse input if used by other sound trigger on same session
2150 // else
2151 // reuse input if active client app is not in IDLE state
2152 //
2153 RecordClientVector clients = desc->clientsList();
2154 bool doClose = false;
2155 for (const auto& client : clients) {
2156 if (isSoundTrigger != client->isSoundTrigger()) {
2157 continue;
2158 }
2159 if (client->isSoundTrigger()) {
2160 if (session == client->session()) {
2161 return desc->mIoHandle;
2162 }
2163 continue;
2164 }
2165 if (client->active() && client->appState() != APP_STATE_IDLE) {
2166 return desc->mIoHandle;
2167 }
2168 doClose = true;
2169 }
2170 if (doClose) {
2171 closeInput(desc->mIoHandle);
2172 } else {
2173 i++;
2174 }
2175 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002176 }
2177
Eric Laurentfe231122017-11-17 17:48:06 -08002178 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002179
Eric Laurentfe231122017-11-17 17:48:06 -08002180 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2181 lConfig.sample_rate = profileSamplingRate;
2182 lConfig.channel_mask = profileChannelMask;
2183 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002184
François Gaffie11d30102018-11-02 16:09:09 +01002185 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002186
2187 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002188 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002189 (profileSamplingRate != lConfig.sample_rate) ||
2190 !audio_formats_match(profileFormat, lConfig.format) ||
2191 (profileChannelMask != lConfig.channel_mask)) {
2192 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002193 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002194 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002195 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002196 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002197 }
Eric Laurent599c7582015-12-07 18:05:55 -08002198 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002199 }
2200
Eric Laurentc722f302014-12-10 11:21:49 -08002201 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002202
Eric Laurent599c7582015-12-07 18:05:55 -08002203 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002204 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002205
Eric Laurent599c7582015-12-07 18:05:55 -08002206 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002207}
2208
Eric Laurent4eb58f12018-12-07 16:41:02 -08002209status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002210{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002211 ALOGV("%s portId %d", __FUNCTION__, portId);
2212
2213 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2214 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002216 return BAD_VALUE;
2217 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002218 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002219 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002220 if (client->active()) {
2221 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2222 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002223 }
2224
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 audio_session_t session = client->session();
2226
Eric Laurent4eb58f12018-12-07 16:41:02 -08002227 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002228
Eric Laurent4eb58f12018-12-07 16:41:02 -08002229 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002230
Eric Laurent4eb58f12018-12-07 16:41:02 -08002231 status_t status = inputDesc->start();
2232 if (status != NO_ERROR) {
2233 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002234 }
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002236 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002237 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002238 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002239
Eric Laurent8f42ea12018-08-08 09:08:25 -07002240 // indicate active capture to sound trigger service if starting capture from a mic on
2241 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002242 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002243 if (device != nullptr) {
2244 status = setInputDevice(input, device, true /* force */);
2245 } else {
2246 ALOGW("%s no new input device can be found for descriptor %d",
2247 __FUNCTION__, inputDesc->getId());
2248 status = BAD_VALUE;
2249 }
Eric Laurente552edb2014-03-10 17:42:56 -07002250
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002251 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002252 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002253 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002254 if ((policyMix != NULL)
2255 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2256 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002257 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002258 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002259
François Gaffie11d30102018-11-02 16:09:09 +01002260 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2261 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002262 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2263 SoundTrigger::setCaptureState(true);
2264 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002265
Eric Laurent8f42ea12018-08-08 09:08:25 -07002266 // automatically enable the remote submix output when input is started if not
2267 // used by a policy mix of type MIX_TYPE_RECORDERS
2268 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002269 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002270 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002271 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002272 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002273 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2274 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002275 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002276 if (address != "") {
2277 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2278 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002279 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002280 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002281 }
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002282 } else if (status != NO_ERROR) {
2283 // Restore client activity state.
2284 inputDesc->setClientActive(client, false);
2285 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
2287
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002288 ALOGV("%s input %d source = %d status = %d exit",
2289 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002290
Mikhail Naganov61e07e32019-07-01 15:07:19 -07002291 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002292}
2293
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002295{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002296 ALOGV("%s portId %d", __FUNCTION__, portId);
2297
2298 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2299 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002300 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002301 return BAD_VALUE;
2302 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002303 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002304 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002305 if (!client->active()) {
2306 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002307 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002308 }
2309
Eric Laurent8f42ea12018-08-08 09:08:25 -07002310 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002311
Eric Laurent8f42ea12018-08-08 09:08:25 -07002312 inputDesc->stop();
2313 if (inputDesc->isActive()) {
2314 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2315 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002316 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002317 // if input maps to a dynamic policy with an activity listener, notify of state change
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002318 if ((policyMix != NULL)
2319 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2320 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002321 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002322 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002323
2324 // automatically disable the remote submix output when input is stopped if not
2325 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002326 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002327 String8 address = String8("");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002328 if (policyMix == NULL) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002329 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002330 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2331 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002332 }
2333 if (address != "") {
2334 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2335 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002336 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002337 }
2338 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002339 resetInputDevice(input);
2340
2341 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2342 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002343 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2344 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002345 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2346 SoundTrigger::setCaptureState(false);
2347 }
2348 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002349 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002350 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002351}
2352
Eric Laurent8fc147b2018-07-22 19:13:55 -07002353void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002354{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002355 ALOGV("%s portId %d", __FUNCTION__, portId);
2356
2357 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2358 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002359 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002360 return;
2361 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002362 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002363 audio_io_handle_t input = inputDesc->mIoHandle;
2364
Eric Laurent8f42ea12018-08-08 09:08:25 -07002365 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002366
Andy Hung39efb7a2018-09-26 15:39:28 -07002367 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002368
Andy Hung39efb7a2018-09-26 15:39:28 -07002369 if (inputDesc->getClientCount() > 0) {
2370 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002371 return;
2372 }
2373
Eric Laurent05b90f82014-08-27 15:32:29 -07002374 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002375 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002376 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002377}
2378
Eric Laurent8f42ea12018-08-08 09:08:25 -07002379void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002380{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002381 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002382
2383 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002384 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385 }
2386}
2387
Eric Laurent8f42ea12018-08-08 09:08:25 -07002388void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2389{
2390 stopInput(portId);
2391 releaseInput(portId);
2392}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002393
Eric Laurent0dd51852019-04-19 18:18:58 -07002394void AudioPolicyManager::checkCloseInputs() {
2395 // After connecting or disconnecting an input device, close input if:
2396 // - it has no client (was just opened to check profile) OR
2397 // - none of its supported devices are connected anymore OR
2398 // - one of its clients cannot be routed to one of its supported
2399 // devices anymore. Otherwise update device selection
2400 std::vector<audio_io_handle_t> inputsToClose;
2401 for (size_t i = 0; i < mInputs.size(); i++) {
2402 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2403 if (input->clientsList().size() == 0
Eric Laurentb5dc2d12019-07-13 09:32:47 -07002404 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())
jiabindff2a4f2019-09-10 14:29:54 -07002405 || (input->getPolicyAudioPort()->getFlags()
2406 & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002407 inputsToClose.push_back(mInputs.keyAt(i));
2408 } else {
2409 bool close = false;
2410 for (const auto& client : input->clientsList()) {
2411 sp<DeviceDescriptor> device =
2412 mEngine->getInputDeviceForAttributes(client->attributes());
2413 if (!input->supportedDevices().contains(device)) {
2414 close = true;
2415 break;
2416 }
2417 }
2418 if (close) {
2419 inputsToClose.push_back(mInputs.keyAt(i));
2420 } else {
2421 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2422 }
2423 }
2424 }
2425
2426 for (const audio_io_handle_t handle : inputsToClose) {
2427 ALOGV("%s closing input %d", __func__, handle);
2428 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002429 }
Eric Laurentd4692962014-05-05 18:13:44 -07002430}
2431
François Gaffie251c7f02018-11-07 10:41:08 +01002432void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002433{
2434 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002435 if (indexMin < 0 || indexMax < 0) {
2436 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2437 return;
2438 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002439 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002440
2441 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002442 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2443 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002444 continue;
2445 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002446 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002447 }
Eric Laurente552edb2014-03-10 17:42:56 -07002448}
2449
Eric Laurente0720872014-03-11 09:30:41 -07002450status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002451 int index,
2452 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002453{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002454 auto attributes = mEngine->getAttributesForStreamType(stream);
Francois Gaffie5992b182020-03-20 14:55:14 +01002455 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2456 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2457 return NO_ERROR;
2458 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002459 ALOGV("%s: stream %s attributes=%s", __func__,
2460 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002461 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002462}
2463
Eric Laurente0720872014-03-11 09:30:41 -07002464status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002465 int *index,
2466 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002467{
François Gaffiec005e562018-11-06 15:04:49 +01002468 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2469 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002470 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002471 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002472 deviceTypes = mEngine->getOutputDevicesForStream(
2473 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002474 }
jiabin12dc6b02019-10-01 09:38:30 -07002475 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002476}
2477
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002478status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002479 int index,
2480 audio_devices_t device)
2481{
2482 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002483 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2484 if (group == VOLUME_GROUP_NONE) {
2485 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002486 return BAD_VALUE;
2487 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002488 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002489 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002490 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002491 VolumeSource vs = toVolumeSource(group);
2492 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2493
2494 status = setVolumeCurveIndex(index, device, curves);
2495 if (status != NO_ERROR) {
2496 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2497 return status;
2498 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002499
jiabin12dc6b02019-10-01 09:38:30 -07002500 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002501 auto curCurvAttrs = curves.getAttributes();
2502 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2503 auto attr = curCurvAttrs.front();
jiabin12dc6b02019-10-01 09:38:30 -07002504 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002505 } else if (!curves.getStreamTypes().empty()) {
2506 auto stream = curves.getStreamTypes().front();
jiabin12dc6b02019-10-01 09:38:30 -07002507 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002508 } else {
2509 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2510 return BAD_VALUE;
2511 }
jiabin12dc6b02019-10-01 09:38:30 -07002512 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2513 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002514
François Gaffiecfe17322018-11-07 13:41:29 +01002515 // update volume on all outputs and streams matching the following:
2516 // - The requested stream (or a stream matching for volume control) is active on the output
2517 // - The device (or devices) selected by the engine for this stream includes
2518 // the requested device
2519 // - For non default requested device, currently selected device on the output is either the
2520 // requested device or one of the devices selected by the engine for this stream
2521 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2522 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002523 for (size_t i = 0; i < mOutputs.size(); i++) {
2524 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07002525 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002526
jiabin12dc6b02019-10-01 09:38:30 -07002527 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2528 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002529 }
François Gaffieed91f582020-01-31 10:35:37 +01002530 if (!(desc->isActive(vs) || isInCall())) {
2531 continue;
2532 }
2533 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2534 curDevices.find(device) == curDevices.end()) {
2535 continue;
2536 }
2537 bool applyVolume = false;
2538 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2539 curSrcDevices.insert(device);
2540 applyVolume = (curSrcDevices.find(
2541 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2542 } else {
2543 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2544 }
2545 if (!applyVolume) {
2546 continue; // next output
2547 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002548 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2549 // If a higher priority strategy is active, and the output is routed to a device with a
2550 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002551 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002552 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002553 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2554 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2555 false /*preferredDevice*/);
2556 if (activeClients.empty()) {
2557 continue;
2558 }
2559 bool isPreempted = false;
2560 bool isHigherPriority = productStrategy < strategy;
2561 for (const auto &client : activeClients) {
2562 if (isHigherPriority && (client->volumeSource() != vs)) {
2563 ALOGV("%s: Strategy=%d (\nrequester:\n"
2564 " group %d, volumeGroup=%d attributes=%s)\n"
2565 " higher priority source active:\n"
2566 " volumeGroup=%d attributes=%s) \n"
2567 " on output %zu, bailing out", __func__, productStrategy,
2568 group, group, toString(attributes).c_str(),
2569 client->volumeSource(), toString(client->attributes()).c_str(), i);
2570 applyVolume = false;
2571 isPreempted = true;
2572 break;
2573 }
2574 // However, continue for loop to ensure no higher prio clients running on output
2575 if (client->volumeSource() == vs) {
2576 applyVolume = true;
2577 }
2578 }
2579 if (isPreempted || applyVolume) {
2580 break;
2581 }
2582 }
2583 if (!applyVolume) {
2584 continue; // next output
2585 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002586 }
François Gaffieed91f582020-01-31 10:35:37 +01002587 //FIXME: workaround for truncated touch sounds
2588 // delayed volume change for system stream to be removed when the problem is
2589 // handled by system UI
2590 status_t volStatus = checkAndSetVolume(
2591 curves, vs, index, desc, curDevices,
2592 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2593 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2594 if (volStatus != NO_ERROR) {
2595 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002596 }
2597 }
François Gaffiecfe17322018-11-07 13:41:29 +01002598 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2599 return status;
2600}
2601
François Gaffieaaac0fd2018-11-22 17:56:39 +01002602status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002603 audio_devices_t device,
2604 IVolumeCurves &volumeCurves)
2605{
2606 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2607 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002608 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2609 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002610 (index > volumeCurves.getVolumeIndexMax())) {
2611 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2612 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2613 return BAD_VALUE;
2614 }
2615 if (!audio_is_output_device(device)) {
2616 return BAD_VALUE;
2617 }
2618
2619 // Force max volume if stream cannot be muted
2620 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2621
François Gaffieaaac0fd2018-11-22 17:56:39 +01002622 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002623 volumeCurves.addCurrentVolumeIndex(device, index);
2624 return NO_ERROR;
2625}
2626
2627status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2628 int &index,
2629 audio_devices_t device)
2630{
2631 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2632 // stream by the engine.
jiabin12dc6b02019-10-01 09:38:30 -07002633 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002634 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin12dc6b02019-10-01 09:38:30 -07002635 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2636 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002637 }
jiabin12dc6b02019-10-01 09:38:30 -07002638 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002639}
2640
2641status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2642 int &index,
jiabin12dc6b02019-10-01 09:38:30 -07002643 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002644{
jiabin12dc6b02019-10-01 09:38:30 -07002645 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002646 return BAD_VALUE;
2647 }
jiabin12dc6b02019-10-01 09:38:30 -07002648 index = curves.getVolumeIndex(deviceTypes);
2649 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002650 return NO_ERROR;
2651}
2652
2653status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2654 int &index)
2655{
2656 index = getVolumeCurves(attr).getVolumeIndexMin();
2657 return NO_ERROR;
2658}
2659
2660status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2661 int &index)
2662{
2663 index = getVolumeCurves(attr).getVolumeIndexMax();
2664 return NO_ERROR;
2665}
2666
Eric Laurent36829f92017-04-07 19:04:42 -07002667audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002668{
2669 // select one output among several suitable for global effects.
2670 // The priority is as follows:
2671 // 1: An offloaded output. If the effect ends up not being offloadable,
2672 // AudioFlinger will invalidate the track and the offloaded output
2673 // will be closed causing the effect to be moved to a PCM output.
2674 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002675 // 3: The primary output
2676 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002677
François Gaffiec005e562018-11-06 15:04:49 +01002678 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2679 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002680 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002681
Eric Laurent36829f92017-04-07 19:04:42 -07002682 if (outputs.size() == 0) {
2683 return AUDIO_IO_HANDLE_NONE;
2684 }
Eric Laurente552edb2014-03-10 17:42:56 -07002685
Eric Laurent36829f92017-04-07 19:04:42 -07002686 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2687 bool activeOnly = true;
2688
2689 while (output == AUDIO_IO_HANDLE_NONE) {
2690 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2691 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2692 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2693
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002694 for (audio_io_handle_t output : outputs) {
2695 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002696 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002697 continue;
2698 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002699 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2700 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002701 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002702 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002703 }
2704 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002705 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002706 }
2707 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002708 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002709 }
2710 }
2711 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2712 output = outputOffloaded;
2713 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2714 output = outputDeepBuffer;
2715 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2716 output = outputPrimary;
2717 } else {
2718 output = outputs[0];
2719 }
2720 activeOnly = false;
2721 }
2722
2723 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002724 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002725 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2726 mMusicEffectOutput = output;
2727 }
2728
2729 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002730 return output;
2731}
2732
Eric Laurent36829f92017-04-07 19:04:42 -07002733audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2734{
2735 return selectOutputForMusicEffects();
2736}
2737
Eric Laurente0720872014-03-11 09:30:41 -07002738status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002739 audio_io_handle_t io,
2740 uint32_t strategy,
2741 int session,
2742 int id)
2743{
Eric Laurent9b2064c2019-11-22 17:25:04 -08002744 if (session != AUDIO_SESSION_DEVICE) {
2745 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002746 if (index < 0) {
Eric Laurent9b2064c2019-11-22 17:25:04 -08002747 index = mInputs.indexOfKey(io);
2748 if (index < 0) {
2749 ALOGW("registerEffect() unknown io %d", io);
2750 return INVALID_OPERATION;
2751 }
Eric Laurente552edb2014-03-10 17:42:56 -07002752 }
2753 }
François Gaffiec005e562018-11-06 15:04:49 +01002754 return mEffects.registerEffect(desc, io, session, id,
2755 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2756 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002757}
2758
Eric Laurentc241b0d2018-11-28 09:08:49 -08002759status_t AudioPolicyManager::unregisterEffect(int id)
2760{
2761 if (mEffects.getEffect(id) == nullptr) {
2762 return INVALID_OPERATION;
2763 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002764 if (mEffects.isEffectEnabled(id)) {
2765 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2766 setEffectEnabled(id, false);
2767 }
2768 return mEffects.unregisterEffect(id);
2769}
2770
Eric Laurentb20cf7d2019-04-05 19:37:34 -07002771void AudioPolicyManager::cleanUpEffectsForIo(audio_io_handle_t io)
2772{
2773 EffectDescriptorCollection effects = mEffects.getEffectsForIo(io);
2774 for (size_t i = 0; i < effects.size(); i++) {
2775 ALOGW("%s removing stale effect %s, id %d on closed IO %d",
2776 __func__, effects.valueAt(i)->mDesc.name, effects.keyAt(i), io);
2777 unregisterEffect(effects.keyAt(i));
2778 }
2779}
2780
Eric Laurentc241b0d2018-11-28 09:08:49 -08002781status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2782{
2783 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2784 if (effect == nullptr) {
2785 return INVALID_OPERATION;
2786 }
2787
2788 status_t status = mEffects.setEffectEnabled(id, enabled);
2789 if (status == NO_ERROR) {
2790 mInputs.trackEffectEnabled(effect, enabled);
2791 }
2792 return status;
2793}
2794
Eric Laurent6c796322019-04-09 14:13:17 -07002795
2796status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2797{
2798 mEffects.moveEffects(ids, io);
2799 return NO_ERROR;
2800}
2801
Eric Laurentc75307b2015-03-17 15:29:32 -07002802bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2803{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002804 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002805}
2806
2807bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2808{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002809 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002810}
2811
Eric Laurente0720872014-03-11 09:30:41 -07002812bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002813{
2814 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002815 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002816 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002817 return true;
2818 }
2819 }
2820 return false;
2821}
2822
Eric Laurent275e8e92014-11-30 15:14:47 -08002823// Register a list of custom mixes with their attributes and format.
2824// When a mix is registered, corresponding input and output profiles are
2825// added to the remote submix hw module. The profile contains only the
2826// parameters (sampling rate, format...) specified by the mix.
2827// The corresponding input remote submix device is also connected.
2828//
2829// When a remote submix device is connected, the address is checked to select the
2830// appropriate profile and the corresponding input or output stream is opened.
2831//
2832// When capture starts, getInputForAttr() will:
2833// - 1 look for a mix matching the address passed in attribtutes tags if any
2834// - 2 if none found, getDeviceForInputSource() will:
2835// - 2.1 look for a mix matching the attributes source
2836// - 2.2 if none found, default to device selection by policy rules
2837// At this time, the corresponding output remote submix device is also connected
2838// and active playback use cases can be transferred to this mix if needed when reconnecting
2839// after AudioTracks are invalidated
2840//
2841// When playback starts, getOutputForAttr() will:
2842// - 1 look for a mix matching the address passed in attribtutes tags if any
2843// - 2 if none found, look for a mix matching the attributes usage
2844// - 3 if none found, default to device and output selection by policy rules.
2845
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002846status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002847{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002848 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2849 status_t res = NO_ERROR;
2850
2851 sp<HwModule> rSubmixModule;
2852 // examine each mix's route type
2853 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002854 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002855 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2856 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2857 ALOGE("Unsupported Policy Mix %zu of %zu: "
2858 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2859 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002860 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002861 break;
2862 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002863 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2864 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002865 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002866 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2867 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002868 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002869 rSubmixModule = mHwModules.getModuleFromName(
2870 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2871 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002872 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002873 i);
2874 res = INVALID_OPERATION;
2875 break;
2876 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002877 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002878
Eric Laurent97ac8712018-07-27 18:59:02 -07002879 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002880 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002881 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002882 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002883 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2884 } else {
2885 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2886 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002887 }
François Gaffie036e1e92015-03-19 10:16:24 +01002888
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002889 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002890 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002891 res = INVALID_OPERATION;
2892 break;
2893 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002894 audio_config_t outputConfig = mix.mFormat;
2895 audio_config_t inputConfig = mix.mFormat;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002896 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2897 // stereo and let audio flinger do the channel conversion if needed.
2898 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2899 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabineaf09f02019-08-19 15:08:30 -07002900 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002901 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabineaf09f02019-08-19 15:08:30 -07002902 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002903 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002904
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002905 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002906 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2907 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2908 ALOGE("Failed to set remote submix device available, type %u, address %s",
2909 mix.mDeviceType, address.string());
2910 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002911 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002912 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2913 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002914 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002915 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002916 i, mixes.size(), type, address.string());
2917
2918 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2919 mix.mDeviceType, mix.mDeviceAddress,
2920 String8(), AUDIO_FORMAT_DEFAULT);
2921 if (device == nullptr) {
2922 res = INVALID_OPERATION;
2923 break;
2924 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002925
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002926 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002927 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2928 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002929
2930 if (desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002931 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002932 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2933 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002934 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002935 } else {
2936 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002937 }
2938 break;
2939 }
2940 }
2941
2942 if (res != NO_ERROR) {
2943 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002944 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002945 res = INVALID_OPERATION;
2946 break;
2947 } else if (!foundOutput) {
2948 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002949 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002950 res = INVALID_OPERATION;
2951 break;
2952 }
Eric Laurentc722f302014-12-10 11:21:49 -08002953 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002954 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002955 if (res != NO_ERROR) {
2956 unregisterPolicyMixes(mixes);
2957 }
2958 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002959}
2960
2961status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2962{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002963 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002964 status_t res = NO_ERROR;
2965 sp<HwModule> rSubmixModule;
2966 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002967 for (const auto& mix : mixes) {
2968 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002969
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002970 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002971 rSubmixModule = mHwModules.getModuleFromName(
2972 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2973 if (rSubmixModule == 0) {
2974 res = INVALID_OPERATION;
2975 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002976 }
2977 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002978
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002979 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002980
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002981 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002982 res = INVALID_OPERATION;
2983 continue;
2984 }
2985
Kevin Rocard04ed0462019-05-02 17:53:24 -07002986 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
2987 if (getDeviceConnectionState(device, address.string()) ==
2988 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2989 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2990 address.string(), "remote-submix",
2991 AUDIO_FORMAT_DEFAULT);
2992 if (res != OK) {
2993 ALOGE("Error making RemoteSubmix device unavailable for mix "
2994 "with type %d, address %s", device, address.string());
2995 }
2996 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002997 }
jiabineaf09f02019-08-19 15:08:30 -07002998 rSubmixModule->removeOutputProfile(address.c_str());
2999 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003000
Kevin Rocard153f92d2018-12-18 18:33:28 -08003001 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003002 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003003 res = INVALID_OPERATION;
3004 continue;
3005 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003006 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003007 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003008 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003009}
3010
Mikhail Naganov100f0122018-11-29 11:22:16 -08003011void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3012{
3013 size_t i = 0;
3014 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3015 for (const auto& fmt : mManualSurroundFormats) {
3016 if (i++ != 0) dst->append(", ");
3017 std::string sfmt;
3018 FormatConverter::toString(fmt, sfmt);
3019 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3020 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3021 }
3022}
3023
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003024status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
3025 const Vector<AudioDeviceTypeAddr>& devices) {
3026 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
3027 // uid/device affinity is only for output devices
3028 for (size_t i = 0; i < devices.size(); i++) {
3029 if (!audio_is_output_device(devices[i].mType)) {
3030 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
3031 devices[i].mType);
3032 return BAD_VALUE;
3033 }
3034 }
3035 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
3036 if (res == NO_ERROR) {
3037 // reevaluate outputs for all given devices
3038 for (size_t i = 0; i < devices.size(); i++) {
3039 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin5b781412019-11-04 14:10:42 -08003040 devices[i].mType, devices[i].mAddress.c_str(), String8(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003041 AUDIO_FORMAT_DEFAULT);
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003042 SortedVector<audio_io_handle_t> outputs;
3043 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
François Gaffie11d30102018-11-02 16:09:09 +01003044 outputs) != NO_ERROR) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003045 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
jiabin5b781412019-11-04 14:10:42 -08003046 " addr=%s", devices[i].mType, devices[i].mAddress.c_str());
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003047 return INVALID_OPERATION;
3048 }
3049 }
3050 }
3051 return res;
3052}
3053
3054status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3055 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003056 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3057 if (res != NO_ERROR) {
3058 ALOGE("%s() Could not remove all device affinities fo uid = %d",
3059 __FUNCTION__, uid);
3060 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003061 }
3062
3063 return res;
3064}
3065
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07003066status_t AudioPolicyManager::setPreferredDeviceForStrategy(product_strategy_t strategy,
3067 const AudioDeviceTypeAddr &device) {
3068 ALOGI("%s() strategy=%d device=%08x addr=%s", __FUNCTION__,
3069 strategy, device.mType, device.mAddress.c_str());
3070 // strategy preferred device is only for output devices
3071 if (!audio_is_output_device(device.mType)) {
3072 ALOGE("%s() device=%08x is NOT an output device", __FUNCTION__, device.mType);
3073 return BAD_VALUE;
3074 }
3075
3076 status_t status = mEngine->setPreferredDeviceForStrategy(strategy, device);
3077 if (status != NO_ERROR) {
3078 ALOGW("Engine could not set preferred device %08x %s for strategy %d",
3079 device.mType, device.mAddress.c_str(), strategy);
3080 return status;
3081 }
3082
3083 checkForDeviceAndOutputChanges();
3084 updateCallAndOutputRouting();
3085
3086 return NO_ERROR;
3087}
3088
3089void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3090{
3091 uint32_t waitMs = 0;
3092 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3093 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3094 waitMs = updateCallRouting(newDevices, delayMs);
3095 }
3096 for (size_t i = 0; i < mOutputs.size(); i++) {
3097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3098 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3099 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3100 // As done in setDeviceConnectionState, we could also fix default device issue by
3101 // preventing the force re-routing in case of default dev that distinguishes on address.
3102 // Let's give back to engine full device choice decision however.
3103 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
3104 }
3105 if (forceVolumeReeval && !newDevices.isEmpty()) {
3106 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3107 }
3108 }
3109}
3110
3111status_t AudioPolicyManager::removePreferredDeviceForStrategy(product_strategy_t strategy)
3112{
3113 ALOGI("%s() strategy=%d", __FUNCTION__, strategy);
3114
3115 status_t status = mEngine->removePreferredDeviceForStrategy(strategy);
3116 if (status != NO_ERROR) {
3117 ALOGW("Engine could not remove preferred device for strategy %d", strategy);
3118 return status;
3119 }
3120
3121 checkForDeviceAndOutputChanges();
3122 updateCallAndOutputRouting();
3123
3124 return NO_ERROR;
3125}
3126
3127status_t AudioPolicyManager::getPreferredDeviceForStrategy(product_strategy_t strategy,
3128 AudioDeviceTypeAddr &device) {
3129 return mEngine->getPreferredDeviceForStrategy(strategy, device);
3130}
3131
Andy Hungc29d82b2018-10-05 12:23:17 -07003132void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003133{
Andy Hungc29d82b2018-10-05 12:23:17 -07003134 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3135 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003136 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003137 std::string stateLiteral;
3138 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003139 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003140 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3141 "communications", "media", "record", "dock", "system",
3142 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3143 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3144 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003145 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3146 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3147 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3148 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3149 dst->append(" (MANUAL: ");
3150 dumpManualSurroundFormats(dst);
3151 dst->append(")");
3152 }
3153 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003154 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003155 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3156 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
3157 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
3158 mAvailableOutputDevices.dump(dst, String8("Available output"));
3159 mAvailableInputDevices.dump(dst, String8("Available input"));
3160 mHwModulesAll.dump(dst);
3161 mOutputs.dump(dst);
3162 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003163 mEffects.dump(dst);
3164 mAudioPatches.dump(dst);
3165 mPolicyMixes.dump(dst);
3166 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003167
Kevin Rocardb99cc752019-03-21 20:52:24 -07003168 dst->appendFormat(" AllowedCapturePolicies:\n");
3169 for (auto& policy : mAllowedCapturePolicies) {
3170 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3171 }
3172
François Gaffiec005e562018-11-06 15:04:49 +01003173 dst->appendFormat("\nPolicy Engine dump:\n");
3174 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003175}
3176
3177status_t AudioPolicyManager::dump(int fd)
3178{
3179 String8 result;
3180 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003181 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003182 return NO_ERROR;
3183}
3184
Kevin Rocardb99cc752019-03-21 20:52:24 -07003185status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3186{
3187 mAllowedCapturePolicies[uid] = capturePolicy;
3188 return NO_ERROR;
3189}
3190
Eric Laurente552edb2014-03-10 17:42:56 -07003191// This function checks for the parameters which can be offloaded.
3192// This can be enhanced depending on the capability of the DSP and policy
3193// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003194bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003195{
3196 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003197 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003198 offloadInfo.sample_rate, offloadInfo.channel_mask,
3199 offloadInfo.format,
3200 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3201 offloadInfo.has_video);
3202
Andy Hung2ddee192015-12-18 17:34:44 -08003203 if (mMasterMono) {
3204 return false; // no offloading if mono is set.
3205 }
3206
Eric Laurente552edb2014-03-10 17:42:56 -07003207 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003208 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3209 ALOGV("offload disabled by audio.offload.disable");
3210 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003211 }
3212
3213 // Check if stream type is music, then only allow offload as of now.
3214 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3215 {
3216 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3217 return false;
3218 }
3219
3220 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003221 const bool allowOffloadWithVideo =
3222 property_get_bool("audio.offload.video", false /* default_value */);
3223 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003224 ALOGV("isOffloadSupported: has_video == true, returning false");
3225 return false;
3226 }
3227
3228 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003229 const int min_duration_secs = property_get_int32(
3230 "audio.offload.min.duration.secs", -1 /* default_value */);
3231 if (min_duration_secs >= 0) {
3232 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3233 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3234 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003235 return false;
3236 }
3237 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3238 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3239 return false;
3240 }
3241
3242 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3243 // creating an offloaded track and tearing it down immediately after start when audioflinger
3244 // detects there is an active non offloadable effect.
3245 // FIXME: We should check the audio session here but we do not have it in this context.
3246 // This may prevent offloading in rare situations where effects are left active by apps
3247 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003248 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003249 return false;
3250 }
3251
3252 // See if there is a profile to support this.
3253 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003254 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003255 offloadInfo.sample_rate,
3256 offloadInfo.format,
3257 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003258 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3259 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003260 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3261 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003262}
3263
Michael Chana94fbb22018-04-24 14:31:19 +10003264bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3265 const audio_attributes_t& attributes) {
3266 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003267 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003268 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003269 config.sample_rate,
3270 config.format,
3271 config.channel_mask,
3272 output_flags,
3273 true /* directOnly */);
3274 ALOGV("%s() profile %sfound with name: %s, "
3275 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3276 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabineaf09f02019-08-19 15:08:30 -07003277 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003278 config.sample_rate, config.format, config.channel_mask, output_flags);
3279 return (profile != 0);
3280}
3281
Eric Laurent6a94d692014-05-20 11:18:06 -07003282status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3283 audio_port_type_t type,
3284 unsigned int *num_ports,
3285 struct audio_port *ports,
3286 unsigned int *generation)
3287{
3288 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3289 generation == NULL) {
3290 return BAD_VALUE;
3291 }
3292 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3293 if (ports == NULL) {
3294 *num_ports = 0;
3295 }
3296
3297 size_t portsWritten = 0;
3298 size_t portsMax = *num_ports;
3299 *num_ports = 0;
3300 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003301 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3302 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003303 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003304 for (const auto& dev : mAvailableOutputDevices) {
3305 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003306 continue;
3307 }
3308 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003309 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003310 }
3311 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003312 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003313 }
3314 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003315 for (const auto& dev : mAvailableInputDevices) {
3316 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003317 continue;
3318 }
3319 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003320 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003321 }
3322 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003323 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003324 }
3325 }
3326 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3327 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3328 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3329 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3330 }
3331 *num_ports += mInputs.size();
3332 }
3333 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003334 size_t numOutputs = 0;
3335 for (size_t i = 0; i < mOutputs.size(); i++) {
3336 if (!mOutputs[i]->isDuplicated()) {
3337 numOutputs++;
3338 if (portsWritten < portsMax) {
3339 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3340 }
3341 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003342 }
Eric Laurent84c70242014-06-23 08:46:27 -07003343 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003344 }
3345 }
3346 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003347 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003348 return NO_ERROR;
3349}
3350
Eric Laurent99fcae42018-05-17 16:59:18 -07003351status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003352{
Eric Laurent99fcae42018-05-17 16:59:18 -07003353 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3354 return BAD_VALUE;
3355 }
3356 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3357 if (dev != 0) {
3358 dev->toAudioPort(port);
3359 return NO_ERROR;
3360 }
3361 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3362 if (dev != 0) {
3363 dev->toAudioPort(port);
3364 return NO_ERROR;
3365 }
3366 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3367 if (out != 0) {
3368 out->toAudioPort(port);
3369 return NO_ERROR;
3370 }
3371 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3372 if (in != 0) {
3373 in->toAudioPort(port);
3374 return NO_ERROR;
3375 }
3376 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003377}
3378
François Gaffiead447b72019-11-18 15:50:22 +01003379status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3380 audio_patch_handle_t *handle,
3381 uid_t uid, uint32_t delayMs,
3382 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003383{
François Gaffiead447b72019-11-18 15:50:22 +01003384 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003385 if (handle == NULL || patch == NULL) {
3386 return BAD_VALUE;
3387 }
François Gaffiead447b72019-11-18 15:50:22 +01003388 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003389
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003390 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003391 return BAD_VALUE;
3392 }
3393 // only one source per audio patch supported for now
3394 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003395 return INVALID_OPERATION;
3396 }
Eric Laurent874c42872014-08-08 15:13:39 -07003397
3398 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003399 return INVALID_OPERATION;
3400 }
Eric Laurent874c42872014-08-08 15:13:39 -07003401 for (size_t i = 0; i < patch->num_sinks; i++) {
3402 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3403 return INVALID_OPERATION;
3404 }
3405 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003406
3407 sp<AudioPatch> patchDesc;
3408 ssize_t index = mAudioPatches.indexOfKey(*handle);
3409
François Gaffiead447b72019-11-18 15:50:22 +01003410 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3411 patch->sources[0].role,
3412 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003413#if LOG_NDEBUG == 0
3414 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffiead447b72019-11-18 15:50:22 +01003415 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3416 patch->sinks[i].role,
3417 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003418 }
3419#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003420
3421 if (index >= 0) {
3422 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003423 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3424 __func__, mUidCached, patchDesc->getUid(), uid);
3425 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003426 return INVALID_OPERATION;
3427 }
3428 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003429 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003430 }
3431
3432 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003433 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003434 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003435 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003436 return BAD_VALUE;
3437 }
Eric Laurent84c70242014-06-23 08:46:27 -07003438 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3439 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003440 if (patchDesc != 0) {
3441 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffiead447b72019-11-18 15:50:22 +01003442 ALOGV("%s source id differs for patch current id %d new id %d",
3443 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003444 return BAD_VALUE;
3445 }
3446 }
Eric Laurent874c42872014-08-08 15:13:39 -07003447 DeviceVector devices;
3448 for (size_t i = 0; i < patch->num_sinks; i++) {
3449 // Only support mix to devices connection
3450 // TODO add support for mix to mix connection
3451 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003452 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003453 return INVALID_OPERATION;
3454 }
3455 sp<DeviceDescriptor> devDesc =
3456 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3457 if (devDesc == 0) {
François Gaffiead447b72019-11-18 15:50:22 +01003458 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003459 return BAD_VALUE;
3460 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003461
François Gaffie11d30102018-11-02 16:09:09 +01003462 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003463 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003464 NULL, // updatedSamplingRate
3465 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003466 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003467 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003468 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003469 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffiead447b72019-11-18 15:50:22 +01003470 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003471 return INVALID_OPERATION;
3472 }
3473 devices.add(devDesc);
3474 }
3475 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003476 return INVALID_OPERATION;
3477 }
Eric Laurent874c42872014-08-08 15:13:39 -07003478
Eric Laurent6a94d692014-05-20 11:18:06 -07003479 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003480 ALOGV("%s setting device %s on output %d",
3481 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003482 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003483 index = mAudioPatches.indexOfKey(*handle);
3484 if (index >= 0) {
3485 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003486 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003487 }
3488 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003489 patchDesc->setUid(uid);
3490 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003491 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003492 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003493 return INVALID_OPERATION;
3494 }
3495 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3496 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3497 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003498 // only one sink supported when connecting an input device to a mix
3499 if (patch->num_sinks > 1) {
3500 return INVALID_OPERATION;
3501 }
François Gaffie53615e22015-03-19 09:24:12 +01003502 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003503 if (inputDesc == NULL) {
3504 return BAD_VALUE;
3505 }
3506 if (patchDesc != 0) {
3507 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3508 return BAD_VALUE;
3509 }
3510 }
François Gaffie11d30102018-11-02 16:09:09 +01003511 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003512 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003513 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003514 return BAD_VALUE;
3515 }
3516
François Gaffie11d30102018-11-02 16:09:09 +01003517 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003518 patch->sinks[0].sample_rate,
3519 NULL, /*updatedSampleRate*/
3520 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003521 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003522 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003523 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003524 // FIXME for the parameter type,
3525 // and the NONE
3526 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003527 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003528 return INVALID_OPERATION;
3529 }
3530 // TODO: reconfigure output format and channels here
François Gaffiead447b72019-11-18 15:50:22 +01003531 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003532 device->toString().c_str(), inputDesc->mIoHandle);
3533 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003534 index = mAudioPatches.indexOfKey(*handle);
3535 if (index >= 0) {
3536 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffiead447b72019-11-18 15:50:22 +01003537 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003538 }
3539 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003540 patchDesc->setUid(uid);
3541 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003542 } else {
François Gaffiead447b72019-11-18 15:50:22 +01003543 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003544 return INVALID_OPERATION;
3545 }
3546 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3547 // device to device connection
3548 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003549 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003550 return BAD_VALUE;
3551 }
3552 }
François Gaffie11d30102018-11-02 16:09:09 +01003553 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003554 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003555 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003556 return BAD_VALUE;
3557 }
Eric Laurent874c42872014-08-08 15:13:39 -07003558
Eric Laurent6a94d692014-05-20 11:18:06 -07003559 //update source and sink with our own data as the data passed in the patch may
3560 // be incomplete.
François Gaffiead447b72019-11-18 15:50:22 +01003561 PatchBuilder patchBuilder;
3562 audio_port_config sourcePortConfig = {};
3563 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3564 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003565
Eric Laurent874c42872014-08-08 15:13:39 -07003566 for (size_t i = 0; i < patch->num_sinks; i++) {
3567 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003568 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003569 return INVALID_OPERATION;
3570 }
François Gaffie11d30102018-11-02 16:09:09 +01003571 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003572 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003573 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003574 return BAD_VALUE;
3575 }
François Gaffiead447b72019-11-18 15:50:22 +01003576 audio_port_config sinkPortConfig = {};
3577 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3578 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003579
Eric Laurent3bcf8592015-04-03 12:13:24 -07003580 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003581 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003582 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003583 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffiead447b72019-11-18 15:50:22 +01003584 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3585 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003586 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3587 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffiead447b72019-11-18 15:50:22 +01003588 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3589 (sourceDesc != nullptr &&
3590 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003591 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003592 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003593 return INVALID_OPERATION;
3594 }
François Gaffiead447b72019-11-18 15:50:22 +01003595 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3596 if (sourceDesc != nullptr) {
3597 // take care of dynamic routing for SwOutput selection,
3598 audio_attributes_t attributes = sourceDesc->attributes();
3599 audio_stream_type_t stream = sourceDesc->stream();
3600 audio_attributes_t resultAttr;
3601 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3602 config.sample_rate = sourceDesc->config().sample_rate;
3603 config.channel_mask = sourceDesc->config().channel_mask;
3604 config.format = sourceDesc->config().format;
3605 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3606 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3607 bool isRequestedDeviceForExclusiveUse = false;
3608 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputs;
3609 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3610 &stream, sourceDesc->uid(), &config, &flags,
3611 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3612 &secondaryOutputs);
3613 if (output == AUDIO_IO_HANDLE_NONE) {
3614 ALOGV("%s no output for device %s",
3615 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003616 return INVALID_OPERATION;
3617 }
François Gaffiead447b72019-11-18 15:50:22 +01003618 } else {
3619 SortedVector<audio_io_handle_t> outputs =
3620 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3621 // if the sink device is reachable via an opened output stream, request to
3622 // go via this output stream by adding a second source to the patch
3623 // description
3624 output = selectOutput(outputs);
3625 }
3626 if (output != AUDIO_IO_HANDLE_NONE) {
3627 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3628 if (outputDesc->isDuplicated()) {
3629 ALOGV("%s output for device %s is duplicated",
3630 __FUNCTION__, sinkDevice->toString().c_str());
3631 return INVALID_OPERATION;
3632 }
3633 audio_port_config srcMixPortConfig = {};
3634 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3635 if (sourceDesc != nullptr) {
3636 sourceDesc->setSwOutput(outputDesc);
3637 }
3638 // for volume control, we may need a valid stream
3639 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3640 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3641 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003642 }
Eric Laurent83b88082014-06-20 18:31:16 -07003643 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003644 }
3645 // TODO: check from routing capabilities in config file and other conflicting patches
3646
François Gaffiead447b72019-11-18 15:50:22 +01003647 status_t status = installPatch(
3648 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003649 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01003650 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003651 return INVALID_OPERATION;
3652 }
3653 } else {
3654 return BAD_VALUE;
3655 }
3656 } else {
3657 return BAD_VALUE;
3658 }
3659 return NO_ERROR;
3660}
3661
3662status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3663 uid_t uid)
3664{
3665 ALOGV("releaseAudioPatch() patch %d", handle);
3666
3667 ssize_t index = mAudioPatches.indexOfKey(handle);
3668
3669 if (index < 0) {
3670 return BAD_VALUE;
3671 }
3672 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01003673 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3674 __func__, mUidCached, patchDesc->getUid(), uid);
3675 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003676 return INVALID_OPERATION;
3677 }
François Gaffiead447b72019-11-18 15:50:22 +01003678 return releaseAudioPatchInternal(handle);
3679}
Eric Laurent6a94d692014-05-20 11:18:06 -07003680
François Gaffiead447b72019-11-18 15:50:22 +01003681status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3682 uint32_t delayMs)
3683{
3684 ALOGV("%s patch %d", __func__, handle);
3685 if (mAudioPatches.indexOfKey(handle) < 0) {
3686 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3687 return BAD_VALUE;
3688 }
3689 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003690 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffiead447b72019-11-18 15:50:22 +01003691 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003692 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003693 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003694 if (outputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003695 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003696 return BAD_VALUE;
3697 }
3698
François Gaffie11d30102018-11-02 16:09:09 +01003699 setOutputDevices(outputDesc,
3700 getNewOutputDevices(outputDesc, true /*fromCache*/),
3701 true,
3702 0,
3703 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003704 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3705 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003706 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003707 if (inputDesc == NULL) {
François Gaffiead447b72019-11-18 15:50:22 +01003708 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 return BAD_VALUE;
3710 }
3711 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003712 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003713 true,
3714 NULL);
3715 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffiead447b72019-11-18 15:50:22 +01003716 status_t status =
3717 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
3718 ALOGV("%s patch panel returned %d patchHandle %d",
3719 __func__, status, patchDesc->getAfHandle());
3720 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07003721 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003722 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie3b173542020-04-06 17:39:47 +02003723 // SW Bridge
3724 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
3725 sp<SwAudioOutputDescriptor> outputDesc =
3726 mOutputs.getOutputFromId(patch->sources[1].id);
3727 if (outputDesc == NULL) {
3728 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
3729 return BAD_VALUE;
3730 }
3731 // Reset handle so that setOutputDevice will force new AF patch to reach the sink
3732 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
3733 setOutputDevices(outputDesc,
3734 getNewOutputDevices(outputDesc, true /*fromCache*/),
3735 true, /*force*/
3736 0,
3737 NULL);
3738 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003739 } else {
3740 return BAD_VALUE;
3741 }
3742 } else {
3743 return BAD_VALUE;
3744 }
3745 return NO_ERROR;
3746}
3747
3748status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3749 struct audio_patch *patches,
3750 unsigned int *generation)
3751{
François Gaffie53615e22015-03-19 09:24:12 +01003752 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 return BAD_VALUE;
3754 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003755 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003756 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003757}
3758
Eric Laurente1715a42014-05-20 11:30:42 -07003759status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003760{
Eric Laurente1715a42014-05-20 11:30:42 -07003761 ALOGV("setAudioPortConfig()");
3762
3763 if (config == NULL) {
3764 return BAD_VALUE;
3765 }
3766 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3767 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003768 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3769 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003770 }
3771
Eric Laurenta121f902014-06-03 13:32:54 -07003772 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003773 if (config->type == AUDIO_PORT_TYPE_MIX) {
3774 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003775 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003776 if (outputDesc == NULL) {
3777 return BAD_VALUE;
3778 }
Eric Laurent84c70242014-06-23 08:46:27 -07003779 ALOG_ASSERT(!outputDesc->isDuplicated(),
3780 "setAudioPortConfig() called on duplicated output %d",
3781 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003782 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003783 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003784 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003785 if (inputDesc == NULL) {
3786 return BAD_VALUE;
3787 }
Eric Laurenta121f902014-06-03 13:32:54 -07003788 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003789 } else {
3790 return BAD_VALUE;
3791 }
3792 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3793 sp<DeviceDescriptor> deviceDesc;
3794 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3795 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3796 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3797 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3798 } else {
3799 return BAD_VALUE;
3800 }
3801 if (deviceDesc == NULL) {
3802 return BAD_VALUE;
3803 }
Eric Laurenta121f902014-06-03 13:32:54 -07003804 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003805 } else {
3806 return BAD_VALUE;
3807 }
3808
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003809 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003810 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3811 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07003812 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07003813 audioPortConfig->toAudioPortConfig(&newConfig, config);
3814 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003815 }
Eric Laurenta121f902014-06-03 13:32:54 -07003816 if (status != NO_ERROR) {
3817 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003818 }
Eric Laurente1715a42014-05-20 11:30:42 -07003819
3820 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003821}
3822
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003823void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3824{
Eric Laurentd60560a2015-04-10 11:31:20 -07003825 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003826 clearAudioPatches(uid);
3827 clearSessionRoutes(uid);
3828}
3829
Eric Laurent6a94d692014-05-20 11:18:06 -07003830void AudioPolicyManager::clearAudioPatches(uid_t uid)
3831{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003832 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003833 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffiead447b72019-11-18 15:50:22 +01003834 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003835 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 }
3837 }
3838}
3839
François Gaffiec005e562018-11-06 15:04:49 +01003840void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003841{
François Gaffiec005e562018-11-06 15:04:49 +01003842 // Take the first attributes following the product strategy as it is used to retrieve the routed
3843 // device. All attributes wihin a strategy follows the same "routing strategy"
3844 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3845 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01003846 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003847 for (size_t j = 0; j < mOutputs.size(); j++) {
3848 if (mOutputs.keyAt(j) == ouptutToSkip) {
3849 continue;
3850 }
3851 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01003852 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003853 continue;
3854 }
3855 // If the default device for this strategy is on another output mix,
3856 // invalidate all tracks in this strategy to force re connection.
3857 // Otherwise select new device on the output mix.
3858 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01003859 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3860 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003861 }
3862 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003863 setOutputDevices(
3864 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003865 }
3866 }
3867}
3868
3869void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3870{
3871 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01003872 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07003873 for (size_t i = 0; i < mOutputs.size(); i++) {
3874 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003875 for (const auto& client : outputDesc->getClientIterable()) {
3876 if (client->hasPreferredDevice() && client->uid() == uid) {
3877 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01003878 auto clientStrategy = client->strategy();
3879 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3880 end(affectedStrategies)) {
3881 continue;
3882 }
3883 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003884 }
3885 }
3886 }
3887 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003888 for (const auto& strategy : affectedStrategies) {
3889 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003890 }
3891
3892 // remove input routes associated with this uid
3893 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07003894 for (size_t i = 0; i < mInputs.size(); i++) {
3895 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07003896 for (const auto& client : inputDesc->getClientIterable()) {
3897 if (client->hasPreferredDevice() && client->uid() == uid) {
3898 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3899 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003900 }
3901 }
3902 }
3903 // reroute inputs if necessary
3904 SortedVector<audio_io_handle_t> inputsToClose;
3905 for (size_t i = 0; i < mInputs.size(); i++) {
3906 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003907 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003908 inputsToClose.add(inputDesc->mIoHandle);
3909 }
3910 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003911 for (const auto& input : inputsToClose) {
3912 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003913 }
3914}
3915
Eric Laurentd60560a2015-04-10 11:31:20 -07003916void AudioPolicyManager::clearAudioSources(uid_t uid)
3917{
3918 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003919 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3920 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07003921 stopAudioSource(mAudioSources.keyAt(i));
3922 }
3923 }
3924}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003925
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003926status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3927 audio_io_handle_t *ioHandle,
3928 audio_devices_t *device)
3929{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003930 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3931 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01003932 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01003933 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003934
François Gaffiedf372692015-03-19 10:43:27 +01003935 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003936}
3937
Eric Laurentd60560a2015-04-10 11:31:20 -07003938status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003939 const audio_attributes_t *attributes,
3940 audio_port_handle_t *portId,
3941 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003942{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003943 ALOGV("%s", __FUNCTION__);
3944 *portId = AUDIO_PORT_HANDLE_NONE;
3945
3946 if (source == NULL || attributes == NULL || portId == NULL) {
3947 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3948 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07003949 return BAD_VALUE;
3950 }
3951
Eric Laurentd60560a2015-04-10 11:31:20 -07003952 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3953 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003954 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3955 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003956 return INVALID_OPERATION;
3957 }
3958
François Gaffie11d30102018-11-02 16:09:09 +01003959 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07003960 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003961 String8(source->ext.device.address),
3962 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01003963 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003964 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07003965 return BAD_VALUE;
3966 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003967
jiabindff2a4f2019-09-10 14:29:54 -07003968 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07003969
François Gaffieaaac0fd2018-11-22 17:56:39 +01003970 sp<SourceClientDescriptor> sourceDesc =
François Gaffiead447b72019-11-18 15:50:22 +01003971 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003972 mEngine->getStreamTypeForAttributes(*attributes),
3973 mEngine->getProductStrategyForAttributes(*attributes),
3974 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07003975
3976 status_t status = connectAudioSource(sourceDesc);
3977 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003978 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07003979 }
3980 return status;
3981}
3982
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003983status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07003984{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003985 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07003986
3987 // make sure we only have one patch per source.
3988 disconnectAudioSource(sourceDesc);
3989
Eric Laurent3e6c7e12018-07-27 17:09:23 -07003990 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01003991 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07003992
François Gaffiec005e562018-11-06 15:04:49 +01003993 DeviceVector sinkDevices =
3994 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3995 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01003996 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3997 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3998 __FUNCTION__, sinkDevice->toString().c_str());
François Gaffiead447b72019-11-18 15:50:22 +01003999 PatchBuilder patchBuilder;
4000 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4001 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4002 status_t status =
4003 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4004 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4005 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4006 return INVALID_OPERATION;
4007 }
4008 sourceDesc->setPatchHandle(handle);
4009 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4010 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4011 if (swOutput != 0) {
4012 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004013 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004014 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004015 }
François Gaffiead447b72019-11-18 15:50:22 +01004016 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004017 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffiead447b72019-11-18 15:50:22 +01004018 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004019 }
François Gaffiead447b72019-11-18 15:50:22 +01004020 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004021 uint32_t delayMs = 0;
François Gaffiead447b72019-11-18 15:50:22 +01004022 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004023 if (status != NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004024 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4025 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004026 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004027 if (delayMs != 0) {
4028 usleep(delayMs * 1000);
4029 }
François Gaffiead447b72019-11-18 15:50:22 +01004030 } else {
4031 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4032 if (hwOutputDesc != 0) {
4033 // create Hwoutput and add to mHwOutputs
4034 } else {
4035 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4036 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004037 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004038 return NO_ERROR;
François Gaffiead447b72019-11-18 15:50:22 +01004039
4040FailureSourceActive:
4041 swOutput->stop();
4042 releaseOutput(sourceDesc->portId());
4043FailureSourceAdded:
4044 sourceDesc->setSwOutput(nullptr);
4045FailureReleasePatch:
4046 releaseAudioPatchInternal(handle);
4047 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004048}
4049
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004050status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004051{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004052 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4053 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004054 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004055 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004056 return BAD_VALUE;
4057 }
4058 status_t status = disconnectAudioSource(sourceDesc);
4059
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004060 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004061 return status;
4062}
4063
Andy Hung2ddee192015-12-18 17:34:44 -08004064status_t AudioPolicyManager::setMasterMono(bool mono)
4065{
4066 if (mMasterMono == mono) {
4067 return NO_ERROR;
4068 }
4069 mMasterMono = mono;
4070 // if enabling mono we close all offloaded devices, which will invalidate the
4071 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4072 // for recreating the new AudioTrack as non-offloaded PCM.
4073 //
4074 // If disabling mono, we leave all tracks as is: we don't know which clients
4075 // and tracks are able to be recreated as offloaded. The next "song" should
4076 // play back offloaded.
4077 if (mMasterMono) {
4078 Vector<audio_io_handle_t> offloaded;
4079 for (size_t i = 0; i < mOutputs.size(); ++i) {
4080 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4081 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4082 offloaded.push(desc->mIoHandle);
4083 }
4084 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004085 for (const auto& handle : offloaded) {
4086 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004087 }
4088 }
4089 // update master mono for all remaining outputs
4090 for (size_t i = 0; i < mOutputs.size(); ++i) {
4091 updateMono(mOutputs.keyAt(i));
4092 }
4093 return NO_ERROR;
4094}
4095
4096status_t AudioPolicyManager::getMasterMono(bool *mono)
4097{
4098 *mono = mMasterMono;
4099 return NO_ERROR;
4100}
4101
Eric Laurentac9cef52017-06-09 15:46:26 -07004102float AudioPolicyManager::getStreamVolumeDB(
4103 audio_stream_type_t stream, int index, audio_devices_t device)
4104{
jiabin12dc6b02019-10-01 09:38:30 -07004105 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004106}
4107
jiabin81772902018-04-02 17:52:27 -07004108status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4109 audio_format_t *surroundFormats,
4110 bool *surroundFormatsEnabled,
4111 bool reported)
4112{
4113 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4114 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4115 return BAD_VALUE;
4116 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004117 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4118 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004119
4120 size_t formatsWritten = 0;
4121 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004122 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004123 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004124 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004125 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004126 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4127 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4128 FormatVector supportedFormats =
4129 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4130 for (size_t j = 0; j < supportedFormats.size(); j++) {
4131 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4132 formats.insert(supportedFormats[j]);
4133 } else {
4134 for (const auto& pair : mConfig.getSurroundFormats()) {
4135 if (pair.second.count(supportedFormats[j]) != 0) {
4136 formats.insert(pair.first);
4137 break;
4138 }
4139 }
4140 }
4141 }
jiabin81772902018-04-02 17:52:27 -07004142 }
4143 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004144 for (const auto& pair : mConfig.getSurroundFormats()) {
4145 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004146 }
4147 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004148 *numSurroundFormats = formats.size();
4149 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4150 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004151 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004152 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004153 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004154 bool formatEnabled = true;
4155 switch (forceUse) {
4156 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4157 formatEnabled = mManualSurroundFormats.count(format) != 0;
4158 break;
4159 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4160 formatEnabled = false;
4161 break;
4162 default: // AUTO or ALWAYS => true
4163 break;
jiabin81772902018-04-02 17:52:27 -07004164 }
4165 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4166 }
jiabin81772902018-04-02 17:52:27 -07004167 }
4168 return NO_ERROR;
4169}
4170
4171status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4172{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004173 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004174 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4175 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004176 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004177 return BAD_VALUE;
4178 }
4179
Mikhail Naganov100f0122018-11-29 11:22:16 -08004180 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4181 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004182 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004183 return INVALID_OPERATION;
4184 }
4185
Mikhail Naganov100f0122018-11-29 11:22:16 -08004186 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004187 return NO_ERROR;
4188 }
4189
Mikhail Naganov100f0122018-11-29 11:22:16 -08004190 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004191 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004192 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004193 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004194 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004195 }
4196 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004197 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004198 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004199 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004200 }
4201 }
4202
4203 sp<SwAudioOutputDescriptor> outputDesc;
4204 bool profileUpdated = false;
jiabin12dc6b02019-10-01 09:38:30 -07004205 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4206 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004207 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4208 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004209 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004210 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004211 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4212 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4213 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004214 name.c_str(),
4215 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004216 if (status != NO_ERROR) {
4217 continue;
4218 }
4219 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4220 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4221 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004222 name.c_str(),
4223 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004224 profileUpdated |= (status == NO_ERROR);
4225 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004226 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin12dc6b02019-10-01 09:38:30 -07004227 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004228 AUDIO_DEVICE_IN_HDMI);
4229 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4230 // Simulate reconnection to update enabled surround sound formats.
jiabin6713a382019-09-12 16:29:15 -07004231 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabineaf09f02019-08-19 15:08:30 -07004232 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004233 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4234 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4235 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004236 name.c_str(),
4237 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004238 if (status != NO_ERROR) {
4239 continue;
4240 }
4241 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4242 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4243 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004244 name.c_str(),
4245 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004246 profileUpdated |= (status == NO_ERROR);
4247 }
4248
jiabin81772902018-04-02 17:52:27 -07004249 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004250 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004251 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004252 }
4253
4254 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4255}
4256
Eric Laurentf32108e2018-10-04 17:22:04 -07004257void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004258{
Eric Laurent4eb58f12018-12-07 16:41:02 -08004259 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004260 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentb20cf7d2019-04-05 19:37:34 -07004261 mInputs.valueAt(i)->setAppState(uid, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004262 }
4263}
4264
jiabin6012f912018-11-02 17:06:30 -07004265bool AudioPolicyManager::isHapticPlaybackSupported()
4266{
4267 for (const auto& hwModule : mHwModules) {
4268 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4269 for (const auto &outProfile : outputProfiles) {
4270 struct audio_port audioPort;
4271 outProfile->toAudioPort(&audioPort);
4272 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4273 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4274 return true;
4275 }
4276 }
4277 }
4278 }
4279 return false;
4280}
4281
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004282status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004283{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004284 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffiead447b72019-11-18 15:50:22 +01004285 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4286 if (swOutput != 0) {
4287 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004288 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01004289 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004290 }
François Gaffiead447b72019-11-18 15:50:22 +01004291 releaseOutput(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004292 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004293 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004294 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004295 // close Hwoutput and remove from mHwOutputs
4296 } else {
4297 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4298 }
4299 }
François Gaffiead447b72019-11-18 15:50:22 +01004300 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004301}
4302
François Gaffiec005e562018-11-06 15:04:49 +01004303sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4304 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004305{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004306 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004307 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004308 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004309 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004310 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4311 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004312 source = sourceDesc;
4313 break;
4314 }
4315 }
4316 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004317}
4318
Eric Laurente552edb2014-03-10 17:42:56 -07004319// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004320// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004321// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004322uint32_t AudioPolicyManager::nextAudioPortGeneration()
4323{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004324 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004325}
4326
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004327static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4328 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004329 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004330 status_t ret;
4331
Cheney Ni00ce33d2018-11-01 06:30:37 +08004332 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
Cheney Nie5985452019-02-24 01:39:15 +08004333 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4334 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4335 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4336 // the legacy hardware module for A2DP and hearing aid.
4337 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4338 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4339 // A2DP offload supported but disabled: try to use special XML file
Cheney Ni6851adb2018-11-01 06:30:37 +08004340 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4341 }
Cheney Nie5985452019-02-24 01:39:15 +08004342 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4343 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07004344 }
4345 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4346
4347 for (const char* fileName : fileNames) {
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004348 for (const auto& path : audio_get_configuration_paths()) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004349 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
Mikhail Naganovedc0ae12020-04-14 14:47:01 -07004350 "%s/%s", path.c_str(), fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004351 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004352 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004353 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004354 return ret;
4355 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004356 }
4357 }
4358 return ret;
4359}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004360
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004361AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4362 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004363 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004364 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004365 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004366 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004367 mA2dpSuspended(false),
Mikhail Naganov560095b2020-03-05 16:28:57 -08004368 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004369 mAudioPortGeneration(1),
4370 mBeaconMuteRefCount(0),
4371 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004372 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004373 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004374 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004375 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004376{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004377}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004378
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004379AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4380 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4381{
4382 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004383}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004384
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004385void AudioPolicyManager::loadConfig() {
4386 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004387 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004388 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004389 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004390}
4391
4392status_t AudioPolicyManager::initialize() {
Mikhail Naganove13c6792019-05-14 10:32:51 -07004393 {
4394 auto engLib = EngineLibrary::load(
4395 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4396 if (!engLib) {
4397 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4398 return NO_INIT;
4399 }
4400 mEngine = engLib->createEngine();
4401 if (mEngine == nullptr) {
4402 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4403 return NO_INIT;
4404 }
François Gaffie2110e042015-03-24 08:41:51 +01004405 }
4406 mEngine->setObserver(this);
4407 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004408 if (status != NO_ERROR) {
4409 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4410 return status;
4411 }
François Gaffie2110e042015-03-24 08:41:51 +01004412
Mikhail Naganov560095b2020-03-05 16:28:57 -08004413 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004414 // open all output streams needed to access attached devices
Mikhail Naganova30ec142020-03-24 09:32:34 -07004415 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004416
Eric Laurent3a4311c2014-03-17 12:00:47 -07004417 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004418 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4419 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4420 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004421 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004422 }
jiabin9ff780e2018-03-19 18:19:52 -07004423 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004424 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabin6713a382019-09-12 16:29:15 -07004425 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004426 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004427 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004428 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabin6713a382019-09-12 16:29:15 -07004429 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004430 }
4431 }
4432 }
Eric Laurente552edb2014-03-10 17:42:56 -07004433
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004434 if (mPrimaryOutput == 0) {
4435 ALOGE("Failed to open primary output");
4436 status = NO_INIT;
4437 }
Eric Laurente552edb2014-03-10 17:42:56 -07004438
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004439 // Silence ALOGV statements
4440 property_set("log.tag." LOG_TAG, "D");
4441
Eric Laurente552edb2014-03-10 17:42:56 -07004442 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004443 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004444}
4445
Eric Laurente0720872014-03-11 09:30:41 -07004446AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004447{
Eric Laurente552edb2014-03-10 17:42:56 -07004448 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004449 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004450 }
4451 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004452 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004453 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004454 mAvailableOutputDevices.clear();
4455 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004456 mOutputs.clear();
4457 mInputs.clear();
4458 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004459 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004460 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004461}
4462
Eric Laurente0720872014-03-11 09:30:41 -07004463status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004464{
Eric Laurent87ffa392015-05-22 10:32:38 -07004465 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004466}
4467
Eric Laurente552edb2014-03-10 17:42:56 -07004468// ---
4469
Mikhail Naganov560095b2020-03-05 16:28:57 -08004470void AudioPolicyManager::onNewAudioModulesAvailable()
4471{
Mikhail Naganova30ec142020-03-24 09:32:34 -07004472 DeviceVector newDevices;
4473 onNewAudioModulesAvailableInt(&newDevices);
4474 if (!newDevices.empty()) {
4475 nextAudioPortGeneration();
4476 mpClientInterface->onAudioPortListUpdate();
4477 }
4478}
4479
4480void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4481{
Mikhail Naganov560095b2020-03-05 16:28:57 -08004482 for (const auto& hwModule : mHwModulesAll) {
4483 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4484 continue;
4485 }
4486 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4487 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4488 ALOGW("could not open HW module %s", hwModule->getName());
4489 continue;
4490 }
4491 mHwModules.push_back(hwModule);
4492 // open all output streams needed to access attached devices
4493 // except for direct output streams that are only opened when they are actually
4494 // required by an app.
4495 // This also validates mAvailableOutputDevices list
4496 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4497 if (!outProfile->canOpenNewIo()) {
4498 ALOGE("Invalid Output profile max open count %u for profile %s",
4499 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4500 continue;
4501 }
4502 if (!outProfile->hasSupportedDevices()) {
4503 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4504 continue;
4505 }
4506 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4507 mTtsOutputAvailable = true;
4508 }
4509
4510 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4511 continue;
4512 }
4513 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4514 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4515 sp<DeviceDescriptor> supportedDevice = 0;
4516 if (supportedDevices.contains(mDefaultOutputDevice)) {
4517 supportedDevice = mDefaultOutputDevice;
4518 } else {
4519 // choose first device present in profile's SupportedDevices also part of
4520 // mAvailableOutputDevices.
4521 if (availProfileDevices.isEmpty()) {
4522 continue;
4523 }
4524 supportedDevice = availProfileDevices.itemAt(0);
4525 }
4526 if (!mOutputDevicesAll.contains(supportedDevice)) {
4527 continue;
4528 }
4529 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4530 mpClientInterface);
4531 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4532 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4533 AUDIO_STREAM_DEFAULT,
4534 AUDIO_OUTPUT_FLAG_NONE, &output);
4535 if (status != NO_ERROR) {
4536 ALOGW("Cannot open output stream for devices %s on hw module %s",
4537 supportedDevice->toString().c_str(), hwModule->getName());
4538 continue;
4539 }
4540 for (const auto &device : availProfileDevices) {
4541 // give a valid ID to an attached device once confirmed it is reachable
4542 if (!device->isAttached()) {
4543 device->attach(hwModule);
4544 mAvailableOutputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004545 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004546 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4547 }
4548 }
4549 if (mPrimaryOutput == 0 &&
4550 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4551 mPrimaryOutput = outputDesc;
4552 }
4553 addOutput(output, outputDesc);
4554 setOutputDevices(outputDesc,
4555 DeviceVector(supportedDevice),
4556 true,
4557 0,
4558 NULL);
4559 }
4560 // open input streams needed to access attached devices to validate
4561 // mAvailableInputDevices list
4562 for (const auto& inProfile : hwModule->getInputProfiles()) {
4563 if (!inProfile->canOpenNewIo()) {
4564 ALOGE("Invalid Input profile max open count %u for profile %s",
4565 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4566 continue;
4567 }
4568 if (!inProfile->hasSupportedDevices()) {
4569 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4570 continue;
4571 }
4572 // chose first device present in profile's SupportedDevices also part of
4573 // available input devices
4574 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4575 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4576 if (availProfileDevices.isEmpty()) {
4577 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4578 continue;
4579 }
4580 sp<AudioInputDescriptor> inputDesc =
4581 new AudioInputDescriptor(inProfile, mpClientInterface);
4582
4583 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4584 status_t status = inputDesc->open(nullptr,
4585 availProfileDevices.itemAt(0),
4586 AUDIO_SOURCE_MIC,
4587 AUDIO_INPUT_FLAG_NONE,
4588 &input);
4589 if (status != NO_ERROR) {
4590 ALOGW("Cannot open input stream for device %s on hw module %s",
4591 availProfileDevices.toString().c_str(),
4592 hwModule->getName());
4593 continue;
4594 }
4595 for (const auto &device : availProfileDevices) {
4596 // give a valid ID to an attached device once confirmed it is reachable
4597 if (!device->isAttached()) {
4598 device->attach(hwModule);
4599 device->importAudioPortAndPickAudioProfile(inProfile, true);
4600 mAvailableInputDevices.add(device);
Mikhail Naganova30ec142020-03-24 09:32:34 -07004601 if (newDevices) newDevices->add(device);
Mikhail Naganov560095b2020-03-05 16:28:57 -08004602 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4603 }
4604 }
4605 inputDesc->close();
4606 }
4607 }
4608}
4609
Eric Laurent98e38192018-02-15 18:31:53 -08004610void AudioPolicyManager::addOutput(audio_io_handle_t output,
4611 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004612{
Eric Laurent1c333e22014-05-20 10:48:17 -07004613 mOutputs.add(output, outputDesc);
jiabin12dc6b02019-10-01 09:38:30 -07004614 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004615 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004616 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004618}
4619
François Gaffie53615e22015-03-19 09:24:12 +01004620void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4621{
4622 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004623 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004624}
4625
Eric Laurent98e38192018-02-15 18:31:53 -08004626void AudioPolicyManager::addInput(audio_io_handle_t input,
4627 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004628{
Eric Laurent1c333e22014-05-20 10:48:17 -07004629 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004630 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004631}
Eric Laurente552edb2014-03-10 17:42:56 -07004632
François Gaffie11d30102018-11-02 16:09:09 +01004633status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004634 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004635 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004636{
François Gaffie11d30102018-11-02 16:09:09 +01004637 audio_devices_t deviceType = device->type();
jiabin6713a382019-09-12 16:29:15 -07004638 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004639 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004640
François Gaffie11d30102018-11-02 16:09:09 +01004641 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004642 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004643 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004644 }
Eric Laurente552edb2014-03-10 17:42:56 -07004645
Eric Laurent3b73df72014-03-11 09:06:29 -07004646 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 // first list already open outputs that can be routed to this device
4648 for (size_t i = 0; i < mOutputs.size(); i++) {
4649 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004650 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004651 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004652 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4653 mOutputs.keyAt(i), device->toString().c_str());
4654 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004655 }
4656 }
4657 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004658 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004659 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004660 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4661 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004662 if (profile->supportsDevice(device)) {
4663 profiles.add(profile);
4664 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4665 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004666 }
4667 }
4668 }
4669
Eric Laurent7b279bb2015-12-14 10:18:23 -08004670 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004671
Eric Laurente552edb2014-03-10 17:42:56 -07004672 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004673 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004674 return BAD_VALUE;
4675 }
4676
4677 // open outputs for matching profiles if needed. Direct outputs are also opened to
4678 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4679 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004680 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004681
4682 // nothing to do if one output is already opened for this profile
4683 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004684 for (j = 0; j < outputs.size(); j++) {
4685 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004686 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004687 // matching profile: save the sample rates, format and channel masks supported
4688 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004689 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07004690 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004691 }
Eric Laurente552edb2014-03-10 17:42:56 -07004692 break;
4693 }
4694 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004695 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004696 continue;
4697 }
4698
Eric Laurent3974e3b2017-12-07 17:58:43 -08004699 if (!profile->canOpenNewIo()) {
4700 ALOGW("Max Output number %u already opened for this profile %s",
4701 profile->maxOpenCount, profile->getTagName().c_str());
4702 continue;
4703 }
4704
Eric Laurent83efe1c2017-07-09 16:51:08 -07004705 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabineaf09f02019-08-19 15:08:30 -07004706 deviceType, address.string(), profile.get(), profile->getName().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004707 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004708 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004709 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004710 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004711
Eric Laurentfe231122017-11-17 17:48:06 -08004712 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004713 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004714 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004715 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004716 mpClientInterface->setParameters(output, String8(param));
4717 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004718 }
François Gaffie11d30102018-11-02 16:09:09 +01004719 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004720 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004721 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004722 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004723 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004724 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004725 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004726 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004727 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4728 profile->pickAudioProfile(
4729 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004730 config.offload_info.sample_rate = config.sample_rate;
4731 config.offload_info.channel_mask = config.channel_mask;
4732 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004733
François Gaffie11d30102018-11-02 16:09:09 +01004734 status_t status = desc->open(&config, DeviceVector(device),
4735 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004736 AUDIO_OUTPUT_FLAG_NONE, &output);
4737 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004738 output = AUDIO_IO_HANDLE_NONE;
4739 }
Eric Laurentd4692962014-05-05 18:13:44 -07004740 }
4741
Eric Laurentcf2c0212014-07-25 16:20:43 -07004742 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004743 addOutput(output, desc);
François Gaffie11d30102018-11-02 16:09:09 +01004744 if (device_distinguishes_on_address(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004745 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004746 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
4747 == NO_ERROR) {
François Gaffieb141c522018-03-12 11:47:40 +01004748 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08004749 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004750 } else {
4751 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004752 address.string());
4753 }
François Gaffie036e1e92015-03-19 10:16:24 +01004754
Eric Laurent87ffa392015-05-22 10:32:38 -07004755 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4756 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004757 // no duplicated output for direct outputs and
4758 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004759 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004760
Eric Laurentd4692962014-05-05 18:13:44 -07004761 //TODO: configure audio effect output stage here
4762
4763 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004764 sp<SwAudioOutputDescriptor> dupOutputDesc =
4765 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4766 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4767 &duplicatedOutput);
4768 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004769 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004770 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004771 } else {
4772 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004773 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004774 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004775 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004777 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004778 }
Eric Laurente552edb2014-03-10 17:42:56 -07004779 }
4780 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004781 } else {
4782 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004783 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004784 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004785 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004786 profiles.removeAt(profile_index);
4787 profile_index--;
4788 } else {
4789 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004790 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01004791 if (audio_device_is_digital(deviceType)) {
jiabindff2a4f2019-09-10 14:29:54 -07004792 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004793 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004794
François Gaffie11d30102018-11-02 16:09:09 +01004795 if (device_distinguishes_on_address(deviceType)) {
4796 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4797 device->toString().c_str());
4798 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4799 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004800 }
Eric Laurente552edb2014-03-10 17:42:56 -07004801 ALOGV("checkOutputsForDevice(): adding output %d", output);
4802 }
4803 }
4804
4805 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004806 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004807 return BAD_VALUE;
4808 }
Eric Laurentd4692962014-05-05 18:13:44 -07004809 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004810 // check if one opened output is not needed any more after disconnecting one device
4811 for (size_t i = 0; i < mOutputs.size(); i++) {
4812 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004813 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004814 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004815 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabin12dc6b02019-10-01 09:38:30 -07004816 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004817 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01004818 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004819 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4820 mOutputs.keyAt(i));
4821 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004822 }
Eric Laurente552edb2014-03-10 17:42:56 -07004823 }
4824 }
Eric Laurentd4692962014-05-05 18:13:44 -07004825 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004826 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004827 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4828 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004829 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004830 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08004831 "clearing direct output profile %zu on module %s",
4832 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004833 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004834 }
4835 }
4836 }
4837 }
4838 return NO_ERROR;
4839}
4840
François Gaffie11d30102018-11-02 16:09:09 +01004841status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07004842 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07004843{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004844 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004845
François Gaffie11d30102018-11-02 16:09:09 +01004846 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004847 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004848 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004849 }
4850
Eric Laurentd4692962014-05-05 18:13:44 -07004851 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07004852 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004853 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004854 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004855 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004856 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004857 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004858 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08004859
François Gaffie11d30102018-11-02 16:09:09 +01004860 if (profile->supportsDevice(device)) {
4861 profiles.add(profile);
4862 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4863 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07004864 }
4865 }
4866 }
4867
Eric Laurent0dd51852019-04-19 18:18:58 -07004868 if (profiles.isEmpty()) {
4869 ALOGW("%s: No input profile available for device %s",
4870 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004871 return BAD_VALUE;
4872 }
4873
4874 // open inputs for matching profiles if needed. Direct inputs are also opened to
4875 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4876 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4877
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08004879
Eric Laurentd4692962014-05-05 18:13:44 -07004880 // nothing to do if one input is already opened for this profile
4881 size_t input_index;
4882 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4883 desc = mInputs.valueAt(input_index);
4884 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01004885 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07004886 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004887 }
Eric Laurentd4692962014-05-05 18:13:44 -07004888 break;
4889 }
4890 }
4891 if (input_index != mInputs.size()) {
4892 continue;
4893 }
4894
Eric Laurent3974e3b2017-12-07 17:58:43 -08004895 if (!profile->canOpenNewIo()) {
4896 ALOGW("Max Input number %u already opened for this profile %s",
4897 profile->maxOpenCount, profile->getTagName().c_str());
4898 continue;
4899 }
4900
Eric Laurentfe231122017-11-17 17:48:06 -08004901 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004902 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004903 status_t status = desc->open(nullptr,
4904 device,
Eric Laurentfe231122017-11-17 17:48:06 -08004905 AUDIO_SOURCE_MIC,
4906 AUDIO_INPUT_FLAG_NONE,
4907 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07004908
Eric Laurentcf2c0212014-07-25 16:20:43 -07004909 if (status == NO_ERROR) {
jiabin6713a382019-09-12 16:29:15 -07004910 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004911 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004912 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004913 mpClientInterface->setParameters(input, String8(param));
4914 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004915 }
François Gaffie11d30102018-11-02 16:09:09 +01004916 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004917 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004918 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004919 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004920 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004921 }
4922
Eric Laurent0dd51852019-04-19 18:18:58 -07004923 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004924 addInput(input, desc);
4925 }
4926 } // endif input != 0
4927
Eric Laurentcf2c0212014-07-25 16:20:43 -07004928 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01004929 ALOGW("%s could not open input for device %s", __func__,
4930 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004931 profiles.removeAt(profile_index);
4932 profile_index--;
4933 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004934 if (audio_device_is_digital(device->type())) {
jiabindff2a4f2019-09-10 14:29:54 -07004935 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004936 }
Eric Laurentd4692962014-05-05 18:13:44 -07004937 ALOGV("checkInputsForDevice(): adding input %d", input);
4938 }
4939 } // end scan profiles
4940
4941 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004942 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07004943 return BAD_VALUE;
4944 }
4945 } else {
4946 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07004947 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08004948 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07004949 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004950 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07004951 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004952 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01004953 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004954 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4955 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01004956 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004957 }
4958 }
4959 }
4960 } // end disconnect
4961
4962 return NO_ERROR;
4963}
4964
4965
Eric Laurente0720872014-03-11 09:30:41 -07004966void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004967{
4968 ALOGV("closeOutput(%d)", output);
4969
François Gaffie1c878552018-11-22 16:53:21 +01004970 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
4971 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004972 ALOGW("closeOutput() unknown output %d", output);
4973 return;
4974 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07004975 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01004976 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08004977
Eric Laurente552edb2014-03-10 17:42:56 -07004978 // look for duplicated outputs connected to the output being removed.
4979 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01004980 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
4981 if (dupOutput->isDuplicated() &&
4982 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
4983 sp<SwAudioOutputDescriptor> remainingOutput =
4984 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07004985 // As all active tracks on duplicated output will be deleted,
4986 // and as they were also referenced on the other output, the reference
4987 // count for their stream type must be adjusted accordingly on
4988 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01004989 const bool wasActive = remainingOutput->isActive();
4990 // Note: no-op on the closing output where all clients has already been set inactive
4991 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08004992 // stop() will be a no op if the output is still active but is needed in case all
4993 // active streams refcounts where cleared above
4994 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01004995 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004996 }
Eric Laurente552edb2014-03-10 17:42:56 -07004997 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4998 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4999
5000 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005001 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005002 }
5003 }
5004
Eric Laurent05b90f82014-08-27 15:32:29 -07005005 nextAudioPortGeneration();
5006
François Gaffie1c878552018-11-22 16:53:21 +01005007 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005008 if (index >= 0) {
5009 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005010 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5011 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005012 mAudioPatches.removeItemsAt(index);
5013 mpClientInterface->onAudioPatchListUpdate();
5014 }
5015
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005016 if (closingOutputWasActive) {
5017 closingOutput->stop();
5018 }
François Gaffie1c878552018-11-22 16:53:21 +01005019 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005020
François Gaffie53615e22015-03-19 09:24:12 +01005021 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005022 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005023
5024 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5025 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005026 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005027 bool directOutputOpen = false;
5028 for (size_t i = 0; i < mOutputs.size(); i++) {
5029 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5030 directOutputOpen = true;
5031 break;
5032 }
5033 }
5034 if (!directOutputOpen) {
5035 ALOGV("no direct outputs open, reset MSD patch");
5036 setMsdPatch();
5037 }
5038 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07005039
5040 cleanUpEffectsForIo(output);
Eric Laurent05b90f82014-08-27 15:32:29 -07005041}
5042
5043void AudioPolicyManager::closeInput(audio_io_handle_t input)
5044{
5045 ALOGV("closeInput(%d)", input);
5046
5047 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5048 if (inputDesc == NULL) {
5049 ALOGW("closeInput() unknown input %d", input);
5050 return;
5051 }
5052
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005054
François Gaffie11d30102018-11-02 16:09:09 +01005055 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005056 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005057 if (index >= 0) {
5058 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005059 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5060 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005061 mAudioPatches.removeItemsAt(index);
5062 mpClientInterface->onAudioPatchListUpdate();
5063 }
5064
Eric Laurentfe231122017-11-17 17:48:06 -08005065 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005066 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005067
François Gaffie11d30102018-11-02 16:09:09 +01005068 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5069 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005070 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
5071 SoundTrigger::setCaptureState(false);
5072 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07005073
5074 cleanUpEffectsForIo(input);
Eric Laurente552edb2014-03-10 17:42:56 -07005075}
5076
François Gaffie11d30102018-11-02 16:09:09 +01005077SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5078 const DeviceVector &devices,
5079 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005080{
5081 SortedVector<audio_io_handle_t> outputs;
5082
François Gaffie11d30102018-11-02 16:09:09 +01005083 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005084 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005085 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005086 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005087 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005088 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin12dc6b02019-10-01 09:38:30 -07005089 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005090 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005091 outputs.add(openOutputs.keyAt(i));
5092 }
5093 }
5094 return outputs;
5095}
5096
Mikhail Naganov37977152018-07-11 15:54:44 -07005097void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5098{
5099 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5100 // output is suspended before any tracks are moved to it
5101 checkA2dpSuspend();
5102 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005103 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005104 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005105 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005106 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005107 setMsdPatch();
5108 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005109}
5110
François Gaffiec005e562018-11-06 15:04:49 +01005111bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5112 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005113{
François Gaffiec005e562018-11-06 15:04:49 +01005114 return mEngine->getProductStrategyForAttributes(lAttr) ==
5115 mEngine->getProductStrategyForAttributes(rAttr);
5116}
5117
5118void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5119{
5120 auto psId = mEngine->getProductStrategyForAttributes(attr);
5121
5122 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5123 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi2deb4782019-11-01 11:04:15 -07005124
François Gaffie11d30102018-11-02 16:09:09 +01005125 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5126 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005127
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005128 // also take into account external policy-related changes: add all outputs which are
5129 // associated with policies in the "before" and "after" output vectors
François Gaffiec005e562018-11-06 15:04:49 +01005130 ALOGVV("%s(): policy related outputs", __func__);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005131 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005132 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005133 if (desc != 0 && desc->mPolicyMix != NULL) {
5134 srcOutputs.add(desc->mIoHandle);
5135 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
5136 }
5137 }
5138 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005139 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005140 if (desc != 0 && desc->mPolicyMix != NULL) {
5141 dstOutputs.add(desc->mIoHandle);
5142 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
5143 }
5144 }
5145
François Gaffiec005e562018-11-06 15:04:49 +01005146 if (srcOutputs != dstOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005147 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5148 // audio from invalidated tracks will be rendered when unmuting
5149 uint32_t maxLatency = 0;
5150 for (audio_io_handle_t srcOut : srcOutputs) {
5151 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
5152 if (desc != 0 && maxLatency < desc->latency()) {
5153 maxLatency = desc->latency();
5154 }
5155 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005156 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005157 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005158 std::to_string(srcOutputs[0]).c_str(),
5159 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005160 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005161 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005162 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
François Gaffiec005e562018-11-06 15:04:49 +01005163 if (desc != 0 && desc->isStrategyActive(psId)) {
5164 setStrategyMute(psId, true, desc);
5165 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005166 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005167 }
François Gaffiec005e562018-11-06 15:04:49 +01005168 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005169 if (source != 0){
5170 connectAudioSource(source);
5171 }
Eric Laurente552edb2014-03-10 17:42:56 -07005172 }
5173
François Gaffiec005e562018-11-06 15:04:49 +01005174 // Move effects associated to this stream from previous output to new output
5175 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005176 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005177 }
François Gaffiec005e562018-11-06 15:04:49 +01005178 // Move tracks associated to this stream (and linked) from previous output to new output
5179 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5180 mpClientInterface->invalidateStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005181 }
5182 }
5183}
5184
Eric Laurente0720872014-03-11 09:30:41 -07005185void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005186{
François Gaffiec005e562018-11-06 15:04:49 +01005187 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5188 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5189 checkOutputForAttributes(attributes);
5190 }
Eric Laurente552edb2014-03-10 17:42:56 -07005191}
5192
Kevin Rocard153f92d2018-12-18 18:33:28 -08005193void AudioPolicyManager::checkSecondaryOutputs() {
5194 std::set<audio_stream_type_t> streamsToInvalidate;
5195 for (size_t i = 0; i < mOutputs.size(); i++) {
5196 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5197 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005198 sp<SwAudioOutputDescriptor> desc;
5199 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
Kevin Rocard94114a22019-04-01 19:38:23 -07005200 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5201 client->flags(), desc, &secondaryDescs);
5202 if (status != OK ||
5203 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005204 client->getSecondaryOutputs().end(),
5205 secondaryDescs.begin(), secondaryDescs.end())) {
5206 streamsToInvalidate.insert(client->stream());
5207 }
5208 }
5209 }
5210 for (audio_stream_type_t stream : streamsToInvalidate) {
5211 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5212 mpClientInterface->invalidateStream(stream);
5213 }
5214}
5215
Eric Laurente0720872014-03-11 09:30:41 -07005216void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005217{
François Gaffie53615e22015-03-19 09:24:12 +01005218 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005219 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005220 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005221 return;
5222 }
5223
Eric Laurent3a4311c2014-03-17 12:00:47 -07005224 bool isScoConnected =
jiabin12dc6b02019-10-01 09:38:30 -07005225 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5226 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurentf732e072016-08-03 19:30:28 -07005227
5228 // if suspended, restore A2DP output if:
5229 // ((SCO device is NOT connected) ||
5230 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
5231 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005232 //
Eric Laurentf732e072016-08-03 19:30:28 -07005233 // if not suspended, suspend A2DP output if:
5234 // (SCO device is connected) &&
5235 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
5236 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005237 //
5238 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005239 if (!isScoConnected ||
5240 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
5241 AUDIO_POLICY_FORCE_BT_SCO) &&
5242 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
5243 AUDIO_POLICY_FORCE_BT_SCO) &&
5244 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005245 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005246
5247 mpClientInterface->restoreOutput(a2dpOutput);
5248 mA2dpSuspended = false;
5249 }
5250 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005251 if (isScoConnected &&
5252 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
5253 AUDIO_POLICY_FORCE_BT_SCO) ||
5254 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
5255 AUDIO_POLICY_FORCE_BT_SCO) ||
5256 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005257 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005258
5259 mpClientInterface->suspendOutput(a2dpOutput);
5260 mA2dpSuspended = true;
5261 }
5262 }
5263}
5264
François Gaffie11d30102018-11-02 16:09:09 +01005265DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5266 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005267{
François Gaffie11d30102018-11-02 16:09:09 +01005268 DeviceVector devices;
5269
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005270 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 if (index >= 0) {
5272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005273 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005274 ALOGV("%s device %s forced by patch %d", __func__,
5275 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5276 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 }
5278 }
5279
Dean Wheatley514b4312020-06-17 21:45:00 +10005280 // Do not retrieve engine device for outputs through MSD
5281 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5282 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5283 return outputDesc->devices();
5284 }
5285
Eric Laurent97ac8712018-07-27 18:59:02 -07005286 // Honor explicit routing requests only if no client using default routing is active on this
5287 // input: a specific app can not force routing for other apps by setting a preferred device.
5288 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005289 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005290 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005291 if (device != nullptr) {
5292 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005293 }
5294
François Gaffiea807ef92018-11-05 10:44:33 +01005295 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5296 // of setForceUse / Default Bus device here
5297 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5298 if (device != nullptr) {
5299 return DeviceVector(device);
5300 }
5301
François Gaffiec005e562018-11-06 15:04:49 +01005302 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5303 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5304 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005305
François Gaffiec005e562018-11-06 15:04:49 +01005306 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005307 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5308 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005309 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005310 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5311 outputDesc->isStrategyActive(productStrategy)) {
5312 // Retrieval of devices for voice DL is done on primary output profile, cannot
5313 // check the route (would force modifying configuration file for this profile)
5314 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5315 break;
5316 }
Eric Laurente552edb2014-03-10 17:42:56 -07005317 }
François Gaffiec005e562018-11-06 15:04:49 +01005318 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005319 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005320}
5321
François Gaffie11d30102018-11-02 16:09:09 +01005322sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5323 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005324{
François Gaffie11d30102018-11-02 16:09:09 +01005325 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005326
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005327 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 if (index >= 0) {
5329 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005330 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005331 ALOGV("getNewInputDevice() device %s forced by patch %d",
5332 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5333 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005334 }
5335 }
5336
Eric Laurent97ac8712018-07-27 18:59:02 -07005337 // Honor explicit routing requests only if no client using default routing is active on this
5338 // input: a specific app can not force routing for other apps by setting a preferred device.
5339 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005340 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5341 if (device != nullptr) {
5342 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005343 }
5344
Eric Laurentdc95a252018-04-12 12:46:56 -07005345 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005346 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005347 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5348 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5349 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005350 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005351 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005352 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005353 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005354
Eric Laurente552edb2014-03-10 17:42:56 -07005355 return device;
5356}
5357
Eric Laurent794fde22016-03-11 09:50:45 -08005358bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5359 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005360 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005361}
5362
Eric Laurente0720872014-03-11 09:30:41 -07005363audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005364 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005365 // getOutputDevicesForStream's behavior for invalid streams.
5366 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5367 // device for music stream), but we want to return the empty set.
5368 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 return AUDIO_DEVICE_NONE;
5370 }
François Gaffie11d30102018-11-02 16:09:09 +01005371 DeviceVector activeDevices;
5372 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005373 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5374 curStream = (audio_stream_type_t) (curStream + 1)) {
5375 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005376 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005377 }
François Gaffiec005e562018-11-06 15:04:49 +01005378 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005379 devices.merge(curDevices);
5380 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005381 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005382 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005383 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005384 }
5385 }
Eric Laurente552edb2014-03-10 17:42:56 -07005386 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005387
Eric Laurentb0688d62018-08-14 15:49:18 -07005388 // Favor devices selected on active streams if any to report correct device in case of
5389 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005390 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005391 devices = activeDevices;
5392 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005393 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5394 and doesn't really need to.*/
jiabin12dc6b02019-10-01 09:38:30 -07005395 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005396 if (!speakerSafeDevices.isEmpty()) {
jiabin12dc6b02019-10-01 09:38:30 -07005397 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005398 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005399 }
jiabin12dc6b02019-10-01 09:38:30 -07005400 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5401 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005402}
5403
Eric Laurente0720872014-03-11 09:30:41 -07005404void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005405 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005406 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005407 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005408 updateDevicesAndOutputs();
5409 break;
5410 default:
5411 break;
5412 }
5413}
5414
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005415uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005416
5417 // skip beacon mute management if a dedicated TTS output is available
5418 if (mTtsOutputAvailable) {
5419 return 0;
5420 }
5421
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005422 switch(event) {
5423 case STARTING_OUTPUT:
5424 mBeaconMuteRefCount++;
5425 break;
5426 case STOPPING_OUTPUT:
5427 if (mBeaconMuteRefCount > 0) {
5428 mBeaconMuteRefCount--;
5429 }
5430 break;
5431 case STARTING_BEACON:
5432 mBeaconPlayingRefCount++;
5433 break;
5434 case STOPPING_BEACON:
5435 if (mBeaconPlayingRefCount > 0) {
5436 mBeaconPlayingRefCount--;
5437 }
5438 break;
5439 }
5440
5441 if (mBeaconMuteRefCount > 0) {
5442 // any playback causes beacon to be muted
5443 return setBeaconMute(true);
5444 } else {
5445 // no other playback: unmute when beacon starts playing, mute when it stops
5446 return setBeaconMute(mBeaconPlayingRefCount == 0);
5447 }
5448}
5449
5450uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5451 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5452 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5453 // keep track of muted state to avoid repeating mute/unmute operations
5454 if (mBeaconMuted != mute) {
5455 // mute/unmute AUDIO_STREAM_TTS on all outputs
5456 ALOGV("\t muting %d", mute);
5457 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005458 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005459 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005460 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin12dc6b02019-10-01 09:38:30 -07005461 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005462 const uint32_t latency = desc->latency() * 2;
5463 if (latency > maxLatency) {
5464 maxLatency = latency;
5465 }
5466 }
5467 mBeaconMuted = mute;
5468 return maxLatency;
5469 }
5470 return 0;
5471}
5472
Eric Laurente0720872014-03-11 09:30:41 -07005473void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005474{
François Gaffiec005e562018-11-06 15:04:49 +01005475 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005476 mPreviousOutputs = mOutputs;
5477}
5478
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005479uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005480 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005481 uint32_t delayMs)
5482{
5483 // mute/unmute strategies using an incompatible device combination
5484 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5485 // if unmuting, unmute only after the specified delay
5486 if (outputDesc->isDuplicated()) {
5487 return 0;
5488 }
5489
5490 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005491 DeviceVector devices = outputDesc->devices();
5492 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005493
François Gaffiec005e562018-11-06 15:04:49 +01005494 auto productStrategies = mEngine->getOrderedProductStrategies();
5495 for (const auto &productStrategy : productStrategies) {
5496 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5497 DeviceVector curDevices =
5498 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5499 curDevices = curDevices.filter(outputDesc->supportedDevices());
5500 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005501 bool doMute = false;
5502
François Gaffiec005e562018-11-06 15:04:49 +01005503 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005504 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005505 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5506 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005507 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005508 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005509 }
Eric Laurent99401132014-05-07 19:48:15 -07005510 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005511 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005512 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005513 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005514 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005515 continue;
5516 }
François Gaffiec005e562018-11-06 15:04:49 +01005517 ALOGVV("%s() %s (curDevice %s)", __func__,
5518 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5519 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5520 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005521 if (mute) {
5522 // FIXME: should not need to double latency if volume could be applied
5523 // immediately by the audioflinger mixer. We must account for the delay
5524 // between now and the next time the audioflinger thread for this output
5525 // will process a buffer (which corresponds to one buffer size,
5526 // usually 1/2 or 1/4 of the latency).
5527 if (muteWaitMs < desc->latency() * 2) {
5528 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005529 }
5530 }
5531 }
5532 }
5533 }
5534 }
5535
Eric Laurent99401132014-05-07 19:48:15 -07005536 // temporary mute output if device selection changes to avoid volume bursts due to
5537 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005538 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005539 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5540 // temporary mute duration is conservatively set to 4 times the reported latency
5541 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5542 if (muteWaitMs < tempMuteWaitMs) {
5543 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005544 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005545 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5546 // make sure that we do not start the temporary mute period too early in case of
5547 // delayed device change
5548 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5549 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005550 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005551 }
5552 }
5553
Eric Laurente552edb2014-03-10 17:42:56 -07005554 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5555 if (muteWaitMs > delayMs) {
5556 muteWaitMs -= delayMs;
5557 usleep(muteWaitMs * 1000);
5558 return muteWaitMs;
5559 }
5560 return 0;
5561}
5562
François Gaffie11d30102018-11-02 16:09:09 +01005563uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5564 const DeviceVector &devices,
5565 bool force,
5566 int delayMs,
5567 audio_patch_handle_t *patchHandle,
5568 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005569{
François Gaffie11d30102018-11-02 16:09:09 +01005570 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005571 uint32_t muteWaitMs;
5572
5573 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005574 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5575 nullptr /* patchHandle */, requiresMuteCheck);
5576 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5577 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005578 return muteWaitMs;
5579 }
Eric Laurente552edb2014-03-10 17:42:56 -07005580
5581 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005582 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005583 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005584
François Gaffie11d30102018-11-02 16:09:09 +01005585 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005586 // output profile or if new device is not supported AND previous device(s) is(are) still
5587 // available (otherwise reset device must be done on the output)
5588 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5589 !mAvailableOutputDevices.filter(prevDevices).empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005590 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5591 return 0;
5592 }
Eric Laurente552edb2014-03-10 17:42:56 -07005593
François Gaffie11d30102018-11-02 16:09:09 +01005594 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5595
5596 if (!filteredDevices.isEmpty()) {
5597 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005598 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005599
5600 // if the outputs are not materially active, there is no need to mute.
5601 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005602 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005603 } else {
5604 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5605 muteWaitMs = 0;
5606 }
Eric Laurente552edb2014-03-10 17:42:56 -07005607
5608 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005609 // the requested device is AUDIO_DEVICE_NONE
5610 // OR the requested device is the same as current device
5611 // AND force is not specified
5612 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005613 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005614 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005615 !force && outputDesc->getPatchHandle() != 0) {
5616 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5617 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005618 return muteWaitMs;
5619 }
5620
François Gaffie11d30102018-11-02 16:09:09 +01005621 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005622
Eric Laurente552edb2014-03-10 17:42:56 -07005623 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005624 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005625 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005626 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005627 PatchBuilder patchBuilder;
5628 patchBuilder.addSource(outputDesc);
5629 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5630 for (const auto &filteredDevice : filteredDevices) {
5631 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005632 }
5633
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005634 // Add half reported latency to delayMs when muteWaitMs is null in order
5635 // to avoid disordered sequence of muting volume and changing devices.
5636 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5637 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005638 }
Eric Laurente552edb2014-03-10 17:42:56 -07005639
5640 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005641 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005642
5643 return muteWaitMs;
5644}
5645
Eric Laurentc75307b2015-03-17 15:29:32 -07005646status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005647 int delayMs,
5648 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005649{
Eric Laurent6a94d692014-05-20 11:18:06 -07005650 ssize_t index;
5651 if (patchHandle) {
5652 index = mAudioPatches.indexOfKey(*patchHandle);
5653 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005654 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005655 }
5656 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005657 return INVALID_OPERATION;
5658 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005659 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005660 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005661 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005662 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01005663 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005664 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005665 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005666 return status;
5667}
5668
5669status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005670 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005671 bool force,
5672 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005673{
5674 status_t status = NO_ERROR;
5675
Eric Laurent1f2f2232014-06-02 12:01:23 -07005676 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005677 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5678 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005679
François Gaffie11d30102018-11-02 16:09:09 +01005680 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005681 PatchBuilder patchBuilder;
5682 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005683 // AUDIO_SOURCE_HOTWORD is for internal use only:
5684 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005685 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5686 auto result = usecase;
5687 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5688 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5689 }
5690 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005691 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005692 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005693 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005694 }
5695 }
5696 return status;
5697}
5698
Eric Laurent6a94d692014-05-20 11:18:06 -07005699status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5700 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005701{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005702 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005703 ssize_t index;
5704 if (patchHandle) {
5705 index = mAudioPatches.indexOfKey(*patchHandle);
5706 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005707 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005708 }
5709 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005710 return INVALID_OPERATION;
5711 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005712 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01005713 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005714 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005715 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffiead447b72019-11-18 15:50:22 +01005716 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005717 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005718 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005719 return status;
5720}
5721
François Gaffie11d30102018-11-02 16:09:09 +01005722sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01005723 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005724 audio_format_t& format,
5725 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005726 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005727{
5728 // Choose an input profile based on the requested capture parameters: select the first available
5729 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005730 //
5731 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5732 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005733
Glenn Kasten730b9262018-03-29 15:01:26 -07005734 sp<IOProfile> firstInexact;
5735 uint32_t updatedSamplingRate = 0;
5736 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5737 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005738 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005739 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005740 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07005741 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01005742 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07005743 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005744 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07005745 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07005746 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07005747 &channelMask /*updatedChannelMask*/,
5748 // FIXME ugly cast
5749 (audio_output_flags_t) flags,
5750 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005751 return profile;
5752 }
François Gaffie11d30102018-11-02 16:09:09 +01005753 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07005754 samplingRate,
5755 &updatedSamplingRate,
5756 format,
5757 &updatedFormat,
5758 channelMask,
5759 &updatedChannelMask,
5760 // FIXME ugly cast
5761 (audio_output_flags_t) flags,
5762 false /*exactMatchRequiredForInputFlags*/)) {
5763 firstInexact = profile;
5764 }
5765
Eric Laurente552edb2014-03-10 17:42:56 -07005766 }
5767 }
Glenn Kasten730b9262018-03-29 15:01:26 -07005768 if (firstInexact != nullptr) {
5769 samplingRate = updatedSamplingRate;
5770 format = updatedFormat;
5771 channelMask = updatedChannelMask;
5772 return firstInexact;
5773 }
Eric Laurente552edb2014-03-10 17:42:56 -07005774 return NULL;
5775}
5776
François Gaffieaaac0fd2018-11-22 17:56:39 +01005777float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
5778 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005779 int index,
jiabin12dc6b02019-10-01 09:38:30 -07005780 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07005781{
jiabin12dc6b02019-10-01 09:38:30 -07005782 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005783
5784 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5785 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5786 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5787 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01005788 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5789 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
5790 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
5791 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005792 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005793
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005794 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01005795 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
5796 mOutputs.isActive(ringVolumeSrc, 0)) {
5797 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin12dc6b02019-10-01 09:38:30 -07005798 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005799 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005800 }
5801
Eric Laurentdcd4ab12018-06-29 17:45:13 -07005802 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01005803 if ((volumeSource != callVolumeSrc && (isInCall() ||
5804 mOutputs.isActiveLocally(callVolumeSrc))) &&
5805 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
5806 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
5807 volumeSource == alarmVolumeSrc ||
5808 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
5809 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5810 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005811 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005812 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin12dc6b02019-10-01 09:38:30 -07005813 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005814 const float maxVoiceVolDb =
jiabin12dc6b02019-10-01 09:38:30 -07005815 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07005816 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07005817 // FIXME: Workaround for call screening applications until a proper audio mode is defined
5818 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
5819 // programmatically muted.
5820 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
5821 // 0. We don't want to cap volume when the system has programmatically muted the voice call
5822 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi86903e02019-07-11 14:55:16 -07005823 bool exemptFromCapping =
5824 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
5825 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07005826 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
5827 volumeSource, volumeDb);
5828 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01005829 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
5830 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
5831 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07005832 }
5833 }
Eric Laurente552edb2014-03-10 17:42:56 -07005834 // if a headset is connected, apply the following rules to ring tones and notifications
5835 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005836 // - always attenuate notifications volume by 6dB
5837 // - attenuate ring tones volume by 6dB unless music is not playing and
5838 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005839 // - if music is playing, always limit the volume to current music volume,
5840 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin12dc6b02019-10-01 09:38:30 -07005841 if (!Intersection(deviceTypes,
5842 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
5843 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurent7a62f292020-08-07 10:51:53 -07005844 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
5845 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005846 ((volumeSource == alarmVolumeSrc ||
5847 volumeSource == ringVolumeSrc) ||
5848 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
5849 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
5850 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5851 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5852 curves.canBeMuted()) {
5853
Eric Laurente552edb2014-03-10 17:42:56 -07005854 // when the phone is ringing we must consider that music could have been paused just before
5855 // by the music application and behave as if music was active if the last music track was
5856 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005857 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005858 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01005859 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin12dc6b02019-10-01 09:38:30 -07005860 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01005861 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5862 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01005863 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin12dc6b02019-10-01 09:38:30 -07005864 float musicVolDb = computeVolume(musicCurves,
5865 musicVolumeSrc,
5866 musicCurves.getVolumeIndex(musicDevice),
5867 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01005868 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5869 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5870 if (volumeDb > minVolDb) {
5871 volumeDb = minVolDb;
5872 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07005873 }
jiabin12dc6b02019-10-01 09:38:30 -07005874 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
5875 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005876 // on A2DP, also ensure notification volume is not too low compared to media when
5877 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01005878 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01005879 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin12dc6b02019-10-01 09:38:30 -07005880 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
5881 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005882 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5883 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005884 }
5885 }
jiabin12dc6b02019-10-01 09:38:30 -07005886 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01005887 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01005888 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005889 }
5890 }
5891
François Gaffie43c73442018-11-08 08:21:55 +01005892 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07005893}
5894
Eric Laurent3839bc02018-07-10 18:33:34 -07005895int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005896 VolumeSource fromVolumeSource,
5897 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07005898{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005899 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07005900 return srcIndex;
5901 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01005902 auto &srcCurves = getVolumeCurves(fromVolumeSource);
5903 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005904 float minSrc = (float)srcCurves.getVolumeIndexMin();
5905 float maxSrc = (float)srcCurves.getVolumeIndexMax();
5906 float minDst = (float)dstCurves.getVolumeIndexMin();
5907 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07005908
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08005909 // preserve mute request or correct range
5910 if (srcIndex < minSrc) {
5911 if (srcIndex == 0) {
5912 return 0;
5913 }
5914 srcIndex = minSrc;
5915 } else if (srcIndex > maxSrc) {
5916 srcIndex = maxSrc;
5917 }
Eric Laurent3839bc02018-07-10 18:33:34 -07005918 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5919}
5920
François Gaffieaaac0fd2018-11-22 17:56:39 +01005921status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
5922 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005923 int index,
5924 const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07005925 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08005926 int delayMs,
5927 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005928{
François Gaffieaaac0fd2018-11-22 17:56:39 +01005929 // do not change actual attributes volume if the attributes is muted
5930 if (outputDesc->isMuted(volumeSource)) {
5931 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
5932 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07005933 return NO_ERROR;
5934 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005935 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5936 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
5937 bool isVoiceVolSrc = callVolSrc == volumeSource;
5938 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
5939
François Gaffie2110e042015-03-24 08:41:51 +01005940 audio_policy_forced_cfg_t forceUseForComm =
5941 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005942 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01005943 // if sco and call follow same curves, bypass forceUseForComm
5944 if ((callVolSrc != btScoVolSrc) &&
5945 ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5946 (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
5947 ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
5948 volumeSource, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005949 return INVALID_OPERATION;
5950 }
jiabin12dc6b02019-10-01 09:38:30 -07005951 if (deviceTypes.empty()) {
5952 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07005953 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005954
jiabin12dc6b02019-10-01 09:38:30 -07005955 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
5956 if (outputDesc->isFixedVolume(deviceTypes) ||
HW Leeda7581e2018-05-22 18:31:34 +08005957 // Force VoIP volume to max for bluetooth SCO
jiabin12dc6b02019-10-01 09:38:30 -07005958
5959 ((isVoiceVolSrc || isBtScoVolSrc) &&
5960 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005961 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005962 }
jiabin12dc6b02019-10-01 09:38:30 -07005963 outputDesc->setVolume(
5964 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07005965
François Gaffieaaac0fd2018-11-22 17:56:39 +01005966 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07005967 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07005968 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01005969 if (isVoiceVolSrc) {
5970 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07005971 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07005972 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07005973 }
Eric Laurent18fba842016-03-31 14:41:26 -07005974 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005975 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5976 mLastVoiceVolume = voiceVolume;
5977 }
5978 }
Eric Laurente552edb2014-03-10 17:42:56 -07005979 return NO_ERROR;
5980}
5981
Eric Laurentc75307b2015-03-17 15:29:32 -07005982void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07005983 const DeviceTypeSet& deviceTypes,
5984 int delayMs,
5985 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005986{
Francois Gaffie5992b182020-03-20 14:55:14 +01005987 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01005988 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
5989 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
5990 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin12dc6b02019-10-01 09:38:30 -07005991 curves.getVolumeIndex(deviceTypes),
5992 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005993 }
5994}
5995
François Gaffiec005e562018-11-06 15:04:49 +01005996void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5997 bool on,
5998 const sp<AudioOutputDescriptor>& outputDesc,
5999 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006000 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006001{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006002 std::vector<VolumeSource> sourcesToMute;
6003 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6004 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6005 toString(attributes).c_str(), on, outputDesc->getId());
6006 VolumeSource source = toVolumeSource(attributes);
6007 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6008 sourcesToMute.push_back(source);
6009 }
Eric Laurente552edb2014-03-10 17:42:56 -07006010 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006011 for (auto source : sourcesToMute) {
jiabin12dc6b02019-10-01 09:38:30 -07006012 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006013 }
6014
Eric Laurente552edb2014-03-10 17:42:56 -07006015}
6016
François Gaffieaaac0fd2018-11-22 17:56:39 +01006017void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6018 bool on,
6019 const sp<AudioOutputDescriptor>& outputDesc,
6020 int delayMs,
jiabin12dc6b02019-10-01 09:38:30 -07006021 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006022{
jiabin12dc6b02019-10-01 09:38:30 -07006023 if (deviceTypes.empty()) {
6024 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006025 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006026 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006027 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006028 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006029 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006030 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6031 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6032 AUDIO_POLICY_FORCE_NONE))) {
jiabin12dc6b02019-10-01 09:38:30 -07006033 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006034 }
6035 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006036 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6037 // ignored
6038 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006039 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006040 if (!outputDesc->isMuted(volumeSource)) {
6041 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006042 return;
6043 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006044 if (outputDesc->decMuteCount(volumeSource) == 0) {
6045 checkAndSetVolume(curves, volumeSource,
jiabin12dc6b02019-10-01 09:38:30 -07006046 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006047 outputDesc,
jiabin12dc6b02019-10-01 09:38:30 -07006048 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006049 delayMs);
6050 }
6051 }
6052}
6053
François Gaffie53615e22015-03-19 09:24:12 +01006054bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6055{
François Gaffiec005e562018-11-06 15:04:49 +01006056 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006057 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6058 return true;
6059 }
6060
6061 // has known usage?
6062 switch (paa->usage) {
6063 case AUDIO_USAGE_UNKNOWN:
6064 case AUDIO_USAGE_MEDIA:
6065 case AUDIO_USAGE_VOICE_COMMUNICATION:
6066 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6067 case AUDIO_USAGE_ALARM:
6068 case AUDIO_USAGE_NOTIFICATION:
6069 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6070 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6071 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6072 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6073 case AUDIO_USAGE_NOTIFICATION_EVENT:
6074 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6075 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6076 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6077 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006078 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006079 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006080 break;
6081 default:
6082 return false;
6083 }
6084 return true;
6085}
6086
François Gaffie2110e042015-03-24 08:41:51 +01006087audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6088{
6089 return mEngine->getForceUse(usage);
6090}
6091
6092bool AudioPolicyManager::isInCall()
6093{
6094 return isStateInCall(mEngine->getPhoneState());
6095}
6096
6097bool AudioPolicyManager::isStateInCall(int state)
6098{
6099 return is_state_in_call(state);
6100}
6101
Eric Laurentd60560a2015-04-10 11:31:20 -07006102void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6103{
6104 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006105 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6106 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6107 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6108 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006109 }
6110 }
6111
6112 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6113 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6114 bool release = false;
6115 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6116 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6117 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6118 source->ext.device.type == deviceDesc->type()) {
6119 release = true;
6120 }
6121 }
6122 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6123 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6124 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6125 sink->ext.device.type == deviceDesc->type()) {
6126 release = true;
6127 }
6128 }
6129 if (release) {
François Gaffiead447b72019-11-18 15:50:22 +01006130 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6131 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006132 }
6133 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006134
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006135 mInputs.clearSessionRoutesForDevice(deviceDesc);
6136
Francois Gaffie716e1432019-01-14 16:58:59 +01006137 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006138}
6139
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006140void AudioPolicyManager::modifySurroundFormats(
6141 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006142 std::unordered_set<audio_format_t> enforcedSurround(
6143 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006144 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6145 for (const auto& pair : mConfig.getSurroundFormats()) {
6146 allSurround.insert(pair.first);
6147 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6148 }
Phil Burk09bc4612016-02-24 15:58:15 -08006149
6150 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6151 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006152 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006153 // This is the resulting set of formats depending on the surround mode:
6154 // 'all surround' = allSurround
6155 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6156 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6157 // 'manual surround' = mManualSurroundFormats
6158 // AUTO: formats v 'enforced surround'
6159 // ALWAYS: formats v 'all surround' v 'enforced surround'
6160 // NEVER: formats ^ 'non-surround'
6161 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006162
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006163 std::unordered_set<audio_format_t> formatSet;
6164 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6165 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006166 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006167 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006168 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006169 formatSet.insert(*formatIter);
6170 }
6171 }
6172 } else {
6173 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6174 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006175 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006176
jiabin81772902018-04-02 17:52:27 -07006177 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006178 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006179 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6180 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6181 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006182 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006183 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6184 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6185 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006186 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006187 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006188 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006189 for (const auto& format : formatSet) {
jiabin4562b3b2019-07-29 10:13:34 -07006190 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006191 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006192}
6193
jiabin4562b3b2019-07-29 10:13:34 -07006194void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6195 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006196 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6197 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6198
6199 // If NEVER, then remove support for channelMasks > stereo.
6200 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin4562b3b2019-07-29 10:13:34 -07006201 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6202 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006203 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6204 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin4562b3b2019-07-29 10:13:34 -07006205 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006206 } else {
jiabin4562b3b2019-07-29 10:13:34 -07006207 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006208 }
6209 }
jiabin81772902018-04-02 17:52:27 -07006210 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6211 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6212 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006213 bool supports5dot1 = false;
6214 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006215 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006216 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6217 supports5dot1 = true;
6218 break;
6219 }
6220 }
6221 // If not then add 5.1 support.
6222 if (!supports5dot1) {
jiabin4562b3b2019-07-29 10:13:34 -07006223 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006224 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006225 }
Phil Burk09bc4612016-02-24 15:58:15 -08006226 }
6227}
6228
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006229void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006230 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006231 AudioProfileVector &profiles)
6232{
6233 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006234 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006235
François Gaffie112b0af2015-11-19 16:13:25 +01006236 // Format MUST be checked first to update the list of AudioProfile
6237 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006238 reply = mpClientInterface->getParameters(
6239 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006240 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006241 AudioParameter repliedParameters(reply);
6242 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006243 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006244 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6245 return;
6246 }
Phil Burk09bc4612016-02-24 15:58:15 -08006247 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006248 if (device == AUDIO_DEVICE_OUT_HDMI
6249 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006250 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006251 }
jiabinb9733bc2019-09-10 14:27:34 -07006252 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006253 }
François Gaffie112b0af2015-11-19 16:13:25 +01006254
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006255 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin4562b3b2019-07-29 10:13:34 -07006256 ChannelMaskSet channelMasks;
6257 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006258 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006259 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006260
6261 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006262 reply = mpClientInterface->getParameters(
6263 ioHandle,
6264 requestedParameters.toString() + ";" +
6265 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006266 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006267 AudioParameter repliedParameters(reply);
6268 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006269 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006270 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006271 }
6272 }
6273 if (profiles.hasDynamicChannelsFor(format)) {
6274 reply = mpClientInterface->getParameters(ioHandle,
6275 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006276 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006277 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006278 AudioParameter repliedParameters(reply);
6279 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006280 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006281 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006282 if (device == AUDIO_DEVICE_OUT_HDMI
6283 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006284 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006285 }
François Gaffie112b0af2015-11-19 16:13:25 +01006286 }
6287 }
jiabinb9733bc2019-09-10 14:27:34 -07006288 addDynamicAudioProfileAndSort(
6289 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006290 }
6291}
Eric Laurentd60560a2015-04-10 11:31:20 -07006292
Mikhail Naganovdc769682018-05-04 15:34:08 -07006293status_t AudioPolicyManager::installPatch(const char *caller,
6294 audio_patch_handle_t *patchHandle,
6295 AudioIODescriptorInterface *ioDescriptor,
6296 const struct audio_patch *patch,
6297 int delayMs)
6298{
6299 ssize_t index = mAudioPatches.indexOfKey(
6300 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6301 *patchHandle : ioDescriptor->getPatchHandle());
6302 sp<AudioPatch> patchDesc;
6303 status_t status = installPatch(
6304 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6305 if (status == NO_ERROR) {
François Gaffiead447b72019-11-18 15:50:22 +01006306 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006307 }
6308 return status;
6309}
6310
6311status_t AudioPolicyManager::installPatch(const char *caller,
6312 ssize_t index,
6313 audio_patch_handle_t *patchHandle,
6314 const struct audio_patch *patch,
6315 int delayMs,
6316 uid_t uid,
6317 sp<AudioPatch> *patchDescPtr)
6318{
6319 sp<AudioPatch> patchDesc;
6320 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6321 if (index >= 0) {
6322 patchDesc = mAudioPatches.valueAt(index);
François Gaffiead447b72019-11-18 15:50:22 +01006323 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006324 }
6325
6326 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6327 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6328 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6329 if (status == NO_ERROR) {
6330 if (index < 0) {
6331 patchDesc = new AudioPatch(patch, uid);
François Gaffiead447b72019-11-18 15:50:22 +01006332 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006333 } else {
6334 patchDesc->mPatch = *patch;
6335 }
François Gaffiead447b72019-11-18 15:50:22 +01006336 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006337 if (patchHandle) {
François Gaffiead447b72019-11-18 15:50:22 +01006338 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006339 }
6340 nextAudioPortGeneration();
6341 mpClientInterface->onAudioPatchListUpdate();
6342 }
6343 if (patchDescPtr) *patchDescPtr = patchDesc;
6344 return status;
6345}
6346
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006347} // namespace android