blob: d9a5fa25177d470e09f49ebde54caafd0cc3ee95 [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>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070050#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070051#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070052#include <system/audio_effects/effect_hapticgenerator.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
jiabin06e4bab2019-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{
jiabince9f20e2019-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 Naganovf23fcf62019-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 Naganovd0e2c742020-03-25 15:59:59 -0700139 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
140}
Paul McLeane743a472015-01-28 11:07:31 -0800141
Mikhail Naganovd0e2c742020-03-25 15:59:59 -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 Naganovd0e2c742020-03-25 15:59:59 -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 Naganovd0e2c742020-03-25 15:59:59 -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
jiabin1c4794b2020-05-05 10:08:05 -0700183 // Populate encapsulation information when a output device is connected.
184 device->setEncapsulationInfoFromHal(mpClientInterface);
185
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700186 // outputs should never be empty here
187 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
188 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100189 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800190
Eric Laurent3ae5f312015-02-03 17:12:08 -0800191 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700193 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
198
François Gaffie11d30102018-11-02 16:09:09 +0100199 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700200
Paul McLeane743a472015-01-28 11:07:31 -0800201 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100202 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100205 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700206
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100207 mOutputs.clearSessionRoutesForDevice(device);
208
François Gaffie11d30102018-11-02 16:09:09 +0100209 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100210
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800211 // Reset active device codec
212 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 } break;
215
216 default:
François Gaffie11d30102018-11-02 16:09:09 +0100217 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700218 return BAD_VALUE;
219 }
220
Eric Laurent736a1022019-03-27 18:28:46 -0700221 // Propagate device availability to Engine
222 setEngineDeviceConnectionState(device, state);
223
Eric Laurentae970022019-01-29 14:25:04 -0800224 // No need to evaluate playback routing when connecting a remote submix
225 // output device used by a dynamic policy of type recorder as no
226 // playback use case is affected.
227 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700228 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800229 for (audio_io_handle_t output : outputs) {
230 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800231 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
232 if (policyMix != nullptr
233 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700234 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800235 doCheckForDeviceAndOutputChanges = false;
236 break;
237 }
238 }
239 }
240
241 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700242 // outputs must be closed after checkOutputForAllStrategies() is executed
243 if (!outputs.isEmpty()) {
244 for (audio_io_handle_t output : outputs) {
245 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100246 // close unused outputs after device disconnection or direct outputs that have
247 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700248 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
249 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800250 (desc->mDirectOpenCount == 0))) {
Mikhail Naganov37977152018-07-11 15:54:44 -0700251 closeOutput(output);
252 }
Eric Laurente552edb2014-03-10 17:42:56 -0700253 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700254 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
255 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700256 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700257 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800258 };
259
260 if (doCheckForDeviceAndOutputChanges) {
261 checkForDeviceAndOutputChanges(checkCloseOutputs);
262 } else {
263 checkCloseOutputs();
264 }
Eric Laurente552edb2014-03-10 17:42:56 -0700265
Eric Laurent87ffa392015-05-22 10:32:38 -0700266 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100267 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
268 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700269 }
François Gaffie11d30102018-11-02 16:09:09 +0100270 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
Eric Laurente552edb2014-03-10 17:42:56 -0700271 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
273 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
François Gaffie11d30102018-11-02 16:09:09 +0100274 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700275 // do not force device change on duplicated output because if device is 0, it will
276 // also force a device 0 for the two outputs it is duplicated to which may override
277 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100278 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100279 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700280 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700281 // always force when disconnecting (a non-duplicated device)
282 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100283 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700284 }
Eric Laurente552edb2014-03-10 17:42:56 -0700285 }
286
Eric Laurentd60560a2015-04-10 11:31:20 -0700287 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100288 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700289 }
290
Eric Laurent72aa32f2014-05-30 18:51:48 -0700291 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700292 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700293 } // end if is output device
294
Eric Laurente552edb2014-03-10 17:42:56 -0700295 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700296 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100297 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700298 switch (state)
299 {
300 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700301 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700302 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100303 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700304 return INVALID_OPERATION;
305 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700306
307 if (mAvailableInputDevices.add(device) < 0) {
308 return NO_MEMORY;
309 }
310
François Gaffie44481e72016-04-20 07:49:57 +0200311 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
312 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100313 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200314
Eric Laurent0dd51852019-04-19 18:18:58 -0700315 if (checkInputsForDevice(device, state) != NO_ERROR) {
316 mAvailableInputDevices.remove(device);
317
François Gaffie11d30102018-11-02 16:09:09 +0100318 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100319
320 mHwModules.cleanUpForDevice(device);
321
Eric Laurentd4692962014-05-05 18:13:44 -0700322 return INVALID_OPERATION;
323 }
324
Eric Laurentd4692962014-05-05 18:13:44 -0700325 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700326
327 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700328 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100330 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return INVALID_OPERATION;
332 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700333
François Gaffie11d30102018-11-02 16:09:09 +0100334 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700335
336 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700338
François Gaffie11d30102018-11-02 16:09:09 +0100339 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700340
341 checkInputsForDevice(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700342 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700343
344 default:
François Gaffie11d30102018-11-02 16:09:09 +0100345 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700346 return BAD_VALUE;
347 }
348
Eric Laurent736a1022019-03-27 18:28:46 -0700349 // Propagate device availability to Engine
350 setEngineDeviceConnectionState(device, state);
351
Eric Laurent0dd51852019-04-19 18:18:58 -0700352 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700353 // As the input device list can impact the output device selection, update
354 // getDeviceForStrategy() cache
355 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700356
Eric Laurent87ffa392015-05-22 10:32:38 -0700357 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100358 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
359 updateCallRouting(newDevices);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700360 }
361
Eric Laurentd60560a2015-04-10 11:31:20 -0700362 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100363 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 }
365
Eric Laurentb52c1522014-05-20 11:27:36 -0700366 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700367 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700368 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700369
François Gaffie11d30102018-11-02 16:09:09 +0100370 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700371 return BAD_VALUE;
372}
373
Eric Laurent736a1022019-03-27 18:28:46 -0700374void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
375 audio_policy_dev_state_t state) {
376
377 // the Engine does not have to know about remote submix devices used by dynamic audio policies
378 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
379 return;
380 }
381 mEngine->setDeviceConnectionState(device, state);
382}
383
384
Eric Laurente0720872014-03-11 09:30:41 -0700385audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100386 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700387{
Eric Laurent634b7142016-04-20 13:48:02 -0700388 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800389 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
390 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700391 (strlen(device_address) != 0)/*matchAddress*/);
392
393 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100394 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700395 device, device_address);
396 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
397 }
François Gaffie53615e22015-03-19 09:24:12 +0100398
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 DeviceVector *deviceVector;
400
Eric Laurente552edb2014-03-10 17:42:56 -0700401 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700403 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700404 deviceVector = &mAvailableInputDevices;
405 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100406 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700408 }
Eric Laurent634b7142016-04-20 13:48:02 -0700409
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800410 return (deviceVector->getDevice(
411 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700412 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800413}
414
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800415status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
416 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800417 const char *device_name,
418 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800419{
420 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700421 String8 reply;
422 AudioParameter param;
423 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800424
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800425 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
426 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800427
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800428 // connect/disconnect only 1 device at a time
429 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
430
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800431 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700432 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800433 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800434 // Nothing to do: device is not connected
435 return NO_ERROR;
436 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800437 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800438
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700439 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800440 // configure codecs.
441 // Handle two specific cases by sending a set parameter to
442 // configure A2DP codecs. No need to toggle device state.
443 // Case 1: A2DP active device switches from primary to primary
444 // module
445 // Case 2: A2DP device config changes on primary module.
jiabin9a3361e2019-10-01 09:38:30 -0700446 if (audio_is_a2dp_out_device(device)) {
447 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800448 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
449 if (availablePrimaryOutputDevices().contains(devDesc) &&
450 (module != 0 && module->getHandle() == primaryHandle)) {
451 reply = mpClientInterface->getParameters(
452 AUDIO_IO_HANDLE_NONE,
453 String8(AudioParameter::keyReconfigA2dpSupported));
454 AudioParameter repliedParameters(reply);
455 repliedParameters.getInt(
456 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
457 if (isReconfigA2dpSupported) {
458 const String8 key(AudioParameter::keyReconfigA2dp);
459 param.add(key, String8("true"));
460 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
461 devDesc->setEncodedFormat(encodedFormat);
462 return NO_ERROR;
463 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700464 }
465 }
cnx421bd2dcc42020-07-11 14:58:44 +0800466 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
467 for (size_t i = 0; i < mOutputs.size(); i++) {
468 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
469 // mute media strategies and delay device switch by the largest
470 // This avoid sending the music tail into the earpiece or headset.
471 setStrategyMute(musicStrategy, true, desc);
472 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
473 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
474 nullptr, true /*fromCache*/).types());
475 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800476 // Toggle the device state: UNAVAILABLE -> AVAILABLE
477 // This will force reading again the device configuration
478 status = setDeviceConnectionState(device,
479 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800480 device_address, device_name,
481 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800482 if (status != NO_ERROR) {
483 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
484 status);
485 return status;
486 }
487
488 status = setDeviceConnectionState(device,
489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800491 if (status != NO_ERROR) {
492 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
493 status);
494 return status;
495 }
496
497 return NO_ERROR;
498}
499
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800500status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
501 std::vector<audio_format_t> *formats)
502{
503 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800504 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800505 std::unordered_set<audio_format_t> formatSet;
506 sp<HwModule> primaryModule =
507 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700508 if (primaryModule == nullptr) {
509 ALOGE("%s() unable to get primary module", __func__);
510 return NO_INIT;
511 }
jiabin9a3361e2019-10-01 09:38:30 -0700512 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
513 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800514 for (const auto& device : declaredDevices) {
515 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800516 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800517 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800518 return status;
519}
520
François Gaffie11d30102018-11-02 16:09:09 +0100521uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700522{
523 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100524 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700525 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700526
jiabin9a3361e2019-10-01 09:38:30 -0700527 if(!hasPrimaryOutput() ||
528 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700529 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700530 }
François Gaffie11d30102018-11-02 16:09:09 +0100531 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
532
Francois Gaffie716e1432019-01-14 16:58:59 +0100533 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100534 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffie9eb18552018-11-05 10:33:26 +0100535 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
François Gaffiec005e562018-11-06 15:04:49 +0100536
537 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
François Gaffie9eb18552018-11-05 10:33:26 +0100538 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700539
540 // release existing RX patch if any
541 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100542 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700543 mCallRxPatch.clear();
544 }
545 // release TX patch if any
546 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100547 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700548 mCallTxPatch.clear();
549 }
550
François Gaffie9eb18552018-11-05 10:33:26 +0100551 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700552 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100553 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700554 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100555 // retrieve Rx Source and Tx Sink device descriptors
556 sp<DeviceDescriptor> rxSourceDevice =
557 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
558 String8(),
559 AUDIO_FORMAT_DEFAULT);
560 sp<DeviceDescriptor> txSinkDevice =
561 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
562 String8(),
563 AUDIO_FORMAT_DEFAULT);
564
565 // RX and TX Telephony device are declared by Primary Audio HAL
566 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
567 (telephonyRxModule->getHalVersionMajor() >= 3)) {
568 if (rxSourceDevice == 0 || txSinkDevice == 0) {
569 // RX / TX Telephony device(s) is(are) not currently available
570 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
571 return muteWaitMs;
572 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100573 // createAudioPatchInternal now supports both HW / SW bridging
574 createRxPatch = true;
575 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100576 } else {
577 // If the RX device is on the primary HW module, then use legacy routing method for
578 // voice calls via setOutputDevice() on primary output.
579 // Otherwise, create two audio patches for TX and RX path.
580 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
581 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700582 // If the TX device is also on the primary HW module, setOutputDevice() will take care
583 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100584 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
585 (txSinkDevice != 0);
586 }
587 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
588 // Otherwise, create two audio patches for TX and RX path.
589 if (!createRxPatch) {
590 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700591 } else { // create RX path audio patch
François Gaffie11d30102018-11-02 16:09:09 +0100592 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800593
594 // If the TX device is on the primary HW module but RX device is
595 // on other HW module, SinkMetaData of telephony input should handle it
596 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700597 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700598 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100599 // terminate active capture if on the same HW module as the call TX source device
600 // FIXME: would be better to refine to only inputs whose profile connects to the
601 // call TX device but this information is not in the audio patch and logic here must be
602 // symmetric to the one in startInput()
603 for (const auto& activeDesc : mInputs.getActiveInputs()) {
604 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
605 closeActiveClients(activeDesc);
606 }
607 }
François Gaffie9eb18552018-11-05 10:33:26 +0100608 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800609 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700610
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800611 return muteWaitMs;
612}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700613
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800614sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100615 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700616 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617
François Gaffie11d30102018-11-02 16:09:09 +0100618 if (device == nullptr) {
619 return nullptr;
620 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100621
622 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800623 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100624 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800625 addSource(mAvailableInputDevices.getDevice(
626 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800627 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100628 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800629 addSink(mAvailableOutputDevices.getDevice(
630 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800631 }
632
François Gaffieafd4cea2019-11-18 15:50:22 +0100633 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
634 status_t status =
635 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
636 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
637 if (status != NO_ERROR || index < 0) {
638 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
639 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800640 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100641 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800642}
643
Mikhail Naganov100f0122018-11-29 11:22:16 -0800644bool AudioPolicyManager::isDeviceOfModule(
645 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
646 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
647 if (module != 0) {
648 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
649 .indexOf(devDesc) != NAME_NOT_FOUND
650 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
651 .indexOf(devDesc) != NAME_NOT_FOUND;
652 }
653 return false;
654}
655
Eric Laurente0720872014-03-11 09:30:41 -0700656void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700657{
658 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100659 // store previous phone state for management of sonification strategy below
660 int oldState = mEngine->getPhoneState();
661
662 if (mEngine->setPhoneState(state) != NO_ERROR) {
663 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700664 return;
665 }
François Gaffie2110e042015-03-24 08:41:51 +0100666 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700667 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700668 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700669 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800670 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700671 }
672
François Gaffie2110e042015-03-24 08:41:51 +0100673 /**
674 * Switching to or from incall state or switching between telephony and VoIP lead to force
675 * routing command.
676 */
Eric Laurent74b71512019-11-06 17:21:57 -0800677 bool force = ((isStateInCall(oldState) != isStateInCall(state))
678 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700679
680 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700681 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700682
Eric Laurente552edb2014-03-10 17:42:56 -0700683 int delayMs = 0;
684 if (isStateInCall(state)) {
685 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100686 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
687 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700688 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700689 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700690 // mute media and sonification strategies and delay device switch by the largest
691 // latency of any output where either strategy is active.
692 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100693 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
694 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
695 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700696 (delayMs < (int)desc->latency()*2)) {
697 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700698 }
François Gaffiec005e562018-11-06 15:04:49 +0100699 setStrategyMute(musicStrategy, true, desc);
700 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
701 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
702 nullptr, true /*fromCache*/).types());
703 setStrategyMute(sonificationStrategy, true, desc);
704 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
705 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
706 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700707 }
708 }
709
Eric Laurent87ffa392015-05-22 10:32:38 -0700710 if (hasPrimaryOutput()) {
François Gaffie11d30102018-11-02 16:09:09 +0100711 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
Eric Laurent87ffa392015-05-22 10:32:38 -0700712 // the device returned is not necessarily reachable via this output
François Gaffie11d30102018-11-02 16:09:09 +0100713 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
Eric Laurent87ffa392015-05-22 10:32:38 -0700714 // force routing command to audio hardware when ending call
715 // even if no device change is needed
François Gaffie11d30102018-11-02 16:09:09 +0100716 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
717 rxDevices = mPrimaryOutput->devices();
Eric Laurent87ffa392015-05-22 10:32:38 -0700718 }
Eric Laurente552edb2014-03-10 17:42:56 -0700719
Eric Laurent87ffa392015-05-22 10:32:38 -0700720 if (state == AUDIO_MODE_IN_CALL) {
François Gaffie11d30102018-11-02 16:09:09 +0100721 updateCallRouting(rxDevices, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700722 } else if (oldState == AUDIO_MODE_IN_CALL) {
723 if (mCallRxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100724 releaseAudioPatchInternal(mCallRxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 mCallRxPatch.clear();
726 }
727 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100728 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurent87ffa392015-05-22 10:32:38 -0700729 mCallTxPatch.clear();
730 }
François Gaffie11d30102018-11-02 16:09:09 +0100731 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurent87ffa392015-05-22 10:32:38 -0700732 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100733 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700734 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700735 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700736
737 // reevaluate routing on all outputs in case tracks have been started during the call
738 for (size_t i = 0; i < mOutputs.size(); i++) {
739 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100740 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700741 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100742 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700743 }
744 }
745
Eric Laurente552edb2014-03-10 17:42:56 -0700746 if (isStateInCall(state)) {
747 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700748 // force reevaluating accessibility routing when call starts
749 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700750 }
751
752 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100753 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
754 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700755}
756
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700757audio_mode_t AudioPolicyManager::getPhoneState() {
758 return mEngine->getPhoneState();
759}
760
Eric Laurente0720872014-03-11 09:30:41 -0700761void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100762 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700763{
François Gaffie2110e042015-03-24 08:41:51 +0100764 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700765 if (config == mEngine->getForceUse(usage)) {
766 return;
767 }
Eric Laurente552edb2014-03-10 17:42:56 -0700768
François Gaffie2110e042015-03-24 08:41:51 +0100769 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
770 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
771 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700772 }
François Gaffie2110e042015-03-24 08:41:51 +0100773 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
774 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
775 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700776
777 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700778 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800779
Eric Laurent22fcda22019-05-17 16:28:47 -0700780 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
781 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
782 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
783 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
784 }
785
Eric Laurentdc462862016-07-19 12:29:53 -0700786 //FIXME: workaround for truncated touch sounds
787 // to be removed when the problem is handled by system UI
788 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700789 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
790 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
791 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700792
793 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -0700794
Mikhail Naganovcf84e592017-12-07 11:25:11 -0800795 for (const auto& activeDesc : mInputs.getActiveInputs()) {
François Gaffie11d30102018-11-02 16:09:09 +0100796 auto newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700797 // Force new input selection if the new device can not be reached via current input
Francois Gaffie716e1432019-01-14 16:58:59 +0100798 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800799 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700800 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800801 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700802 }
Eric Laurente552edb2014-03-10 17:42:56 -0700803 }
Eric Laurente552edb2014-03-10 17:42:56 -0700804}
805
Eric Laurente0720872014-03-11 09:30:41 -0700806void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700807{
808 ALOGV("setSystemProperty() property %s, value %s", property, value);
809}
810
Michael Chana94fbb22018-04-24 14:31:19 +1000811// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
812// search to profiles for direct outputs.
813sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100814 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000815 uint32_t samplingRate,
816 audio_format_t format,
817 audio_channel_mask_t channelMask,
818 audio_output_flags_t flags,
819 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700820{
Michael Chana94fbb22018-04-24 14:31:19 +1000821 if (directOnly) {
822 // only retain flags that will drive the direct output profile selection
823 // if explicitly requested
824 static const uint32_t kRelevantFlags =
825 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700826 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000827 flags =
828 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
829 }
Eric Laurent861a6282015-05-18 15:40:16 -0700830
831 sp<IOProfile> profile;
832
Mikhail Naganovd4120142017-12-06 15:49:22 -0800833 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800834 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100835 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700836 samplingRate, NULL /*updatedSamplingRate*/,
837 format, NULL /*updatedFormat*/,
838 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700839 flags)) {
840 continue;
841 }
842 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100843 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700844 continue;
845 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800846 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700847 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800848 continue;
849 }
Michael Chana94fbb22018-04-24 14:31:19 +1000850 if (!directOnly) return curProfile;
851 // when searching for direct outputs, if several profiles are compatible, give priority
852 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100853 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700854 continue;
855 }
856 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100857 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700858 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700859 }
Eric Laurente552edb2014-03-10 17:42:56 -0700860 }
861 }
Eric Laurent861a6282015-05-18 15:40:16 -0700862 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700863}
864
Eric Laurentf4e63452017-11-06 19:31:46 +0000865audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700866{
François Gaffiec005e562018-11-06 15:04:49 +0100867 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800868
869 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
870 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
871 // format, flags, etc. This may result in some discrepancy for functions that utilize
872 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
873 // and AudioSystem::getOutputSamplingRate().
874
François Gaffie11d30102018-11-02 16:09:09 +0100875 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700876 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700877
François Gaffie11d30102018-11-02 16:09:09 +0100878 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
879 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000880 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700881}
882
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700883status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
884 const audio_attributes_t *srcAttr,
885 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700886{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700887 if (srcAttr != NULL) {
888 if (!isValidAttributes(srcAttr)) {
889 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
890 __func__,
891 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
892 srcAttr->tags);
893 return BAD_VALUE;
894 }
895 *dstAttr = *srcAttr;
896 } else {
897 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
898 ALOGE("%s: invalid stream type", __func__);
899 return BAD_VALUE;
900 }
François Gaffiec005e562018-11-06 15:04:49 +0100901 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700902 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700903
904 // Only honor audibility enforced when required. The client will be
905 // forced to reconnect if the forced usage changes.
906 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700907 dstAttr->flags = static_cast<audio_flags_mask_t>(
908 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700909 }
910
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700911 return NO_ERROR;
912}
913
Kevin Rocard153f92d2018-12-18 18:33:28 -0800914status_t AudioPolicyManager::getOutputForAttrInt(
915 audio_attributes_t *resultAttr,
916 audio_io_handle_t *output,
917 audio_session_t session,
918 const audio_attributes_t *attr,
919 audio_stream_type_t *stream,
920 uid_t uid,
921 const audio_config_t *config,
922 audio_output_flags_t *flags,
923 audio_port_handle_t *selectedDeviceId,
924 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700925 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800926 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700927{
François Gaffiec005e562018-11-06 15:04:49 +0100928 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100929 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100930 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100931 const sp<DeviceDescriptor> requestedDevice =
932 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
933
Eric Laurent8a1095a2019-11-08 14:44:16 -0800934 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700935 status_t status = getAudioAttributes(resultAttr, attr, *stream);
936 if (status != NO_ERROR) {
937 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -0700938 }
Kevin Rocardb99cc752019-03-21 20:52:24 -0700939 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700940 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -0700941 }
François Gaffiec005e562018-11-06 15:04:49 +0100942 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -0700943
François Gaffiec005e562018-11-06 15:04:49 +0100944 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
945 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700946
Kevin Rocard153f92d2018-12-18 18:33:28 -0800947 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
948 // otherwise, fallback to the dynamic policies, if none match, query the engine.
949 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -0700950 sp<AudioPolicyMix> primaryMix;
951 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -0700952 if (status != OK) {
953 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800954 }
Kevin Rocard94114a22019-04-01 19:38:23 -0700955
Kevin Rocard153f92d2018-12-18 18:33:28 -0800956 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -0700957 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -0800958
959 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -0700960 if ((usePrimaryOutputFromPolicyMixes
961 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -0800962 && !audio_is_linear_pcm(config->format)) {
963 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -0800964 return BAD_VALUE;
965 }
966 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700967 sp<DeviceDescriptor> deviceDesc =
968 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
969 primaryMix->mDeviceAddress,
970 AUDIO_FORMAT_DEFAULT);
971 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -0700972 if (deviceDesc != nullptr
973 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -0700974 audio_io_handle_t newOutput;
975 status = openDirectOutput(
976 *stream, session, config,
977 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
978 DeviceVector(deviceDesc), &newOutput);
979 if (status != NO_ERROR) {
980 policyDesc = nullptr;
981 } else {
982 policyDesc = mOutputs.valueFor(newOutput);
983 primaryMix->setOutput(policyDesc);
984 }
985 }
986 if (policyDesc != nullptr) {
987 policyDesc->mPolicyMix = primaryMix;
988 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -0800989 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -0800990
Jean-Michel Trivif41599b2020-01-07 14:22:08 -0800991 ALOGV("getOutputForAttr() returns output %d", *output);
992 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
993 *outputType = API_OUT_MIX_PLAYBACK;
994 } else {
995 *outputType = API_OUTPUT_LEGACY;
996 }
997 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -0800998 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700999 }
François Gaffiec005e562018-11-06 15:04:49 +01001000 // Virtual sources must always be dynamicaly or explicitly routed
1001 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1002 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1003 return BAD_VALUE;
1004 }
1005 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1006 // in order to let the choice of the order to future vendor engine
1007 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001008
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001009 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001010 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001011 }
1012
Nadav Barb2f18162018-07-18 13:01:53 +03001013 // Set incall music only if device was explicitly set, and fallback to the device which is
1014 // chosen by the engine if not.
1015 // FIXME: provide a more generic approach which is not device specific and move this back
1016 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001017 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001018 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001019 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001020 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001021 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001022 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001023 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001024 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001025 }
1026 }
1027
François Gaffiec005e562018-11-06 15:04:49 +01001028 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1029 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1030 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001031
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001032 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001033 if (!msdDevices.isEmpty()) {
1034 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
François Gaffiec005e562018-11-06 15:04:49 +01001035 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1036 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1037 ALOGV("%s() Using MSD devices %s instead of devices %s",
1038 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1039 outputDevices = msdDevices;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001040 } else {
1041 *output = AUDIO_IO_HANDLE_NONE;
1042 }
1043 }
1044 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001045 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001046 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001047 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001048 if (*output == AUDIO_IO_HANDLE_NONE) {
1049 return INVALID_OPERATION;
1050 }
Paul McLeanaa981192015-03-21 09:55:15 -07001051
François Gaffiec005e562018-11-06 15:04:49 +01001052 *selectedDeviceId = getFirstDeviceId(outputDevices);
Eric Laurent2ac76942017-06-22 17:17:09 -07001053
Eric Laurent8a1095a2019-11-08 14:44:16 -08001054 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1055 *outputType = API_OUTPUT_TELEPHONY_TX;
1056 } else {
1057 *outputType = API_OUTPUT_LEGACY;
1058 }
1059
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001060 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1061
1062 return NO_ERROR;
1063}
1064
1065status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1066 audio_io_handle_t *output,
1067 audio_session_t session,
1068 audio_stream_type_t *stream,
1069 uid_t uid,
1070 const audio_config_t *config,
1071 audio_output_flags_t *flags,
1072 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001073 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001074 std::vector<audio_io_handle_t> *secondaryOutputs,
1075 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001076{
1077 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1078 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1079 return INVALID_OPERATION;
1080 }
Francois Gaffie716e1432019-01-14 16:58:59 +01001081 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001082 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001083 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001084 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001085 const sp<DeviceDescriptor> requestedDevice =
1086 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1087
1088 // Prevent from storing invalid requested device id in clients
1089 const audio_port_handle_t sanitizedRequestedPortId =
1090 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1091 *selectedDeviceId = sanitizedRequestedPortId;
1092
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001093 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001094 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001095 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001096 if (status != NO_ERROR) {
1097 return status;
1098 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001099 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001100 if (secondaryOutputs != nullptr) {
1101 for (auto &secondaryMix : secondaryMixes) {
1102 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1103 if (outputDesc != nullptr &&
1104 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1105 secondaryOutputs->push_back(outputDesc->mIoHandle);
1106 weakSecondaryOutputDescs.push_back(outputDesc);
1107 }
1108 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110
Eric Laurent8fc147b2018-07-22 19:13:55 -07001111 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001112 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001113 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001114 };
jiabin4ef93452019-09-10 14:29:54 -07001115 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001116
Eric Laurentc209fe42020-06-05 18:11:23 -07001117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001118 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001119 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001120 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001121 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001122 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001123 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001124 std::move(weakSecondaryOutputDescs),
1125 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001126 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001127
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001128 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1129 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001130
Eric Laurente83b55d2014-11-14 10:06:21 -08001131 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001132}
1133
Eric Laurentc529cf62020-04-17 18:19:10 -07001134status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1135 audio_session_t session,
1136 const audio_config_t *config,
1137 audio_output_flags_t flags,
1138 const DeviceVector &devices,
1139 audio_io_handle_t *output) {
1140
1141 *output = AUDIO_IO_HANDLE_NONE;
1142
1143 // skip direct output selection if the request can obviously be attached to a mixed output
1144 // and not explicitly requested
1145 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1146 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1147 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1148 return NAME_NOT_FOUND;
1149 }
1150
1151 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1152 // This prevents creating an offloaded track and tearing it down immediately after start
1153 // when audioflinger detects there is an active non offloadable effect.
1154 // FIXME: We should check the audio session here but we do not have it in this context.
1155 // This may prevent offloading in rare situations where effects are left active by apps
1156 // in the background.
1157 sp<IOProfile> profile;
1158 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1159 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1160 profile = getProfileForOutput(
1161 devices, config->sample_rate, config->format, config->channel_mask,
1162 flags, true /* directOnly */);
1163 }
1164
1165 if (profile == nullptr) {
1166 return NAME_NOT_FOUND;
1167 }
1168
1169 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1170 for (size_t i = 0; i < mOutputs.size(); i++) {
1171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1172 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1173 // reuse direct output if currently open by the same client
1174 // and configured with same parameters
1175 if ((config->sample_rate == desc->getSamplingRate()) &&
1176 (config->format == desc->getFormat()) &&
1177 (config->channel_mask == desc->getChannelMask()) &&
1178 (session == desc->mDirectClientSession)) {
1179 desc->mDirectOpenCount++;
1180 ALOGI("%s reusing direct output %d for session %d", __func__,
1181 mOutputs.keyAt(i), session);
1182 *output = mOutputs.keyAt(i);
1183 return NO_ERROR;
1184 }
1185 }
1186 }
1187
1188 if (!profile->canOpenNewIo()) {
1189 return NAME_NOT_FOUND;
1190 }
1191
1192 sp<SwAudioOutputDescriptor> outputDesc =
1193 new SwAudioOutputDescriptor(profile, mpClientInterface);
1194
1195 String8 address = getFirstDeviceAddress(devices);
1196
1197 // MSD patch may be using the only output stream that can service this request. Release
1198 // MSD patch to prioritize this request over any active output on MSD.
1199 AudioPatchCollection msdPatches = getMsdPatches();
1200 for (size_t i = 0; i < msdPatches.size(); i++) {
1201 const auto& patch = msdPatches[i];
1202 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1203 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1204 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1205 devices.containsDeviceWithType(sink->ext.device.type) &&
1206 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1207 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1208 releaseAudioPatch(patch->getHandle(), mUidCached);
1209 break;
1210 }
1211 }
1212 }
1213
1214 status_t status = outputDesc->open(config, devices, stream, flags, output);
1215
1216 // only accept an output with the requested parameters
1217 if (status != NO_ERROR ||
1218 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1219 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1220 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1221 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1222 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1223 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1224 config->channel_mask, outputDesc->getChannelMask());
1225 if (*output != AUDIO_IO_HANDLE_NONE) {
1226 outputDesc->close();
1227 }
1228 // fall back to mixer output if possible when the direct output could not be open
1229 if (audio_is_linear_pcm(config->format) &&
1230 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1231 return NAME_NOT_FOUND;
1232 }
1233 *output = AUDIO_IO_HANDLE_NONE;
1234 return BAD_VALUE;
1235 }
1236 outputDesc->mDirectOpenCount = 1;
1237 outputDesc->mDirectClientSession = session;
1238
1239 addOutput(*output, outputDesc);
1240 mPreviousOutputs = mOutputs;
1241 ALOGV("%s returns new direct output %d", __func__, *output);
1242 mpClientInterface->onAudioPortListUpdate();
1243 return NO_ERROR;
1244}
1245
François Gaffie11d30102018-11-02 16:09:09 +01001246audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1247 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001248 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001249 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001250 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001251 audio_output_flags_t *flags,
1252 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001253{
Andy Hungc88b0642018-04-27 15:42:35 -07001254 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001255
jiabine375d412019-02-26 12:54:53 -08001256 // Discard haptic channel mask when forcing muting haptic channels.
1257 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001258 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1259 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001260
Eric Laurente552edb2014-03-10 17:42:56 -07001261 // open a direct output if required by specified parameters
1262 //force direct flag if offload flag is set: offloading implies a direct output stream
1263 // and all common behaviors are driven by checking only the direct flag
1264 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001265 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1266 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001267 }
Nadav Bar766fb022018-01-07 12:18:03 +02001268 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1269 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001270 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001271 // only allow deep buffering for music stream type
1272 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001273 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001274 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001275 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001276 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1277 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001278 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001279 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001280 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001281 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001282 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001283 audio_is_linear_pcm(config->format) &&
1284 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001285 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001286 AUDIO_OUTPUT_FLAG_DIRECT);
1287 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001288 }
Eric Laurente552edb2014-03-10 17:42:56 -07001289
Eric Laurentc529cf62020-04-17 18:19:10 -07001290 audio_config_t directConfig = *config;
1291 directConfig.channel_mask = channelMask;
1292 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1293 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001294 return output;
1295 }
1296
Eric Laurent14cbfca2016-03-17 09:42:16 -07001297 // A request for HW A/V sync cannot fallback to a mixed output because time
1298 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001299 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001300 return AUDIO_IO_HANDLE_NONE;
1301 }
1302
Eric Laurente552edb2014-03-10 17:42:56 -07001303 // ignoring channel mask due to downmix capability in mixer
1304
1305 // open a non direct output
1306
1307 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001308 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001309 // get which output is suitable for the specified stream. The actual
1310 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001311 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001312
Eric Laurent8838a382014-09-08 16:44:28 -07001313 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001314 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001315 output = selectOutput(
1316 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001317 }
François Gaffie11d30102018-11-02 16:09:09 +01001318 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001319 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001320 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001321
Eric Laurente552edb2014-03-10 17:42:56 -07001322 return output;
1323}
1324
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001325sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001326 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1327 mAvailableInputDevices);
1328 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1329}
1330
1331DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1332 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1333 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334}
1335
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001336const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1337 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001338 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1339 if (msdModule != 0) {
1340 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1341 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1342 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1343 const struct audio_port_config *source = &patch->mPatch.sources[j];
1344 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1345 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001346 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001347 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001348 }
1349 }
1350 }
1351 return msdPatches;
1352}
1353
François Gaffie11d30102018-11-02 16:09:09 +01001354status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001355 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1356{
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00001357 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001358 if (msdModule == nullptr) {
1359 ALOGE("%s() unable to get MSD module", __func__);
1360 return NO_INIT;
1361 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001362 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001363 if (deviceModule == nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001364 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 return NO_INIT;
1366 }
1367 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1368 if (inputProfiles.isEmpty()) {
1369 ALOGE("%s() no input profiles for MSD module", __func__);
1370 return NO_INIT;
1371 }
1372 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1373 if (outputProfiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01001374 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001375 return NO_INIT;
1376 }
1377 AudioProfileVector msdProfiles;
1378 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1379 for (const auto &inProfile : inputProfiles) {
1380 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001381 appendAudioProfiles(msdProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001382 }
1383 }
1384 AudioProfileVector deviceProfiles;
1385 for (const auto &outProfile : outputProfiles) {
1386 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
jiabin3e277cc2019-09-10 14:27:34 -07001387 appendAudioProfiles(deviceProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001388 }
1389 }
1390 struct audio_config_base bestSinkConfig;
jiabin3e277cc2019-09-10 14:27:34 -07001391 status_t result = findBestMatchingOutputConfig(msdProfiles, deviceProfiles,
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001392 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
jiabin3e277cc2019-09-10 14:27:34 -07001393 bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 if (result != NO_ERROR) {
François Gaffie11d30102018-11-02 16:09:09 +01001395 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1396 __func__, outputDevice->toString().c_str(), hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001397 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001398 }
1399 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1400 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1401 sinkConfig->format = bestSinkConfig.format;
1402 // For encoded streams force direct flag to prevent downstream mixing.
1403 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1404 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001405 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1406 // For formats compatible with IEC61937 encapsulation, assume that
1407 // the record thread input from MSD is IEC61937 framed (for proportional buffer sizing).
1408 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1409 // raw and IEC61937 framed streams.
1410 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1411 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1412 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1414 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1415 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1416 sourceConfig->format = bestSinkConfig.format;
1417 // Copy input stream directly without any processing (e.g. resampling).
1418 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1419 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1420 if (hwAvSync) {
1421 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1422 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1423 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1424 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1425 }
1426 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1427 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1428 sinkConfig->config_mask |= config_mask;
1429 sourceConfig->config_mask |= config_mask;
1430 return NO_ERROR;
1431}
1432
François Gaffie11d30102018-11-02 16:09:09 +01001433PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001434{
1435 PatchBuilder patchBuilder;
François Gaffie11d30102018-11-02 16:09:09 +01001436 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1438 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1439 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1440 // For now, we just forcefully try with HwAvSync first.
1441 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1442 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1443 getBestMsdAudioProfileFor(
1444 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1445 if (res == NO_ERROR) {
1446 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1447 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1448 }
1449 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1450 " supporting PCM format conversion.", __func__);
1451 return patchBuilder;
1452}
1453
François Gaffie11d30102018-11-02 16:09:09 +01001454status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1455 sp<DeviceDescriptor> device = outputDevice;
1456 if (device == nullptr) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001457 // Use media strategy for unspecified output device. This should only
1458 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1459 // therefore invalidate explicit routing requests.
François Gaffiec005e562018-11-06 15:04:49 +01001460 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1461 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01001462 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1463 device = devices.itemAt(0);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 }
François Gaffie11d30102018-11-02 16:09:09 +01001465 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1466 PatchBuilder patchBuilder = buildMsdPatch(device);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001467 const struct audio_patch* patch = patchBuilder.patch();
1468 const AudioPatchCollection msdPatches = getMsdPatches();
1469 if (!msdPatches.isEmpty()) {
1470 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1471 "The current MSD prototype only supports one output patch");
1472 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1473 if (audio_patches_are_equal(&currentPatch->mPatch, patch)) {
1474 return NO_ERROR;
1475 }
François Gaffieafd4cea2019-11-18 15:50:22 +01001476 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001477 }
1478 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1479 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1480 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1481 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
François Gaffie11d30102018-11-02 16:09:09 +01001482 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1483 device->toString().c_str(), patch->sources[0].format,
1484 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485 return status;
1486}
1487
Eric Laurente0720872014-03-11 09:30:41 -07001488audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001489 audio_output_flags_t flags,
1490 audio_format_t format,
1491 audio_channel_mask_t channelMask,
1492 uint32_t samplingRate,
1493 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001494{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001495 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1496 "%s called with format %#x", __func__, format);
1497
jiabinebb6af42020-06-09 17:31:17 -07001498 // Return the output that haptic-generating attached to when 1) session id is specified,
1499 // 2) haptic-generating effect exists for given session id and 3) the output that
1500 // haptic-generating effect attached to is in given outputs.
1501 if (sessionId != AUDIO_SESSION_NONE) {
1502 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1503 sessionId, FX_IID_HAPTICGENERATOR);
1504 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1505 return hapticGeneratingOutput;
1506 }
1507 }
1508
Eric Laurent16c66dd2019-05-01 17:54:10 -07001509 // Flags disqualifying an output: the match must happen before calling selectOutput()
1510 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1511 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1512
1513 // Flags expressing a functional request: must be honored in priority over
1514 // other criteria
1515 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1516 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1517 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1518 // Flags expressing a performance request: have lower priority than serving
1519 // requested sampling rate or channel mask
1520 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1521 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1522 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1523
1524 const audio_output_flags_t functionalFlags =
1525 (audio_output_flags_t)(flags & kFunctionalFlags);
1526 const audio_output_flags_t performanceFlags =
1527 (audio_output_flags_t)(flags & kPerformanceFlags);
1528
1529 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1530
Eric Laurente552edb2014-03-10 17:42:56 -07001531 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001532 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001533 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001534 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001535 // 2: the output with the highest number of requested functional flags
1536 // 3: the output supporting the exact channel mask
1537 // 4: the output with a higher channel count than requested
1538 // 5: the output with a higher sampling rate than requested
1539 // 6: the output with the highest number of requested performance flags
1540 // 7: the output with the bit depth the closest to the requested one
1541 // 8: the primary output
1542 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001543
Eric Laurent16c66dd2019-05-01 17:54:10 -07001544 // matching criteria values in priority order for best matching output so far
1545 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001546
Eric Laurent16c66dd2019-05-01 17:54:10 -07001547 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1548 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1549 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001550
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001551 for (audio_io_handle_t output : outputs) {
1552 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001553 // matching criteria values in priority order for current output
1554 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001555
Eric Laurent16c66dd2019-05-01 17:54:10 -07001556 if (outputDesc->isDuplicated()) {
1557 continue;
1558 }
1559 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1560 continue;
1561 }
Eric Laurent8838a382014-09-08 16:44:28 -07001562
Eric Laurent16c66dd2019-05-01 17:54:10 -07001563 // If haptic channel is specified, use the haptic output if present.
1564 // When using haptic output, same audio format and sample rate are required.
1565 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001566 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001567 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1568 continue;
1569 }
1570 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001571 && format == outputDesc->getFormat()
1572 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001573 currentMatchCriteria[0] = outputHapticChannelCount;
1574 }
1575
1576 // functional flags match
1577 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1578
1579 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001580 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1581 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001582 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1583 channelCount <= outputChannelCount) {
1584 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001585 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1586 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001587 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001588 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001589 currentMatchCriteria[3] = outputChannelCount;
1590 }
1591
1592 // sampling rate match
1593 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001594 samplingRate <= outputDesc->getSamplingRate()) {
1595 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001596 }
1597
1598 // performance flags match
1599 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1600
1601 // format match
1602 if (format != AUDIO_FORMAT_INVALID) {
1603 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001604 PolicyAudioPort::kFormatDistanceMax -
1605 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001606 }
1607
1608 // primary output match
1609 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1610
1611 // compare match criteria by priority then value
1612 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1613 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1614 bestMatchCriteria = currentMatchCriteria;
1615 bestOutput = output;
1616
1617 std::stringstream result;
1618 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1619 std::ostream_iterator<int>(result, " "));
1620 ALOGV("%s new bestOutput %d criteria %s",
1621 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001622 }
1623 }
1624
Eric Laurent16c66dd2019-05-01 17:54:10 -07001625 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001626}
1627
Eric Laurent8fc147b2018-07-22 19:13:55 -07001628status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001629{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001630 ALOGV("%s portId %d", __FUNCTION__, portId);
1631
1632 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1633 if (outputDesc == 0) {
1634 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001635 return BAD_VALUE;
1636 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001637 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001638
Eric Laurent8fc147b2018-07-22 19:13:55 -07001639 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001640 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001641
Eric Laurent733ce942017-12-07 12:18:25 -08001642 status_t status = outputDesc->start();
1643 if (status != NO_ERROR) {
1644 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001645 }
1646
Eric Laurent97ac8712018-07-27 18:59:02 -07001647 uint32_t delayMs;
1648 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001649
1650 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001651 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001652 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001653 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001654 if (delayMs != 0) {
1655 usleep(delayMs * 1000);
1656 }
1657
1658 return status;
1659}
1660
Eric Laurent97ac8712018-07-27 18:59:02 -07001661status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1662 const sp<TrackClientDescriptor>& client,
1663 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001664{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001665 // cannot start playback of STREAM_TTS if any other output is being used
1666 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001667
1668 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001669 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001670 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001671 auto clientStrategy = client->strategy();
1672 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001673 if (stream == AUDIO_STREAM_TTS) {
1674 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001675 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001676 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001677 return INVALID_OPERATION;
1678 } else {
1679 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1680 }
1681 } else {
1682 // some playback other than beacon starts
1683 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1684 }
1685
Eric Laurent77305a62016-07-25 16:39:22 -07001686 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001687 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001688 bool force = !outputDesc->isActive() &&
1689 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001690
François Gaffie11d30102018-11-02 16:09:09 +01001691 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001692 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001693 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001694 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001695 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001696 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001697 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001698 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001699 } else {
1700 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001701 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001702 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1703 AUDIO_FORMAT_DEFAULT);
1704 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1705 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001706 }
1707
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001708 // requiresMuteCheck is false when we can bypass mute strategy.
1709 // It covers a common case when there is no materially active audio
1710 // and muting would result in unnecessary delay and dropped audio.
1711 const uint32_t outputLatencyMs = outputDesc->latency();
1712 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1713
Eric Laurente552edb2014-03-10 17:42:56 -07001714 // increment usage count for this stream on the requested output:
1715 // NOTE that the usage count is the same for duplicated output and hardware output which is
1716 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001717 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001718
1719 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001720 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1721 client->isPreferredDeviceForExclusiveUse()) {
1722 // Preferred device may be exclusive, use only if no other active clients on this output
1723 devices = DeviceVector(
1724 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1725 } else {
1726 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1727 }
François Gaffie11d30102018-11-02 16:09:09 +01001728 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001729 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001730 }
1731 }
Eric Laurente552edb2014-03-10 17:42:56 -07001732
François Gaffiec005e562018-11-06 15:04:49 +01001733 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001734 selectOutputForMusicEffects();
1735 }
1736
François Gaffie1c878552018-11-22 16:53:21 +01001737 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001738 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001739 if (devices.isEmpty()) {
1740 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001741 }
François Gaffiec005e562018-11-06 15:04:49 +01001742 bool shouldWait =
1743 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1744 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1745 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001746 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001747 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001748 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001749 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001750 // An output has a shared device if
1751 // - managed by the same hw module
1752 // - supports the currently selected device
1753 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001754 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001755
Eric Laurent77305a62016-07-25 16:39:22 -07001756 // force a device change if any other output is:
1757 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001758 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001759 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001760 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001761 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001762 // change the device currently selected by the other output.
1763 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001764 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001765 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001766 force = true;
1767 }
1768 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001769 // a notification so that audio focus effect can propagate, or that a mute/unmute
1770 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001771 const uint32_t latencyMs = desc->latency();
1772 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1773
1774 if (shouldWait && isActive && (waitMs < latencyMs)) {
1775 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001776 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001777
1778 // Require mute check if another output is on a shared device
1779 // and currently active to have proper drain and avoid pops.
1780 // Note restoring AudioTracks onto this output needs to invoke
1781 // a volume ramp if there is no mute.
1782 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001783 }
1784 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001785
1786 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001787 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001788
Eric Laurente552edb2014-03-10 17:42:56 -07001789 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001790 auto &curves = getVolumeCurves(client->attributes());
1791 checkAndSetVolume(curves, client->volumeSource(),
1792 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001793 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001794 outputDesc->devices().types(), 0 /*delay*/,
1795 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001796
1797 // update the outputs if starting an output with a stream that can affect notification
1798 // routing
1799 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001800
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001801 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001802 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001803 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1804 }
Eric Laurentdc462862016-07-19 12:29:53 -07001805
1806 if (waitMs > muteWaitMs) {
1807 *delayMs = waitMs - muteWaitMs;
1808 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001809
1810 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1811 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1812 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1813 // change occurs after the MixerThread starts and causes a stream volume
1814 // glitch.
1815 //
1816 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001817 }
Eric Laurentdc462862016-07-19 12:29:53 -07001818
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001819 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001820 mEngine->getForceUse(
1821 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001822 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001823 }
1824
Eric Laurent97ac8712018-07-27 18:59:02 -07001825 // Automatically enable the remote submix input when output is started on a re routing mix
1826 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001827 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1828 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001829 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1830 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1831 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001832 "remote-submix",
1833 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001834 }
1835
Eric Laurente552edb2014-03-10 17:42:56 -07001836 return NO_ERROR;
1837}
1838
Eric Laurent8fc147b2018-07-22 19:13:55 -07001839status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001840{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001841 ALOGV("%s portId %d", __FUNCTION__, portId);
1842
1843 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1844 if (outputDesc == 0) {
1845 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001846 return BAD_VALUE;
1847 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001848 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001849
Eric Laurent97ac8712018-07-27 18:59:02 -07001850 ALOGV("stopOutput() output %d, stream %d, session %d",
1851 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001852
Eric Laurent97ac8712018-07-27 18:59:02 -07001853 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001854
Eric Laurent733ce942017-12-07 12:18:25 -08001855 if (status == NO_ERROR ) {
1856 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001857 }
1858 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001859}
1860
Eric Laurent97ac8712018-07-27 18:59:02 -07001861status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1862 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001863{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001864 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001865 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001866 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001867
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001868 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1869
François Gaffie1c878552018-11-22 16:53:21 +01001870 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1871 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001872 // Automatically disable the remote submix input when output is stopped on a
1873 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001874 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001875 if (isSingleDeviceType(
1876 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001877 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001878 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001879 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1880 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001881 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001882 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001883 }
1884 }
1885 bool forceDeviceUpdate = false;
1886 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01001887 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07001888 forceDeviceUpdate = true;
1889 }
1890
Eric Laurente552edb2014-03-10 17:42:56 -07001891 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07001892 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07001893
Eric Laurente552edb2014-03-10 17:42:56 -07001894 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01001895 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01001896 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01001897 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001898 // delay the device switch by twice the latency because stopOutput() is executed when
1899 // the track stop() command is received and at that time the audio track buffer can
1900 // still contain data that needs to be drained. The latency only covers the audio HAL
1901 // and kernel buffers. Also the latency does not always include additional delay in the
1902 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01001903 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001904
1905 // force restoring the device selection on other active outputs if it differs from the
1906 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001907 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001908 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001909 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001910 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001911 desc->isActive() &&
1912 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01001913 (newDevices != desc->devices())) {
1914 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1915 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07001916
François Gaffie11d30102018-11-02 16:09:09 +01001917 setOutputDevices(desc, newDevices2, force, delayMs);
1918
Eric Laurent57de36c2016-09-28 16:59:11 -07001919 // re-apply device specific volume if not done by setOutputDevice()
1920 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01001921 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07001922 }
Eric Laurente552edb2014-03-10 17:42:56 -07001923 }
1924 }
1925 // update the outputs if stopping one with a stream that can affect notification routing
1926 handleNotificationRoutingForStream(stream);
1927 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001928
1929 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1930 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08001931 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001932 }
1933
François Gaffiec005e562018-11-06 15:04:49 +01001934 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001935 selectOutputForMusicEffects();
1936 }
Eric Laurente552edb2014-03-10 17:42:56 -07001937 return NO_ERROR;
1938 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001939 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001940 return INVALID_OPERATION;
1941 }
1942}
1943
Eric Laurent8fc147b2018-07-22 19:13:55 -07001944void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001945{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001946 ALOGV("%s portId %d", __FUNCTION__, portId);
1947
1948 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1949 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07001950 // If an output descriptor is closed due to a device routing change,
1951 // then there are race conditions with releaseOutput from tracks
1952 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1953 // destroyed shortly thereafter.
1954 //
1955 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07001956 ALOGW("releaseOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001957 return;
1958 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959
1960 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001961
Eric Laurent8fc147b2018-07-22 19:13:55 -07001962 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1963 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001964 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07001965 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001966 return;
1967 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07001968 if (--outputDesc->mDirectOpenCount == 0) {
1969 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07001970 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001971 }
1972 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001973 // stopOutput() needs to be successfully called before releaseOutput()
1974 // otherwise there may be inaccurate stream reference counts.
1975 // This is checked in outputDesc->removeClient below.
1976 outputDesc->removeClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001977}
1978
Eric Laurentcaf7f482014-11-25 17:50:47 -08001979status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1980 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07001981 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001982 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001983 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001984 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001985 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001986 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001987 input_type_t *inputType,
1988 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001989{
François Gaffiec005e562018-11-06 15:04:49 +01001990 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1991 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1992 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001993
Eric Laurentad2e7b92017-09-14 20:06:42 -07001994 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08001995 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01001996 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001997 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01001998 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07001999 sp<AudioInputDescriptor> inputDesc;
2000 sp<RecordClientDescriptor> clientDesc;
2001 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002002 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002003
2004 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2005 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2006 return INVALID_OPERATION;
2007 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002008
Francois Gaffie716e1432019-01-14 16:58:59 +01002009 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2010 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002011 }
2012
Paul McLean466dc8e2015-04-17 13:15:36 -06002013 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002014 sp<DeviceDescriptor> explicitRoutingDevice =
2015 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002016
Eric Laurentad2e7b92017-09-14 20:06:42 -07002017 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2018 // possible
2019 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2020 *input != AUDIO_IO_HANDLE_NONE) {
2021 ssize_t index = mInputs.indexOfKey(*input);
2022 if (index < 0) {
2023 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2024 status = BAD_VALUE;
2025 goto error;
2026 }
2027 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002028 RecordClientVector clients = inputDesc->getClientsForSession(session);
2029 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002030 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2031 status = BAD_VALUE;
2032 goto error;
2033 }
2034 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2035 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002036 // corresponds to a new client and is only permitted from the same UID.
2037 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002038 if (clients.size() > 1) {
2039 for (const auto& client : clients) {
2040 // The client map is ordered by key values (portId) and portIds are allocated
2041 // incrementaly. So the first client in this list is the one opened by audio flinger
2042 // when the mmap stream is created and should be ignored as it does not correspond
2043 // to an actual client
2044 if (client == *clients.cbegin()) {
2045 continue;
2046 }
2047 if (uid != client->uid() && !client->isSilenced()) {
2048 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2049 uid, client->portId(), client->uid());
2050 status = INVALID_OPERATION;
2051 goto error;
2052 }
Eric Laurent331679c2018-04-16 17:03:16 -07002053 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002054 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002055 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002056 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002057
Eric Laurent8f42ea12018-08-08 09:08:25 -07002058 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002059 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002060 }
2061
2062 *input = AUDIO_IO_HANDLE_NONE;
2063 *inputType = API_INPUT_INVALID;
2064
Francois Gaffie716e1432019-01-14 16:58:59 +01002065 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002066
Francois Gaffie716e1432019-01-14 16:58:59 +01002067 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2068 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2069 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002070 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002071 ALOGW("%s could not find input mix for attr %s",
2072 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002073 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002074 }
jiabinc1de2df2019-05-07 14:26:40 -07002075 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2076 String8(attr->tags + strlen("addr=")),
2077 AUDIO_FORMAT_DEFAULT);
2078 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002079 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002080 __func__, attributes.source, attributes.tags);
2081 status = BAD_VALUE;
2082 goto error;
2083 }
2084
Kevin Rocard25f9b052019-02-27 15:08:54 -08002085 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2086 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2087 } else {
2088 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2089 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002090 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002091 if (explicitRoutingDevice != nullptr) {
2092 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002093 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002094 // Prevent from storing invalid requested device id in clients
2095 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002096 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
Eric Laurent97ac8712018-07-27 18:59:02 -07002097 }
François Gaffie11d30102018-11-02 16:09:09 +01002098 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002099 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002100 status = BAD_VALUE;
2101 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002102 }
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002103 if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002104 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2105 // there is an external policy, but this input is attached to a mix of recorders,
2106 // meaning it receives audio injected into the framework, so the recorder doesn't
2107 // know about it and is therefore considered "legacy"
2108 *inputType = API_INPUT_LEGACY;
2109 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002110 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002111 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002112 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002113 } else {
2114 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002115 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002116
Eric Laurent599c7582015-12-07 18:05:55 -08002117 }
2118
François Gaffiec005e562018-11-06 15:04:49 +01002119 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002120 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002121 status = INVALID_OPERATION;
2122 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002123 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002124
Eric Laurent8f42ea12018-08-08 09:08:25 -07002125exit:
2126
François Gaffiec005e562018-11-06 15:04:49 +01002127 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2128 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002129
Francois Gaffie716e1432019-01-14 16:58:59 +01002130 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002131 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002132 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002133
Mikhail Naganov2996f672019-04-18 12:29:59 -07002134 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002135 requestedDeviceId, attributes.source, flags,
2136 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002137 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002138 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139
2140 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2141 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002142
Eric Laurent599c7582015-12-07 18:05:55 -08002143 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002144
2145error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002146 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002147}
2148
2149
François Gaffie11d30102018-11-02 16:09:09 +01002150audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002151 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002152 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002153 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002154 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002155 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002156{
2157 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002158 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002159 bool isSoundTrigger = false;
2160
François Gaffiec005e562018-11-06 15:04:49 +01002161 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002162 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2163 if (index >= 0) {
2164 input = mSoundTriggerSessions.valueFor(session);
2165 isSoundTrigger = true;
2166 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2167 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2168 } else {
2169 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002170 }
François Gaffiec005e562018-11-06 15:04:49 +01002171 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002172 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002173 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002174 }
2175
Andy Hungf129b032015-04-07 13:45:50 -07002176 // find a compatible input profile (not necessarily identical in parameters)
2177 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002178 // sampling rate and flags may be updated by getInputProfile
2179 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2180 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002181 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002182 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002183 audio_input_flags_t profileFlags = flags;
2184 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002185 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002186 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002187 profileFlags);
2188 if (profile != 0) {
2189 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002190 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2191 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002192 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2193 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2194 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002195 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2196 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2197 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002198 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002199 }
Eric Laurente552edb2014-03-10 17:42:56 -07002200 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002201 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002202 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002203 if (samplingRate == 0) {
2204 samplingRate = profileSamplingRate;
2205 }
Eric Laurente552edb2014-03-10 17:42:56 -07002206
Eric Laurent322b4d22015-04-03 15:57:54 -07002207 if (profile->getModuleHandle() == 0) {
2208 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002209 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002210 }
2211
Eric Laurent3974e3b2017-12-07 17:58:43 -08002212 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002213 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002214 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002215 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002216 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002217 continue;
2218 }
2219 // if sound trigger, reuse input if used by other sound trigger on same session
2220 // else
2221 // reuse input if active client app is not in IDLE state
2222 //
2223 RecordClientVector clients = desc->clientsList();
2224 bool doClose = false;
2225 for (const auto& client : clients) {
2226 if (isSoundTrigger != client->isSoundTrigger()) {
2227 continue;
2228 }
2229 if (client->isSoundTrigger()) {
2230 if (session == client->session()) {
2231 return desc->mIoHandle;
2232 }
2233 continue;
2234 }
2235 if (client->active() && client->appState() != APP_STATE_IDLE) {
2236 return desc->mIoHandle;
2237 }
2238 doClose = true;
2239 }
2240 if (doClose) {
2241 closeInput(desc->mIoHandle);
2242 } else {
2243 i++;
2244 }
2245 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002246 }
2247
Eric Laurentfe231122017-11-17 17:48:06 -08002248 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002249
Eric Laurentfe231122017-11-17 17:48:06 -08002250 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2251 lConfig.sample_rate = profileSamplingRate;
2252 lConfig.channel_mask = profileChannelMask;
2253 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002254
François Gaffie11d30102018-11-02 16:09:09 +01002255 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002256
2257 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002258 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002259 (profileSamplingRate != lConfig.sample_rate) ||
2260 !audio_formats_match(profileFormat, lConfig.format) ||
2261 (profileChannelMask != lConfig.channel_mask)) {
2262 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002263 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002264 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002265 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002266 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002267 }
Eric Laurent599c7582015-12-07 18:05:55 -08002268 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002269 }
2270
Eric Laurentc722f302014-12-10 11:21:49 -08002271 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002272
Eric Laurent599c7582015-12-07 18:05:55 -08002273 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002274 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002275
Eric Laurent599c7582015-12-07 18:05:55 -08002276 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002277}
2278
Eric Laurent4eb58f12018-12-07 16:41:02 -08002279status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002280{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002281 ALOGV("%s portId %d", __FUNCTION__, portId);
2282
2283 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2284 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002285 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002286 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002288 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002289 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002290 if (client->active()) {
2291 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2292 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002293 }
2294
Eric Laurent8f42ea12018-08-08 09:08:25 -07002295 audio_session_t session = client->session();
2296
Eric Laurent4eb58f12018-12-07 16:41:02 -08002297 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002298
Eric Laurent4eb58f12018-12-07 16:41:02 -08002299 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002300
Eric Laurent4eb58f12018-12-07 16:41:02 -08002301 status_t status = inputDesc->start();
2302 if (status != NO_ERROR) {
2303 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002304 }
Eric Laurente552edb2014-03-10 17:42:56 -07002305
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002306 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002307 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002308 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002309
Eric Laurent8f42ea12018-08-08 09:08:25 -07002310 // indicate active capture to sound trigger service if starting capture from a mic on
2311 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002312 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002313 if (device != nullptr) {
2314 status = setInputDevice(input, device, true /* force */);
2315 } else {
2316 ALOGW("%s no new input device can be found for descriptor %d",
2317 __FUNCTION__, inputDesc->getId());
2318 status = BAD_VALUE;
2319 }
Eric Laurente552edb2014-03-10 17:42:56 -07002320
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002321 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002322 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002323 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002324 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002325 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2326 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002327 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002328 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002329
François Gaffie11d30102018-11-02 16:09:09 +01002330 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2331 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002332 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002333 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002334 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002335
Eric Laurent8f42ea12018-08-08 09:08:25 -07002336 // automatically enable the remote submix output when input is started if not
2337 // used by a policy mix of type MIX_TYPE_RECORDERS
2338 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002339 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002340 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002341 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002342 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002343 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2344 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002345 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002346 if (address != "") {
2347 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2348 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002349 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002350 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002351 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002352 } else if (status != NO_ERROR) {
2353 // Restore client activity state.
2354 inputDesc->setClientActive(client, false);
2355 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002356 }
2357
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002358 ALOGV("%s input %d source = %d status = %d exit",
2359 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002360
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002361 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002362}
2363
Eric Laurent8fc147b2018-07-22 19:13:55 -07002364status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002365{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002366 ALOGV("%s portId %d", __FUNCTION__, portId);
2367
2368 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2369 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002370 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002371 return BAD_VALUE;
2372 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002373 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002374 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002375 if (!client->active()) {
2376 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002377 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002378 }
2379
Eric Laurent8f42ea12018-08-08 09:08:25 -07002380 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002381
Eric Laurent8f42ea12018-08-08 09:08:25 -07002382 inputDesc->stop();
2383 if (inputDesc->isActive()) {
2384 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2385 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002386 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002387 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002388 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002389 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2390 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002391 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002392 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002393
2394 // automatically disable the remote submix output when input is stopped if not
2395 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002396 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002397 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002398 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002399 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002400 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2401 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002402 }
2403 if (address != "") {
2404 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2405 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002406 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002407 }
2408 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002409 resetInputDevice(input);
2410
2411 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2412 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002413 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2414 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002415 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002416 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002417 }
2418 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002419 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002420 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002421}
2422
Eric Laurent8fc147b2018-07-22 19:13:55 -07002423void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002424{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002425 ALOGV("%s portId %d", __FUNCTION__, portId);
2426
2427 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2428 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002429 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002430 return;
2431 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002432 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002433 audio_io_handle_t input = inputDesc->mIoHandle;
2434
Eric Laurent8f42ea12018-08-08 09:08:25 -07002435 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002436
Andy Hung39efb7a2018-09-26 15:39:28 -07002437 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002438
Andy Hung39efb7a2018-09-26 15:39:28 -07002439 if (inputDesc->getClientCount() > 0) {
2440 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002441 return;
2442 }
2443
Eric Laurent05b90f82014-08-27 15:32:29 -07002444 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002445 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002446 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002447}
2448
Eric Laurent8f42ea12018-08-08 09:08:25 -07002449void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002450{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002451 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002452
2453 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002454 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002455 }
2456}
2457
Eric Laurent8f42ea12018-08-08 09:08:25 -07002458void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2459{
2460 stopInput(portId);
2461 releaseInput(portId);
2462}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002463
Eric Laurent0dd51852019-04-19 18:18:58 -07002464void AudioPolicyManager::checkCloseInputs() {
2465 // After connecting or disconnecting an input device, close input if:
2466 // - it has no client (was just opened to check profile) OR
2467 // - none of its supported devices are connected anymore OR
2468 // - one of its clients cannot be routed to one of its supported
2469 // devices anymore. Otherwise update device selection
2470 std::vector<audio_io_handle_t> inputsToClose;
2471 for (size_t i = 0; i < mInputs.size(); i++) {
2472 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2473 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002474 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002475 inputsToClose.push_back(mInputs.keyAt(i));
2476 } else {
2477 bool close = false;
2478 for (const auto& client : input->clientsList()) {
2479 sp<DeviceDescriptor> device =
2480 mEngine->getInputDeviceForAttributes(client->attributes());
2481 if (!input->supportedDevices().contains(device)) {
2482 close = true;
2483 break;
2484 }
2485 }
2486 if (close) {
2487 inputsToClose.push_back(mInputs.keyAt(i));
2488 } else {
2489 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2490 }
2491 }
2492 }
2493
2494 for (const audio_io_handle_t handle : inputsToClose) {
2495 ALOGV("%s closing input %d", __func__, handle);
2496 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002497 }
Eric Laurentd4692962014-05-05 18:13:44 -07002498}
2499
François Gaffie251c7f02018-11-07 10:41:08 +01002500void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002501{
2502 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002503 if (indexMin < 0 || indexMax < 0) {
2504 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2505 return;
2506 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002507 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002508
2509 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002510 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2511 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002512 continue;
2513 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002514 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002515 }
Eric Laurente552edb2014-03-10 17:42:56 -07002516}
2517
Eric Laurente0720872014-03-11 09:30:41 -07002518status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002519 int index,
2520 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002521{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002522 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002523 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2524 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2525 return NO_ERROR;
2526 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002527 ALOGV("%s: stream %s attributes=%s", __func__,
2528 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002529 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002530}
2531
Eric Laurente0720872014-03-11 09:30:41 -07002532status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002533 int *index,
2534 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002535{
François Gaffiec005e562018-11-06 15:04:49 +01002536 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2537 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002538 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002539 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002540 deviceTypes = mEngine->getOutputDevicesForStream(
2541 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002542 }
jiabin9a3361e2019-10-01 09:38:30 -07002543 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002544}
2545
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002546status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002547 int index,
2548 audio_devices_t device)
2549{
2550 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002551 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2552 if (group == VOLUME_GROUP_NONE) {
2553 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002554 return BAD_VALUE;
2555 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002556 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002557 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002558 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002559 VolumeSource vs = toVolumeSource(group);
2560 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2561
2562 status = setVolumeCurveIndex(index, device, curves);
2563 if (status != NO_ERROR) {
2564 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2565 return status;
2566 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002567
jiabin9a3361e2019-10-01 09:38:30 -07002568 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002569 auto curCurvAttrs = curves.getAttributes();
2570 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2571 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002572 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002573 } else if (!curves.getStreamTypes().empty()) {
2574 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002575 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002576 } else {
2577 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2578 return BAD_VALUE;
2579 }
jiabin9a3361e2019-10-01 09:38:30 -07002580 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2581 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002582
François Gaffiecfe17322018-11-07 13:41:29 +01002583 // update volume on all outputs and streams matching the following:
2584 // - The requested stream (or a stream matching for volume control) is active on the output
2585 // - The device (or devices) selected by the engine for this stream includes
2586 // the requested device
2587 // - For non default requested device, currently selected device on the output is either the
2588 // requested device or one of the devices selected by the engine for this stream
2589 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2590 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002591 for (size_t i = 0; i < mOutputs.size(); i++) {
2592 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002593 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002594
jiabin9a3361e2019-10-01 09:38:30 -07002595 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2596 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002597 }
François Gaffieed91f582020-01-31 10:35:37 +01002598 if (!(desc->isActive(vs) || isInCall())) {
2599 continue;
2600 }
2601 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2602 curDevices.find(device) == curDevices.end()) {
2603 continue;
2604 }
2605 bool applyVolume = false;
2606 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2607 curSrcDevices.insert(device);
2608 applyVolume = (curSrcDevices.find(
2609 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2610 } else {
2611 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2612 }
2613 if (!applyVolume) {
2614 continue; // next output
2615 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002616 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2617 // If a higher priority strategy is active, and the output is routed to a device with a
2618 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002619 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002620 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002621 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2622 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2623 false /*preferredDevice*/);
2624 if (activeClients.empty()) {
2625 continue;
2626 }
2627 bool isPreempted = false;
2628 bool isHigherPriority = productStrategy < strategy;
2629 for (const auto &client : activeClients) {
2630 if (isHigherPriority && (client->volumeSource() != vs)) {
2631 ALOGV("%s: Strategy=%d (\nrequester:\n"
2632 " group %d, volumeGroup=%d attributes=%s)\n"
2633 " higher priority source active:\n"
2634 " volumeGroup=%d attributes=%s) \n"
2635 " on output %zu, bailing out", __func__, productStrategy,
2636 group, group, toString(attributes).c_str(),
2637 client->volumeSource(), toString(client->attributes()).c_str(), i);
2638 applyVolume = false;
2639 isPreempted = true;
2640 break;
2641 }
2642 // However, continue for loop to ensure no higher prio clients running on output
2643 if (client->volumeSource() == vs) {
2644 applyVolume = true;
2645 }
2646 }
2647 if (isPreempted || applyVolume) {
2648 break;
2649 }
2650 }
2651 if (!applyVolume) {
2652 continue; // next output
2653 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002654 }
François Gaffieed91f582020-01-31 10:35:37 +01002655 //FIXME: workaround for truncated touch sounds
2656 // delayed volume change for system stream to be removed when the problem is
2657 // handled by system UI
2658 status_t volStatus = checkAndSetVolume(
2659 curves, vs, index, desc, curDevices,
2660 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2661 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2662 if (volStatus != NO_ERROR) {
2663 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002664 }
2665 }
François Gaffiecfe17322018-11-07 13:41:29 +01002666 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2667 return status;
2668}
2669
François Gaffieaaac0fd2018-11-22 17:56:39 +01002670status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002671 audio_devices_t device,
2672 IVolumeCurves &volumeCurves)
2673{
2674 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2675 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002676 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2677 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002678 (index > volumeCurves.getVolumeIndexMax())) {
2679 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2680 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2681 return BAD_VALUE;
2682 }
2683 if (!audio_is_output_device(device)) {
2684 return BAD_VALUE;
2685 }
2686
2687 // Force max volume if stream cannot be muted
2688 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2689
François Gaffieaaac0fd2018-11-22 17:56:39 +01002690 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002691 volumeCurves.addCurrentVolumeIndex(device, index);
2692 return NO_ERROR;
2693}
2694
2695status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2696 int &index,
2697 audio_devices_t device)
2698{
2699 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2700 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002701 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002702 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002703 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2704 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002705 }
jiabin9a3361e2019-10-01 09:38:30 -07002706 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002707}
2708
2709status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2710 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002711 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002712{
jiabin9a3361e2019-10-01 09:38:30 -07002713 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002714 return BAD_VALUE;
2715 }
jiabin9a3361e2019-10-01 09:38:30 -07002716 index = curves.getVolumeIndex(deviceTypes);
2717 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002718 return NO_ERROR;
2719}
2720
2721status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2722 int &index)
2723{
2724 index = getVolumeCurves(attr).getVolumeIndexMin();
2725 return NO_ERROR;
2726}
2727
2728status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2729 int &index)
2730{
2731 index = getVolumeCurves(attr).getVolumeIndexMax();
2732 return NO_ERROR;
2733}
2734
Eric Laurent36829f92017-04-07 19:04:42 -07002735audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002736{
2737 // select one output among several suitable for global effects.
2738 // The priority is as follows:
2739 // 1: An offloaded output. If the effect ends up not being offloadable,
2740 // AudioFlinger will invalidate the track and the offloaded output
2741 // will be closed causing the effect to be moved to a PCM output.
2742 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002743 // 3: The primary output
2744 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002745
François Gaffiec005e562018-11-06 15:04:49 +01002746 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2747 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002748 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002749
Eric Laurent36829f92017-04-07 19:04:42 -07002750 if (outputs.size() == 0) {
2751 return AUDIO_IO_HANDLE_NONE;
2752 }
Eric Laurente552edb2014-03-10 17:42:56 -07002753
Eric Laurent36829f92017-04-07 19:04:42 -07002754 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2755 bool activeOnly = true;
2756
2757 while (output == AUDIO_IO_HANDLE_NONE) {
2758 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2759 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2760 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2761
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002762 for (audio_io_handle_t output : outputs) {
2763 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002764 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002765 continue;
2766 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002767 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2768 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002769 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002770 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002771 }
2772 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002773 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002774 }
2775 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002776 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002777 }
2778 }
2779 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2780 output = outputOffloaded;
2781 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2782 output = outputDeepBuffer;
2783 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2784 output = outputPrimary;
2785 } else {
2786 output = outputs[0];
2787 }
2788 activeOnly = false;
2789 }
2790
2791 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002792 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002793 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2794 mMusicEffectOutput = output;
2795 }
2796
2797 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002798 return output;
2799}
2800
Eric Laurent36829f92017-04-07 19:04:42 -07002801audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2802{
2803 return selectOutputForMusicEffects();
2804}
2805
Eric Laurente0720872014-03-11 09:30:41 -07002806status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002807 audio_io_handle_t io,
2808 uint32_t strategy,
2809 int session,
2810 int id)
2811{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002812 if (session != AUDIO_SESSION_DEVICE) {
2813 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002814 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002815 index = mInputs.indexOfKey(io);
2816 if (index < 0) {
2817 ALOGW("registerEffect() unknown io %d", io);
2818 return INVALID_OPERATION;
2819 }
Eric Laurente552edb2014-03-10 17:42:56 -07002820 }
2821 }
François Gaffiec005e562018-11-06 15:04:49 +01002822 return mEffects.registerEffect(desc, io, session, id,
2823 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2824 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002825}
2826
Eric Laurentc241b0d2018-11-28 09:08:49 -08002827status_t AudioPolicyManager::unregisterEffect(int id)
2828{
2829 if (mEffects.getEffect(id) == nullptr) {
2830 return INVALID_OPERATION;
2831 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002832 if (mEffects.isEffectEnabled(id)) {
2833 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2834 setEffectEnabled(id, false);
2835 }
2836 return mEffects.unregisterEffect(id);
2837}
2838
2839status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2840{
2841 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2842 if (effect == nullptr) {
2843 return INVALID_OPERATION;
2844 }
2845
2846 status_t status = mEffects.setEffectEnabled(id, enabled);
2847 if (status == NO_ERROR) {
2848 mInputs.trackEffectEnabled(effect, enabled);
2849 }
2850 return status;
2851}
2852
Eric Laurent6c796322019-04-09 14:13:17 -07002853
2854status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2855{
2856 mEffects.moveEffects(ids, io);
2857 return NO_ERROR;
2858}
2859
Eric Laurentc75307b2015-03-17 15:29:32 -07002860bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2861{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002862 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002863}
2864
2865bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2866{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002867 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002868}
2869
Eric Laurente0720872014-03-11 09:30:41 -07002870bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002871{
2872 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002873 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002874 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002875 return true;
2876 }
2877 }
2878 return false;
2879}
2880
Eric Laurent275e8e92014-11-30 15:14:47 -08002881// Register a list of custom mixes with their attributes and format.
2882// When a mix is registered, corresponding input and output profiles are
2883// added to the remote submix hw module. The profile contains only the
2884// parameters (sampling rate, format...) specified by the mix.
2885// The corresponding input remote submix device is also connected.
2886//
2887// When a remote submix device is connected, the address is checked to select the
2888// appropriate profile and the corresponding input or output stream is opened.
2889//
2890// When capture starts, getInputForAttr() will:
2891// - 1 look for a mix matching the address passed in attribtutes tags if any
2892// - 2 if none found, getDeviceForInputSource() will:
2893// - 2.1 look for a mix matching the attributes source
2894// - 2.2 if none found, default to device selection by policy rules
2895// At this time, the corresponding output remote submix device is also connected
2896// and active playback use cases can be transferred to this mix if needed when reconnecting
2897// after AudioTracks are invalidated
2898//
2899// When playback starts, getOutputForAttr() will:
2900// - 1 look for a mix matching the address passed in attribtutes tags if any
2901// - 2 if none found, look for a mix matching the attributes usage
2902// - 3 if none found, default to device and output selection by policy rules.
2903
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002904status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002905{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002906 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2907 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07002908 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002909 sp<HwModule> rSubmixModule;
2910 // examine each mix's route type
2911 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002912 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08002913 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2914 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2915 ALOGE("Unsupported Policy Mix %zu of %zu: "
2916 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2917 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002918 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002919 break;
2920 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002921 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2922 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07002923 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002924 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2925 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002926 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08002927 rSubmixModule = mHwModules.getModuleFromName(
2928 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2929 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002930 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08002931 i);
2932 res = INVALID_OPERATION;
2933 break;
2934 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002935 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002936
Eric Laurent97ac8712018-07-27 18:59:02 -07002937 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002938 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07002939 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002940 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002941 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2942 } else {
2943 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2944 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07002945 }
François Gaffie036e1e92015-03-19 10:16:24 +01002946
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002947 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002948 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002949 res = INVALID_OPERATION;
2950 break;
2951 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002952 audio_config_t outputConfig = mix.mFormat;
2953 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07002954 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
2955 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002956 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2957 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07002958 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002959 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07002960 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002961 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002962
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002963 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07002964 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2965 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2966 ALOGE("Failed to set remote submix device available, type %u, address %s",
2967 mix.mDeviceType, address.string());
2968 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002969 }
Eric Laurent97ac8712018-07-27 18:59:02 -07002970 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2971 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08002972 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002973 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08002974 i, mixes.size(), type, address.string());
2975
2976 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2977 mix.mDeviceType, mix.mDeviceAddress,
2978 String8(), AUDIO_FORMAT_DEFAULT);
2979 if (device == nullptr) {
2980 res = INVALID_OPERATION;
2981 break;
2982 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002983
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002984 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07002985 // First try to find an already opened output supporting the device
2986 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002987 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08002988
Eric Laurentc529cf62020-04-17 18:19:10 -07002989 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07002990 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08002991 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2992 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002993 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002994 } else {
2995 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002996 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002997 }
2998 }
Eric Laurentc529cf62020-04-17 18:19:10 -07002999 // If no output found, try to find a direct output profile supporting the device
3000 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3001 sp<HwModule> module = mHwModules[i];
3002 for (size_t j = 0;
3003 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3004 j++) {
3005 sp<IOProfile> profile = module->getOutputProfiles()[j];
3006 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3007 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3008 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3009 address.string());
3010 res = INVALID_OPERATION;
3011 } else {
3012 foundOutput = true;
3013 }
3014 }
3015 }
3016 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003017 if (res != NO_ERROR) {
3018 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003019 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003020 res = INVALID_OPERATION;
3021 break;
3022 } else if (!foundOutput) {
3023 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003024 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003025 res = INVALID_OPERATION;
3026 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003027 } else {
3028 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003029 }
Eric Laurentc722f302014-12-10 11:21:49 -08003030 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003031 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003032 if (res != NO_ERROR) {
3033 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003034 } else if (checkOutputs) {
3035 checkForDeviceAndOutputChanges();
3036 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003037 }
3038 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003039}
3040
3041status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3042{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003043 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003044 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003045 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003046 sp<HwModule> rSubmixModule;
3047 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003048 for (const auto& mix : mixes) {
3049 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003050
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003051 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003052 rSubmixModule = mHwModules.getModuleFromName(
3053 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3054 if (rSubmixModule == 0) {
3055 res = INVALID_OPERATION;
3056 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003057 }
3058 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003059
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003060 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003061
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003062 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003063 res = INVALID_OPERATION;
3064 continue;
3065 }
3066
Kevin Rocard04ed0462019-05-02 17:53:24 -07003067 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3068 if (getDeviceConnectionState(device, address.string()) ==
3069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3070 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3071 address.string(), "remote-submix",
3072 AUDIO_FORMAT_DEFAULT);
3073 if (res != OK) {
3074 ALOGE("Error making RemoteSubmix device unavailable for mix "
3075 "with type %d, address %s", device, address.string());
3076 }
3077 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003078 }
jiabin5740f082019-08-19 15:08:30 -07003079 rSubmixModule->removeOutputProfile(address.c_str());
3080 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003081
Kevin Rocard153f92d2018-12-18 18:33:28 -08003082 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003083 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003084 res = INVALID_OPERATION;
3085 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003086 } else {
3087 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003088 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003089 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003090 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003091 if (res == NO_ERROR && checkOutputs) {
3092 checkForDeviceAndOutputChanges();
3093 updateCallAndOutputRouting();
3094 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003095 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003096}
3097
Mikhail Naganov100f0122018-11-29 11:22:16 -08003098void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3099{
3100 size_t i = 0;
3101 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3102 for (const auto& fmt : mManualSurroundFormats) {
3103 if (i++ != 0) dst->append(", ");
3104 std::string sfmt;
3105 FormatConverter::toString(fmt, sfmt);
3106 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3107 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3108 }
3109}
3110
Eric Laurentc529cf62020-04-17 18:19:10 -07003111// Returns true if all devices types match the predicate and are supported by one HW module
3112bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003113 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003114 std::function<bool(audio_devices_t)> predicate,
3115 const char *context) {
3116 for (size_t i = 0; i < devices.size(); i++) {
3117 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003118 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003119 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003120 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003121 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003122 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003123 return false;
3124 }
3125 }
3126 return true;
3127}
3128
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003129status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003130 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003131 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003132 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3133 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003134 }
3135 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003136 if (res != NO_ERROR) {
3137 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3138 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003139 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003140
3141 checkForDeviceAndOutputChanges();
3142 updateCallAndOutputRouting();
3143
3144 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003145}
3146
3147status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3148 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003149 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3150 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003151 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003152 __FUNCTION__, uid);
3153 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003154 }
3155
Eric Laurentc529cf62020-04-17 18:19:10 -07003156 checkForDeviceAndOutputChanges();
3157 updateCallAndOutputRouting();
3158
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003159 return res;
3160}
3161
jiabin0a488932020-08-07 17:32:40 -07003162status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3163 device_role_t role,
3164 const AudioDeviceTypeAddrVector &devices) {
3165 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3166 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003167
Eric Laurentc529cf62020-04-17 18:19:10 -07003168 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003169 return BAD_VALUE;
3170 }
jiabin0a488932020-08-07 17:32:40 -07003171 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003172 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003173 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3174 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003175 return status;
3176 }
3177
3178 checkForDeviceAndOutputChanges();
3179 updateCallAndOutputRouting();
3180
3181 return NO_ERROR;
3182}
3183
3184void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3185{
3186 uint32_t waitMs = 0;
3187 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
3188 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
3189 waitMs = updateCallRouting(newDevices, delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003190 // Only apply special touch sound delay once
3191 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003192 }
3193 for (size_t i = 0; i < mOutputs.size(); i++) {
3194 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3195 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3196 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3197 // As done in setDeviceConnectionState, we could also fix default device issue by
3198 // preventing the force re-routing in case of default dev that distinguishes on address.
3199 // Let's give back to engine full device choice decision however.
3200 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003201 // Only apply special touch sound delay once
3202 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003203 }
3204 if (forceVolumeReeval && !newDevices.isEmpty()) {
3205 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3206 }
3207 }
3208}
3209
jiabin0a488932020-08-07 17:32:40 -07003210status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3211 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003212{
jiabin0a488932020-08-07 17:32:40 -07003213 ALOGI("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003214
jiabin0a488932020-08-07 17:32:40 -07003215 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003216 if (status != NO_ERROR) {
3217 ALOGW("Engine could not remove preferred device for strategy %d", strategy);
3218 return status;
3219 }
3220
3221 checkForDeviceAndOutputChanges();
3222 updateCallAndOutputRouting();
3223
3224 return NO_ERROR;
3225}
3226
jiabin0a488932020-08-07 17:32:40 -07003227status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3228 device_role_t role,
3229 AudioDeviceTypeAddrVector &devices) {
3230 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003231}
3232
Jiabin Huang3b98d322020-09-03 17:54:16 +00003233status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3234 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3235 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3236 dumpAudioDeviceTypeAddrVector(devices).c_str());
3237
Mikhail Naganov55773032020-10-01 15:08:13 -07003238 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003239 return BAD_VALUE;
3240 }
3241 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3242 ALOGW_IF(status != NO_ERROR,
3243 "Engine could not set preferred devices %s for audio source %d role %d",
3244 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3245
3246 return status;
3247}
3248
3249status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3250 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3251 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3252 dumpAudioDeviceTypeAddrVector(devices).c_str());
3253
Mikhail Naganov55773032020-10-01 15:08:13 -07003254 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003255 return BAD_VALUE;
3256 }
3257 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3258 ALOGW_IF(status != NO_ERROR,
3259 "Engine could not add preferred devices %s for audio source %d role %d",
3260 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3261
3262 return status;
3263}
3264
3265status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3266 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3267{
3268 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3269 dumpAudioDeviceTypeAddrVector(devices).c_str());
3270
Mikhail Naganov55773032020-10-01 15:08:13 -07003271 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003272 return BAD_VALUE;
3273 }
3274
3275 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3276 audioSource, role, devices);
3277 ALOGW_IF(status != NO_ERROR,
3278 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3279
3280 return status;
3281}
3282
3283status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3284 device_role_t role) {
3285 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3286
3287 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3288 ALOGW_IF(status != NO_ERROR,
3289 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3290
3291 return status;
3292}
3293
3294status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3295 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3296 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3297}
3298
Oscar Azucena90e77632019-11-27 17:12:28 -08003299status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003300 const AudioDeviceTypeAddrVector& devices) {
3301 ALOGI("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003302 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3303 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003304 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003305 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3306 if (status != NO_ERROR) {
3307 ALOGE("%s() could not set device affinity for userId %d",
3308 __FUNCTION__, userId);
3309 return status;
3310 }
3311
3312 // reevaluate outputs for all devices
3313 checkForDeviceAndOutputChanges();
3314 updateCallAndOutputRouting();
3315
3316 return NO_ERROR;
3317}
3318
3319status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
3320 ALOGI("%s() userId=%d", __FUNCTION__, userId);
3321 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3322 if (status != NO_ERROR) {
3323 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3324 __FUNCTION__, userId);
3325 return status;
3326 }
3327
3328 // reevaluate outputs for all devices
3329 checkForDeviceAndOutputChanges();
3330 updateCallAndOutputRouting();
3331
3332 return NO_ERROR;
3333}
3334
Andy Hungc29d82b2018-10-05 12:23:17 -07003335void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003336{
Andy Hungc29d82b2018-10-05 12:23:17 -07003337 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3338 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003339 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003340 std::string stateLiteral;
3341 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003342 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003343 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3344 "communications", "media", "record", "dock", "system",
3345 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3346 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3347 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003348 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3349 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3350 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3351 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3352 dst->append(" (MANUAL: ");
3353 dumpManualSurroundFormats(dst);
3354 dst->append(")");
3355 }
3356 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003357 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003358 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3359 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
3360 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
3361 mAvailableOutputDevices.dump(dst, String8("Available output"));
3362 mAvailableInputDevices.dump(dst, String8("Available input"));
3363 mHwModulesAll.dump(dst);
3364 mOutputs.dump(dst);
3365 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003366 mEffects.dump(dst);
3367 mAudioPatches.dump(dst);
3368 mPolicyMixes.dump(dst);
3369 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003370
Kevin Rocardb99cc752019-03-21 20:52:24 -07003371 dst->appendFormat(" AllowedCapturePolicies:\n");
3372 for (auto& policy : mAllowedCapturePolicies) {
3373 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3374 }
3375
François Gaffiec005e562018-11-06 15:04:49 +01003376 dst->appendFormat("\nPolicy Engine dump:\n");
3377 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003378}
3379
3380status_t AudioPolicyManager::dump(int fd)
3381{
3382 String8 result;
3383 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003384 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003385 return NO_ERROR;
3386}
3387
Kevin Rocardb99cc752019-03-21 20:52:24 -07003388status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3389{
3390 mAllowedCapturePolicies[uid] = capturePolicy;
3391 return NO_ERROR;
3392}
3393
Eric Laurente552edb2014-03-10 17:42:56 -07003394// This function checks for the parameters which can be offloaded.
3395// This can be enhanced depending on the capability of the DSP and policy
3396// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07003397bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003398{
3399 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003400 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07003401 offloadInfo.sample_rate, offloadInfo.channel_mask,
3402 offloadInfo.format,
3403 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3404 offloadInfo.has_video);
3405
Andy Hung2ddee192015-12-18 17:34:44 -08003406 if (mMasterMono) {
3407 return false; // no offloading if mono is set.
3408 }
3409
Eric Laurente552edb2014-03-10 17:42:56 -07003410 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003411 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3412 ALOGV("offload disabled by audio.offload.disable");
3413 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07003414 }
3415
3416 // Check if stream type is music, then only allow offload as of now.
3417 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3418 {
3419 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3420 return false;
3421 }
3422
3423 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003424 const bool allowOffloadWithVideo =
3425 property_get_bool("audio.offload.video", false /* default_value */);
3426 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07003427 ALOGV("isOffloadSupported: has_video == true, returning false");
3428 return false;
3429 }
3430
3431 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003432 const int min_duration_secs = property_get_int32(
3433 "audio.offload.min.duration.secs", -1 /* default_value */);
3434 if (min_duration_secs >= 0) {
3435 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3436 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3437 min_duration_secs);
Eric Laurente552edb2014-03-10 17:42:56 -07003438 return false;
3439 }
3440 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3441 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3442 return false;
3443 }
3444
3445 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3446 // creating an offloaded track and tearing it down immediately after start when audioflinger
3447 // detects there is an active non offloadable effect.
3448 // FIXME: We should check the audio session here but we do not have it in this context.
3449 // This may prevent offloading in rare situations where effects are left active by apps
3450 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003451 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003452 return false;
3453 }
3454
3455 // See if there is a profile to support this.
3456 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003457 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003458 offloadInfo.sample_rate,
3459 offloadInfo.format,
3460 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003461 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3462 true /* directOnly */);
Eric Laurent1c333e22014-05-20 10:48:17 -07003463 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3464 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07003465}
3466
Michael Chana94fbb22018-04-24 14:31:19 +10003467bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3468 const audio_attributes_t& attributes) {
3469 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003470 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003471 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003472 config.sample_rate,
3473 config.format,
3474 config.channel_mask,
3475 output_flags,
3476 true /* directOnly */);
3477 ALOGV("%s() profile %sfound with name: %s, "
3478 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3479 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003480 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003481 config.sample_rate, config.format, config.channel_mask, output_flags);
3482 return (profile != 0);
3483}
3484
Eric Laurent6a94d692014-05-20 11:18:06 -07003485status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3486 audio_port_type_t type,
3487 unsigned int *num_ports,
3488 struct audio_port *ports,
3489 unsigned int *generation)
3490{
3491 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3492 generation == NULL) {
3493 return BAD_VALUE;
3494 }
3495 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3496 if (ports == NULL) {
3497 *num_ports = 0;
3498 }
3499
3500 size_t portsWritten = 0;
3501 size_t portsMax = *num_ports;
3502 *num_ports = 0;
3503 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003504 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3505 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003506 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003507 for (const auto& dev : mAvailableOutputDevices) {
3508 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003509 continue;
3510 }
3511 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003512 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003513 }
3514 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003515 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003516 }
3517 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003518 for (const auto& dev : mAvailableInputDevices) {
3519 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003520 continue;
3521 }
3522 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003523 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003524 }
3525 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003526 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003527 }
3528 }
3529 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3530 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3531 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3532 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3533 }
3534 *num_ports += mInputs.size();
3535 }
3536 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003537 size_t numOutputs = 0;
3538 for (size_t i = 0; i < mOutputs.size(); i++) {
3539 if (!mOutputs[i]->isDuplicated()) {
3540 numOutputs++;
3541 if (portsWritten < portsMax) {
3542 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3543 }
3544 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003545 }
Eric Laurent84c70242014-06-23 08:46:27 -07003546 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003547 }
3548 }
3549 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003550 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003551 return NO_ERROR;
3552}
3553
Eric Laurent99fcae42018-05-17 16:59:18 -07003554status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003555{
Eric Laurent99fcae42018-05-17 16:59:18 -07003556 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3557 return BAD_VALUE;
3558 }
3559 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3560 if (dev != 0) {
3561 dev->toAudioPort(port);
3562 return NO_ERROR;
3563 }
3564 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3565 if (dev != 0) {
3566 dev->toAudioPort(port);
3567 return NO_ERROR;
3568 }
3569 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3570 if (out != 0) {
3571 out->toAudioPort(port);
3572 return NO_ERROR;
3573 }
3574 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3575 if (in != 0) {
3576 in->toAudioPort(port);
3577 return NO_ERROR;
3578 }
3579 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003580}
3581
François Gaffieafd4cea2019-11-18 15:50:22 +01003582status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3583 audio_patch_handle_t *handle,
3584 uid_t uid, uint32_t delayMs,
3585 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003586{
François Gaffieafd4cea2019-11-18 15:50:22 +01003587 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003588 if (handle == NULL || patch == NULL) {
3589 return BAD_VALUE;
3590 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003591 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003592
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003593 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003594 return BAD_VALUE;
3595 }
3596 // only one source per audio patch supported for now
3597 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003598 return INVALID_OPERATION;
3599 }
Eric Laurent874c42872014-08-08 15:13:39 -07003600
3601 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003602 return INVALID_OPERATION;
3603 }
Eric Laurent874c42872014-08-08 15:13:39 -07003604 for (size_t i = 0; i < patch->num_sinks; i++) {
3605 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3606 return INVALID_OPERATION;
3607 }
3608 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003609
3610 sp<AudioPatch> patchDesc;
3611 ssize_t index = mAudioPatches.indexOfKey(*handle);
3612
François Gaffieafd4cea2019-11-18 15:50:22 +01003613 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3614 patch->sources[0].role,
3615 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003616#if LOG_NDEBUG == 0
3617 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003618 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3619 patch->sinks[i].role,
3620 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003621 }
3622#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003623
3624 if (index >= 0) {
3625 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003626 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3627 __func__, mUidCached, patchDesc->getUid(), uid);
3628 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003629 return INVALID_OPERATION;
3630 }
3631 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003632 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003633 }
3634
3635 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003636 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003637 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003638 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003639 return BAD_VALUE;
3640 }
Eric Laurent84c70242014-06-23 08:46:27 -07003641 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3642 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003643 if (patchDesc != 0) {
3644 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003645 ALOGV("%s source id differs for patch current id %d new id %d",
3646 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003647 return BAD_VALUE;
3648 }
3649 }
Eric Laurent874c42872014-08-08 15:13:39 -07003650 DeviceVector devices;
3651 for (size_t i = 0; i < patch->num_sinks; i++) {
3652 // Only support mix to devices connection
3653 // TODO add support for mix to mix connection
3654 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003655 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003656 return INVALID_OPERATION;
3657 }
3658 sp<DeviceDescriptor> devDesc =
3659 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3660 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003661 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003662 return BAD_VALUE;
3663 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003664
François Gaffie11d30102018-11-02 16:09:09 +01003665 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003666 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003667 NULL, // updatedSamplingRate
3668 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003669 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003670 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003671 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003672 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003673 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003674 return INVALID_OPERATION;
3675 }
3676 devices.add(devDesc);
3677 }
3678 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003679 return INVALID_OPERATION;
3680 }
Eric Laurent874c42872014-08-08 15:13:39 -07003681
Eric Laurent6a94d692014-05-20 11:18:06 -07003682 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003683 ALOGV("%s setting device %s on output %d",
3684 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003685 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003686 index = mAudioPatches.indexOfKey(*handle);
3687 if (index >= 0) {
3688 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003689 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003690 }
3691 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003692 patchDesc->setUid(uid);
3693 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003694 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003695 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003696 return INVALID_OPERATION;
3697 }
3698 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3699 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3700 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003701 // only one sink supported when connecting an input device to a mix
3702 if (patch->num_sinks > 1) {
3703 return INVALID_OPERATION;
3704 }
François Gaffie53615e22015-03-19 09:24:12 +01003705 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003706 if (inputDesc == NULL) {
3707 return BAD_VALUE;
3708 }
3709 if (patchDesc != 0) {
3710 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3711 return BAD_VALUE;
3712 }
3713 }
François Gaffie11d30102018-11-02 16:09:09 +01003714 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003715 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003716 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003717 return BAD_VALUE;
3718 }
3719
François Gaffie11d30102018-11-02 16:09:09 +01003720 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003721 patch->sinks[0].sample_rate,
3722 NULL, /*updatedSampleRate*/
3723 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003724 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003725 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003726 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 // FIXME for the parameter type,
3728 // and the NONE
3729 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003730 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 return INVALID_OPERATION;
3732 }
3733 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003734 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003735 device->toString().c_str(), inputDesc->mIoHandle);
3736 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003737 index = mAudioPatches.indexOfKey(*handle);
3738 if (index >= 0) {
3739 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003740 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003741 }
3742 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003743 patchDesc->setUid(uid);
3744 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003745 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003746 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003747 return INVALID_OPERATION;
3748 }
3749 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3750 // device to device connection
3751 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003752 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 return BAD_VALUE;
3754 }
3755 }
François Gaffie11d30102018-11-02 16:09:09 +01003756 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003757 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003758 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003759 return BAD_VALUE;
3760 }
Eric Laurent874c42872014-08-08 15:13:39 -07003761
Eric Laurent6a94d692014-05-20 11:18:06 -07003762 //update source and sink with our own data as the data passed in the patch may
3763 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003764 PatchBuilder patchBuilder;
3765 audio_port_config sourcePortConfig = {};
3766 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3767 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003768
Eric Laurent874c42872014-08-08 15:13:39 -07003769 for (size_t i = 0; i < patch->num_sinks; i++) {
3770 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003771 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003772 return INVALID_OPERATION;
3773 }
François Gaffie11d30102018-11-02 16:09:09 +01003774 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003775 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003776 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003777 return BAD_VALUE;
3778 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003779 audio_port_config sinkPortConfig = {};
3780 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3781 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003782
Eric Laurent3bcf8592015-04-03 12:13:24 -07003783 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08003784 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07003785 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02003786 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01003787 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
3788 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01003789 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3790 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01003791 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
3792 (sourceDesc != nullptr &&
3793 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003794 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003795 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003796 return INVALID_OPERATION;
3797 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003798 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3799 if (sourceDesc != nullptr) {
3800 // take care of dynamic routing for SwOutput selection,
3801 audio_attributes_t attributes = sourceDesc->attributes();
3802 audio_stream_type_t stream = sourceDesc->stream();
3803 audio_attributes_t resultAttr;
3804 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3805 config.sample_rate = sourceDesc->config().sample_rate;
3806 config.channel_mask = sourceDesc->config().channel_mask;
3807 config.format = sourceDesc->config().format;
3808 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3809 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3810 bool isRequestedDeviceForExclusiveUse = false;
François Gaffieafd4cea2019-11-18 15:50:22 +01003811 output_type_t outputType;
3812 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
3813 &stream, sourceDesc->uid(), &config, &flags,
3814 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07003815 nullptr, &outputType);
François Gaffieafd4cea2019-11-18 15:50:22 +01003816 if (output == AUDIO_IO_HANDLE_NONE) {
3817 ALOGV("%s no output for device %s",
3818 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurent874c42872014-08-08 15:13:39 -07003819 return INVALID_OPERATION;
3820 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003821 } else {
3822 SortedVector<audio_io_handle_t> outputs =
3823 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3824 // if the sink device is reachable via an opened output stream, request to
3825 // go via this output stream by adding a second source to the patch
3826 // description
3827 output = selectOutput(outputs);
3828 }
3829 if (output != AUDIO_IO_HANDLE_NONE) {
3830 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3831 if (outputDesc->isDuplicated()) {
3832 ALOGV("%s output for device %s is duplicated",
3833 __FUNCTION__, sinkDevice->toString().c_str());
3834 return INVALID_OPERATION;
3835 }
3836 audio_port_config srcMixPortConfig = {};
3837 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
3838 if (sourceDesc != nullptr) {
3839 sourceDesc->setSwOutput(outputDesc);
3840 }
3841 // for volume control, we may need a valid stream
3842 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
3843 sourceDesc->stream() : AUDIO_STREAM_PATCH;
3844 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07003845 }
Eric Laurent83b88082014-06-20 18:31:16 -07003846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003847 }
3848 // TODO: check from routing capabilities in config file and other conflicting patches
3849
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 status_t status = installPatch(
3851 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07003852 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003853 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07003854 return INVALID_OPERATION;
3855 }
3856 } else {
3857 return BAD_VALUE;
3858 }
3859 } else {
3860 return BAD_VALUE;
3861 }
3862 return NO_ERROR;
3863}
3864
3865status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3866 uid_t uid)
3867{
3868 ALOGV("releaseAudioPatch() patch %d", handle);
3869
3870 ssize_t index = mAudioPatches.indexOfKey(handle);
3871
3872 if (index < 0) {
3873 return BAD_VALUE;
3874 }
3875 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003876 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
3877 __func__, mUidCached, patchDesc->getUid(), uid);
3878 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003879 return INVALID_OPERATION;
3880 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003881 return releaseAudioPatchInternal(handle);
3882}
Eric Laurent6a94d692014-05-20 11:18:06 -07003883
François Gaffieafd4cea2019-11-18 15:50:22 +01003884status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
3885 uint32_t delayMs)
3886{
3887 ALOGV("%s patch %d", __func__, handle);
3888 if (mAudioPatches.indexOfKey(handle) < 0) {
3889 ALOGE("%s: no patch found with handle=%d", __func__, handle);
3890 return BAD_VALUE;
3891 }
3892 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003893 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01003894 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003896 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003897 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003898 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003899 return BAD_VALUE;
3900 }
3901
François Gaffie11d30102018-11-02 16:09:09 +01003902 setOutputDevices(outputDesc,
3903 getNewOutputDevices(outputDesc, true /*fromCache*/),
3904 true,
3905 0,
3906 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07003907 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3908 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003909 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003910 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003911 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003912 return BAD_VALUE;
3913 }
3914 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003915 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003916 true,
3917 NULL);
3918 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003919 status_t status =
3920 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
3921 ALOGV("%s patch panel returned %d patchHandle %d",
3922 __func__, status, patchDesc->getAfHandle());
3923 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003925 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02003926 // SW Bridge
3927 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
3928 sp<SwAudioOutputDescriptor> outputDesc =
3929 mOutputs.getOutputFromId(patch->sources[1].id);
3930 if (outputDesc == NULL) {
3931 ALOGE("%s output not found for id %d", __func__, patch->sources[0].id);
3932 return BAD_VALUE;
3933 }
Francois Gaffie8e544542020-05-11 14:12:53 +02003934 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
3935 // force SwOutput patch removal as AF counter part patch has already gone.
3936 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
3937 removeAudioPatch(outputDesc->getPatchHandle());
3938 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02003939 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
3940 setOutputDevices(outputDesc,
3941 getNewOutputDevices(outputDesc, true /*fromCache*/),
3942 true, /*force*/
3943 0,
3944 NULL);
3945 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003946 } else {
3947 return BAD_VALUE;
3948 }
3949 } else {
3950 return BAD_VALUE;
3951 }
3952 return NO_ERROR;
3953}
3954
3955status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3956 struct audio_patch *patches,
3957 unsigned int *generation)
3958{
François Gaffie53615e22015-03-19 09:24:12 +01003959 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003960 return BAD_VALUE;
3961 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003963 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003964}
3965
Eric Laurente1715a42014-05-20 11:30:42 -07003966status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003967{
Eric Laurente1715a42014-05-20 11:30:42 -07003968 ALOGV("setAudioPortConfig()");
3969
3970 if (config == NULL) {
3971 return BAD_VALUE;
3972 }
3973 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3974 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003975 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3976 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003977 }
3978
Eric Laurenta121f902014-06-03 13:32:54 -07003979 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003980 if (config->type == AUDIO_PORT_TYPE_MIX) {
3981 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003982 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003983 if (outputDesc == NULL) {
3984 return BAD_VALUE;
3985 }
Eric Laurent84c70242014-06-23 08:46:27 -07003986 ALOG_ASSERT(!outputDesc->isDuplicated(),
3987 "setAudioPortConfig() called on duplicated output %d",
3988 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003989 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003990 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003991 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003992 if (inputDesc == NULL) {
3993 return BAD_VALUE;
3994 }
Eric Laurenta121f902014-06-03 13:32:54 -07003995 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003996 } else {
3997 return BAD_VALUE;
3998 }
3999 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4000 sp<DeviceDescriptor> deviceDesc;
4001 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4002 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4003 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4004 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4005 } else {
4006 return BAD_VALUE;
4007 }
4008 if (deviceDesc == NULL) {
4009 return BAD_VALUE;
4010 }
Eric Laurenta121f902014-06-03 13:32:54 -07004011 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004012 } else {
4013 return BAD_VALUE;
4014 }
4015
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004016 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004017 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4018 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004019 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004020 audioPortConfig->toAudioPortConfig(&newConfig, config);
4021 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004022 }
Eric Laurenta121f902014-06-03 13:32:54 -07004023 if (status != NO_ERROR) {
4024 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004025 }
Eric Laurente1715a42014-05-20 11:30:42 -07004026
4027 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004028}
4029
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004030void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4031{
Eric Laurentd60560a2015-04-10 11:31:20 -07004032 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004033 clearAudioPatches(uid);
4034 clearSessionRoutes(uid);
4035}
4036
Eric Laurent6a94d692014-05-20 11:18:06 -07004037void AudioPolicyManager::clearAudioPatches(uid_t uid)
4038{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004039 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004041 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004042 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004043 }
4044 }
4045}
4046
François Gaffiec005e562018-11-06 15:04:49 +01004047void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004048{
François Gaffiec005e562018-11-06 15:04:49 +01004049 // Take the first attributes following the product strategy as it is used to retrieve the routed
4050 // device. All attributes wihin a strategy follows the same "routing strategy"
4051 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4052 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004053 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004054 for (size_t j = 0; j < mOutputs.size(); j++) {
4055 if (mOutputs.keyAt(j) == ouptutToSkip) {
4056 continue;
4057 }
4058 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004059 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004060 continue;
4061 }
4062 // If the default device for this strategy is on another output mix,
4063 // invalidate all tracks in this strategy to force re connection.
4064 // Otherwise select new device on the output mix.
4065 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004066 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4067 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004068 }
4069 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004070 setOutputDevices(
4071 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004072 }
4073 }
4074}
4075
4076void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4077{
4078 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004079 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004080 for (size_t i = 0; i < mOutputs.size(); i++) {
4081 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004082 for (const auto& client : outputDesc->getClientIterable()) {
4083 if (client->hasPreferredDevice() && client->uid() == uid) {
4084 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004085 auto clientStrategy = client->strategy();
4086 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4087 end(affectedStrategies)) {
4088 continue;
4089 }
4090 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004091 }
4092 }
4093 }
4094 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004095 for (const auto& strategy : affectedStrategies) {
4096 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004097 }
4098
4099 // remove input routes associated with this uid
4100 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004101 for (size_t i = 0; i < mInputs.size(); i++) {
4102 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004103 for (const auto& client : inputDesc->getClientIterable()) {
4104 if (client->hasPreferredDevice() && client->uid() == uid) {
4105 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4106 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004107 }
4108 }
4109 }
4110 // reroute inputs if necessary
4111 SortedVector<audio_io_handle_t> inputsToClose;
4112 for (size_t i = 0; i < mInputs.size(); i++) {
4113 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004114 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004115 inputsToClose.add(inputDesc->mIoHandle);
4116 }
4117 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004118 for (const auto& input : inputsToClose) {
4119 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004120 }
4121}
4122
Eric Laurentd60560a2015-04-10 11:31:20 -07004123void AudioPolicyManager::clearAudioSources(uid_t uid)
4124{
4125 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004126 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4127 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004128 stopAudioSource(mAudioSources.keyAt(i));
4129 }
4130 }
4131}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004132
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004133status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4134 audio_io_handle_t *ioHandle,
4135 audio_devices_t *device)
4136{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004137 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4138 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004139 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004140 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004141
François Gaffiedf372692015-03-19 10:43:27 +01004142 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004143}
4144
Eric Laurentd60560a2015-04-10 11:31:20 -07004145status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004146 const audio_attributes_t *attributes,
4147 audio_port_handle_t *portId,
4148 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004149{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004150 ALOGV("%s", __FUNCTION__);
4151 *portId = AUDIO_PORT_HANDLE_NONE;
4152
4153 if (source == NULL || attributes == NULL || portId == NULL) {
4154 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4155 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004156 return BAD_VALUE;
4157 }
4158
Eric Laurentd60560a2015-04-10 11:31:20 -07004159 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4160 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004161 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4162 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004163 return INVALID_OPERATION;
4164 }
4165
François Gaffie11d30102018-11-02 16:09:09 +01004166 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004167 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004168 String8(source->ext.device.address),
4169 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004170 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004171 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004172 return BAD_VALUE;
4173 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004174
jiabin4ef93452019-09-10 14:29:54 -07004175 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004176
François Gaffieaaac0fd2018-11-22 17:56:39 +01004177 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004178 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004179 mEngine->getStreamTypeForAttributes(*attributes),
4180 mEngine->getProductStrategyForAttributes(*attributes),
4181 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004182
4183 status_t status = connectAudioSource(sourceDesc);
4184 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004185 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004186 }
4187 return status;
4188}
4189
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004190status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004191{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004192 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004193
4194 // make sure we only have one patch per source.
4195 disconnectAudioSource(sourceDesc);
4196
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004197 audio_attributes_t attributes = sourceDesc->attributes();
François Gaffie11d30102018-11-02 16:09:09 +01004198 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
Eric Laurentd60560a2015-04-10 11:31:20 -07004199
François Gaffiec005e562018-11-06 15:04:49 +01004200 DeviceVector sinkDevices =
4201 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
4202 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004203 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
4204 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
4205 __FUNCTION__, sinkDevice->toString().c_str());
Eric Laurentd60560a2015-04-10 11:31:20 -07004206
François Gaffieafd4cea2019-11-18 15:50:22 +01004207 PatchBuilder patchBuilder;
4208 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4209 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4210 status_t status =
4211 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4212 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4213 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4214 return INVALID_OPERATION;
4215 }
4216 sourceDesc->setPatchHandle(handle);
4217 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4218 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4219 if (swOutput != 0) {
4220 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004221 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004222 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004223 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004224 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004225 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004226 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004227 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004228 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004229 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004230 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004231 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004232 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4233 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004234 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004235 if (delayMs != 0) {
4236 usleep(delayMs * 1000);
4237 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004238 } else {
4239 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4240 if (hwOutputDesc != 0) {
4241 // create Hwoutput and add to mHwOutputs
4242 } else {
4243 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4244 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004245 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004246 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004247
4248FailureSourceActive:
4249 swOutput->stop();
4250 releaseOutput(sourceDesc->portId());
4251FailureSourceAdded:
4252 sourceDesc->setSwOutput(nullptr);
4253FailureReleasePatch:
4254 releaseAudioPatchInternal(handle);
4255 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004256}
4257
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004258status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004259{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004260 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4261 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004262 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004263 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004264 return BAD_VALUE;
4265 }
4266 status_t status = disconnectAudioSource(sourceDesc);
4267
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004268 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004269 return status;
4270}
4271
Andy Hung2ddee192015-12-18 17:34:44 -08004272status_t AudioPolicyManager::setMasterMono(bool mono)
4273{
4274 if (mMasterMono == mono) {
4275 return NO_ERROR;
4276 }
4277 mMasterMono = mono;
4278 // if enabling mono we close all offloaded devices, which will invalidate the
4279 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4280 // for recreating the new AudioTrack as non-offloaded PCM.
4281 //
4282 // If disabling mono, we leave all tracks as is: we don't know which clients
4283 // and tracks are able to be recreated as offloaded. The next "song" should
4284 // play back offloaded.
4285 if (mMasterMono) {
4286 Vector<audio_io_handle_t> offloaded;
4287 for (size_t i = 0; i < mOutputs.size(); ++i) {
4288 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4289 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4290 offloaded.push(desc->mIoHandle);
4291 }
4292 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004293 for (const auto& handle : offloaded) {
4294 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004295 }
4296 }
4297 // update master mono for all remaining outputs
4298 for (size_t i = 0; i < mOutputs.size(); ++i) {
4299 updateMono(mOutputs.keyAt(i));
4300 }
4301 return NO_ERROR;
4302}
4303
4304status_t AudioPolicyManager::getMasterMono(bool *mono)
4305{
4306 *mono = mMasterMono;
4307 return NO_ERROR;
4308}
4309
Eric Laurentac9cef52017-06-09 15:46:26 -07004310float AudioPolicyManager::getStreamVolumeDB(
4311 audio_stream_type_t stream, int index, audio_devices_t device)
4312{
jiabin9a3361e2019-10-01 09:38:30 -07004313 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004314}
4315
jiabin81772902018-04-02 17:52:27 -07004316status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4317 audio_format_t *surroundFormats,
4318 bool *surroundFormatsEnabled,
4319 bool reported)
4320{
4321 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4322 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4323 return BAD_VALUE;
4324 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004325 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4326 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
jiabin81772902018-04-02 17:52:27 -07004327
4328 size_t formatsWritten = 0;
4329 size_t formatsMax = *numSurroundFormats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004330 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
jiabin81772902018-04-02 17:52:27 -07004331 if (reported) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004332 // Return formats from all device profiles that have already been resolved by
Mikhail Naganov2563f232018-09-27 14:48:01 -07004333 // checkOutputsForDevice().
Mikhail Naganov100f0122018-11-29 11:22:16 -08004334 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4335 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4336 FormatVector supportedFormats =
4337 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4338 for (size_t j = 0; j < supportedFormats.size(); j++) {
4339 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4340 formats.insert(supportedFormats[j]);
4341 } else {
4342 for (const auto& pair : mConfig.getSurroundFormats()) {
4343 if (pair.second.count(supportedFormats[j]) != 0) {
4344 formats.insert(pair.first);
4345 break;
4346 }
4347 }
4348 }
4349 }
jiabin81772902018-04-02 17:52:27 -07004350 }
4351 } else {
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004352 for (const auto& pair : mConfig.getSurroundFormats()) {
4353 formats.insert(pair.first);
jiabin81772902018-04-02 17:52:27 -07004354 }
4355 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004356 *numSurroundFormats = formats.size();
4357 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4358 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov2563f232018-09-27 14:48:01 -07004359 for (const auto& format: formats) {
jiabin81772902018-04-02 17:52:27 -07004360 if (formatsWritten < formatsMax) {
Mikhail Naganov2563f232018-09-27 14:48:01 -07004361 surroundFormats[formatsWritten] = format;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004362 bool formatEnabled = true;
4363 switch (forceUse) {
4364 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4365 formatEnabled = mManualSurroundFormats.count(format) != 0;
4366 break;
4367 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4368 formatEnabled = false;
4369 break;
4370 default: // AUTO or ALWAYS => true
4371 break;
jiabin81772902018-04-02 17:52:27 -07004372 }
4373 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4374 }
jiabin81772902018-04-02 17:52:27 -07004375 }
4376 return NO_ERROR;
4377}
4378
4379status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4380{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004381 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004382 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4383 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004384 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004385 return BAD_VALUE;
4386 }
4387
Mikhail Naganov100f0122018-11-29 11:22:16 -08004388 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4389 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004390 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004391 return INVALID_OPERATION;
4392 }
4393
Mikhail Naganov100f0122018-11-29 11:22:16 -08004394 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004395 return NO_ERROR;
4396 }
4397
Mikhail Naganov100f0122018-11-29 11:22:16 -08004398 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004399 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004400 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004401 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004402 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004403 }
4404 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004405 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004406 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004407 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004408 }
4409 }
4410
4411 sp<SwAudioOutputDescriptor> outputDesc;
4412 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004413 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4414 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004415 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4416 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004417 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004418 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004419 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4420 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4421 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004422 name.c_str(),
4423 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004424 if (status != NO_ERROR) {
4425 continue;
4426 }
4427 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4428 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4429 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004430 name.c_str(),
4431 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004432 profileUpdated |= (status == NO_ERROR);
4433 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004434 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004435 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004436 AUDIO_DEVICE_IN_HDMI);
4437 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4438 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004439 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004440 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004441 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4442 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4443 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004444 name.c_str(),
4445 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004446 if (status != NO_ERROR) {
4447 continue;
4448 }
4449 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4450 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4451 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004452 name.c_str(),
4453 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004454 profileUpdated |= (status == NO_ERROR);
4455 }
4456
jiabin81772902018-04-02 17:52:27 -07004457 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004458 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004459 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004460 }
4461
4462 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4463}
4464
Eric Laurent5ada82e2019-08-29 17:53:54 -07004465void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004466{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004467 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004468 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004469 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004470 }
4471}
4472
jiabin6012f912018-11-02 17:06:30 -07004473bool AudioPolicyManager::isHapticPlaybackSupported()
4474{
4475 for (const auto& hwModule : mHwModules) {
4476 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4477 for (const auto &outProfile : outputProfiles) {
4478 struct audio_port audioPort;
4479 outProfile->toAudioPort(&audioPort);
4480 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4481 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4482 return true;
4483 }
4484 }
4485 }
4486 }
4487 return false;
4488}
4489
Eric Laurent8340e672019-11-06 11:01:08 -08004490bool AudioPolicyManager::isCallScreenModeSupported()
4491{
4492 return getConfig().isCallScreenModeSupported();
4493}
4494
4495
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004496status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004497{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004498 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
François Gaffieafd4cea2019-11-18 15:50:22 +01004499 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4500 if (swOutput != 0) {
4501 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004502 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004503 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004504 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004505 releaseOutput(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004506 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004507 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004508 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004509 // close Hwoutput and remove from mHwOutputs
4510 } else {
4511 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4512 }
4513 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004514 return releaseAudioPatchInternal(sourceDesc->getPatchHandle());
Eric Laurentd60560a2015-04-10 11:31:20 -07004515}
4516
François Gaffiec005e562018-11-06 15:04:49 +01004517sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4518 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004519{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004520 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004521 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004522 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004523 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004524 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4525 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004526 source = sourceDesc;
4527 break;
4528 }
4529 }
4530 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004531}
4532
Eric Laurente552edb2014-03-10 17:42:56 -07004533// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004534// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004535// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004536uint32_t AudioPolicyManager::nextAudioPortGeneration()
4537{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004538 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004539}
4540
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004541static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4542 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
Petri Gyntherf497f292018-04-17 18:46:10 -07004543 std::vector<const char*> fileNames;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004544 status_t ret;
4545
Cheney Ni00ce33d2018-11-01 06:30:37 +08004546 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
Cheney Nie5985452019-02-24 01:39:15 +08004547 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4548 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4549 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4550 // the legacy hardware module for A2DP and hearing aid.
4551 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4552 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4553 // A2DP offload supported but disabled: try to use special XML file
Cheney Ni6851adb2018-11-01 06:30:37 +08004554 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4555 }
Cheney Nie5985452019-02-24 01:39:15 +08004556 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4557 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
Petri Gyntherf497f292018-04-17 18:46:10 -07004558 }
4559 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4560
4561 for (const char* fileName : fileNames) {
Mikhail Naganov27cf37c2020-04-14 14:47:01 -07004562 for (const auto& path : audio_get_configuration_paths()) {
Petri Gyntherf497f292018-04-17 18:46:10 -07004563 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
Mikhail Naganov27cf37c2020-04-14 14:47:01 -07004564 "%s/%s", path.c_str(), fileName);
Mikhail Naganova289aea2018-09-17 15:26:23 -07004565 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
Petri Gyntherf497f292018-04-17 18:46:10 -07004566 if (ret == NO_ERROR) {
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004567 config.setSource(audioPolicyXmlConfigFile);
Petri Gyntherf497f292018-04-17 18:46:10 -07004568 return ret;
4569 }
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004570 }
4571 }
4572 return ret;
4573}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004574
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004575AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4576 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004577 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004578 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004579 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004580 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004581 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004582 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004583 mAudioPortGeneration(1),
4584 mBeaconMuteRefCount(0),
4585 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004586 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004587 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004588 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004589 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004590{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004591}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004592
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004593AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4594 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4595{
4596 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004597}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004598
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004599void AudioPolicyManager::loadConfig() {
4600 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004601 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004602 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004603 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004604}
4605
4606status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004607 {
4608 auto engLib = EngineLibrary::load(
4609 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4610 if (!engLib) {
4611 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4612 return NO_INIT;
4613 }
4614 mEngine = engLib->createEngine();
4615 if (mEngine == nullptr) {
4616 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4617 return NO_INIT;
4618 }
François Gaffie2110e042015-03-24 08:41:51 +01004619 }
4620 mEngine->setObserver(this);
4621 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004622 if (status != NO_ERROR) {
4623 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4624 return status;
4625 }
François Gaffie2110e042015-03-24 08:41:51 +01004626
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004627 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004628 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004629 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004630
Eric Laurent3a4311c2014-03-17 12:00:47 -07004631 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004632 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4633 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4634 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004635 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004636 }
jiabin9ff780e2018-03-19 18:19:52 -07004637 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004638 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004639 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004640 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004641 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004642 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004643 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004644 }
4645 }
4646 }
Eric Laurente552edb2014-03-10 17:42:56 -07004647
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004648 if (mPrimaryOutput == 0) {
4649 ALOGE("Failed to open primary output");
4650 status = NO_INIT;
4651 }
Eric Laurente552edb2014-03-10 17:42:56 -07004652
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004653 // Silence ALOGV statements
4654 property_set("log.tag." LOG_TAG, "D");
4655
Eric Laurente552edb2014-03-10 17:42:56 -07004656 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004657 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004658}
4659
Eric Laurente0720872014-03-11 09:30:41 -07004660AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004661{
Eric Laurente552edb2014-03-10 17:42:56 -07004662 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004663 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004664 }
4665 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004666 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004667 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004668 mAvailableOutputDevices.clear();
4669 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004670 mOutputs.clear();
4671 mInputs.clear();
4672 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004673 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004674 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004675}
4676
Eric Laurente0720872014-03-11 09:30:41 -07004677status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004678{
Eric Laurent87ffa392015-05-22 10:32:38 -07004679 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004680}
4681
Eric Laurente552edb2014-03-10 17:42:56 -07004682// ---
4683
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004684void AudioPolicyManager::onNewAudioModulesAvailable()
4685{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004686 DeviceVector newDevices;
4687 onNewAudioModulesAvailableInt(&newDevices);
4688 if (!newDevices.empty()) {
4689 nextAudioPortGeneration();
4690 mpClientInterface->onAudioPortListUpdate();
4691 }
4692}
4693
4694void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4695{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004696 for (const auto& hwModule : mHwModulesAll) {
4697 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4698 continue;
4699 }
4700 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4701 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4702 ALOGW("could not open HW module %s", hwModule->getName());
4703 continue;
4704 }
4705 mHwModules.push_back(hwModule);
4706 // open all output streams needed to access attached devices
4707 // except for direct output streams that are only opened when they are actually
4708 // required by an app.
4709 // This also validates mAvailableOutputDevices list
4710 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4711 if (!outProfile->canOpenNewIo()) {
4712 ALOGE("Invalid Output profile max open count %u for profile %s",
4713 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4714 continue;
4715 }
4716 if (!outProfile->hasSupportedDevices()) {
4717 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4718 continue;
4719 }
4720 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4721 mTtsOutputAvailable = true;
4722 }
4723
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004724 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4725 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4726 sp<DeviceDescriptor> supportedDevice = 0;
4727 if (supportedDevices.contains(mDefaultOutputDevice)) {
4728 supportedDevice = mDefaultOutputDevice;
4729 } else {
4730 // choose first device present in profile's SupportedDevices also part of
4731 // mAvailableOutputDevices.
4732 if (availProfileDevices.isEmpty()) {
4733 continue;
4734 }
4735 supportedDevice = availProfileDevices.itemAt(0);
4736 }
4737 if (!mOutputDevicesAll.contains(supportedDevice)) {
4738 continue;
4739 }
4740 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4741 mpClientInterface);
4742 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4743 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4744 AUDIO_STREAM_DEFAULT,
4745 AUDIO_OUTPUT_FLAG_NONE, &output);
4746 if (status != NO_ERROR) {
4747 ALOGW("Cannot open output stream for devices %s on hw module %s",
4748 supportedDevice->toString().c_str(), hwModule->getName());
4749 continue;
4750 }
4751 for (const auto &device : availProfileDevices) {
4752 // give a valid ID to an attached device once confirmed it is reachable
4753 if (!device->isAttached()) {
4754 device->attach(hwModule);
4755 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07004756 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004757 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004758 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4759 }
4760 }
4761 if (mPrimaryOutput == 0 &&
4762 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4763 mPrimaryOutput = outputDesc;
4764 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004765 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4766 outputDesc->close();
4767 } else {
4768 addOutput(output, outputDesc);
4769 setOutputDevices(outputDesc,
4770 DeviceVector(supportedDevice),
4771 true,
4772 0,
4773 NULL);
4774 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004775 }
4776 // open input streams needed to access attached devices to validate
4777 // mAvailableInputDevices list
4778 for (const auto& inProfile : hwModule->getInputProfiles()) {
4779 if (!inProfile->canOpenNewIo()) {
4780 ALOGE("Invalid Input profile max open count %u for profile %s",
4781 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4782 continue;
4783 }
4784 if (!inProfile->hasSupportedDevices()) {
4785 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4786 continue;
4787 }
4788 // chose first device present in profile's SupportedDevices also part of
4789 // available input devices
4790 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4791 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
4792 if (availProfileDevices.isEmpty()) {
4793 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4794 continue;
4795 }
4796 sp<AudioInputDescriptor> inputDesc =
4797 new AudioInputDescriptor(inProfile, mpClientInterface);
4798
4799 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4800 status_t status = inputDesc->open(nullptr,
4801 availProfileDevices.itemAt(0),
4802 AUDIO_SOURCE_MIC,
4803 AUDIO_INPUT_FLAG_NONE,
4804 &input);
4805 if (status != NO_ERROR) {
4806 ALOGW("Cannot open input stream for device %s on hw module %s",
4807 availProfileDevices.toString().c_str(),
4808 hwModule->getName());
4809 continue;
4810 }
4811 for (const auto &device : availProfileDevices) {
4812 // give a valid ID to an attached device once confirmed it is reachable
4813 if (!device->isAttached()) {
4814 device->attach(hwModule);
4815 device->importAudioPortAndPickAudioProfile(inProfile, true);
4816 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004817 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004818 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4819 }
4820 }
4821 inputDesc->close();
4822 }
4823 }
4824}
4825
Eric Laurent98e38192018-02-15 18:31:53 -08004826void AudioPolicyManager::addOutput(audio_io_handle_t output,
4827 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004828{
Eric Laurent1c333e22014-05-20 10:48:17 -07004829 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07004830 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08004831 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004832 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004833 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004834}
4835
François Gaffie53615e22015-03-19 09:24:12 +01004836void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4837{
4838 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004839 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004840}
4841
Eric Laurent98e38192018-02-15 18:31:53 -08004842void AudioPolicyManager::addInput(audio_io_handle_t input,
4843 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004844{
Eric Laurent1c333e22014-05-20 10:48:17 -07004845 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004847}
Eric Laurente552edb2014-03-10 17:42:56 -07004848
François Gaffie11d30102018-11-02 16:09:09 +01004849status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01004850 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01004851 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004852{
François Gaffie11d30102018-11-02 16:09:09 +01004853 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07004854 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004855 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004856
François Gaffie11d30102018-11-02 16:09:09 +01004857 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07004858 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01004859 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004860 }
Eric Laurente552edb2014-03-10 17:42:56 -07004861
Eric Laurent3b73df72014-03-11 09:06:29 -07004862 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004863 // first list already open outputs that can be routed to this device
4864 for (size_t i = 0; i < mOutputs.size(); i++) {
4865 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004866 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07004867 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01004868 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4869 mOutputs.keyAt(i), device->toString().c_str());
4870 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07004871 }
4872 }
4873 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004874 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08004875 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08004876 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4877 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01004878 if (profile->supportsDevice(device)) {
4879 profiles.add(profile);
4880 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4881 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07004882 }
4883 }
4884 }
4885
Eric Laurent7b279bb2015-12-14 10:18:23 -08004886 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004887
Eric Laurente552edb2014-03-10 17:42:56 -07004888 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004889 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07004890 return BAD_VALUE;
4891 }
4892
4893 // open outputs for matching profiles if needed. Direct outputs are also opened to
4894 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4895 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004897
4898 // nothing to do if one output is already opened for this profile
4899 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004900 for (j = 0; j < outputs.size(); j++) {
4901 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004902 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004903 // matching profile: save the sample rates, format and channel masks supported
4904 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01004905 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07004906 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07004907 }
Eric Laurente552edb2014-03-10 17:42:56 -07004908 break;
4909 }
4910 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004911 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004912 continue;
4913 }
4914
Eric Laurent3974e3b2017-12-07 17:58:43 -08004915 if (!profile->canOpenNewIo()) {
4916 ALOGW("Max Output number %u already opened for this profile %s",
4917 profile->maxOpenCount, profile->getTagName().c_str());
4918 continue;
4919 }
4920
Eric Laurent83efe1c2017-07-09 16:51:08 -07004921 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07004922 deviceType, address.string(), profile.get(), profile->getName().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07004923 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004924 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01004925 status_t status = desc->open(nullptr, DeviceVector(device),
Eric Laurentfe231122017-11-17 17:48:06 -08004926 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
Eric Laurente552edb2014-03-10 17:42:56 -07004927
Eric Laurentfe231122017-11-17 17:48:06 -08004928 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004929 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004930 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01004931 char *param = audio_device_address_to_parameter(deviceType, address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004932 mpClientInterface->setParameters(output, String8(param));
4933 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004934 }
François Gaffie11d30102018-11-02 16:09:09 +01004935 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004936 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004937 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08004938 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004939 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004940 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentfe231122017-11-17 17:48:06 -08004941 desc->close();
Phil Burk702b1052016-03-02 16:38:26 -08004942 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08004943 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4944 profile->pickAudioProfile(
4945 config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004946 config.offload_info.sample_rate = config.sample_rate;
4947 config.offload_info.channel_mask = config.channel_mask;
4948 config.offload_info.format = config.format;
Eric Laurentfe231122017-11-17 17:48:06 -08004949
François Gaffie11d30102018-11-02 16:09:09 +01004950 status_t status = desc->open(&config, DeviceVector(device),
4951 AUDIO_STREAM_DEFAULT,
Eric Laurentfe231122017-11-17 17:48:06 -08004952 AUDIO_OUTPUT_FLAG_NONE, &output);
4953 if (status != NO_ERROR) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004954 output = AUDIO_IO_HANDLE_NONE;
4955 }
Eric Laurentd4692962014-05-05 18:13:44 -07004956 }
4957
Eric Laurentcf2c0212014-07-25 16:20:43 -07004958 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004959 addOutput(output, desc);
Eric Laurent0e26e3f2020-04-29 14:24:16 -07004960 if (audio_is_remote_submix_device(deviceType) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004961 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004962 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
4963 == NO_ERROR) {
François Gaffieb141c522018-03-12 11:47:40 +01004964 policyMix->setOutput(desc);
Mikhail Naganovbfac5832019-03-05 16:55:28 -08004965 desc->mPolicyMix = policyMix;
François Gaffieb141c522018-03-12 11:47:40 +01004966 } else {
4967 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Eric Laurent275e8e92014-11-30 15:14:47 -08004968 address.string());
4969 }
François Gaffie036e1e92015-03-19 10:16:24 +01004970
Eric Laurent87ffa392015-05-22 10:32:38 -07004971 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4972 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004973 // no duplicated output for direct outputs and
4974 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004975 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004976
Eric Laurentd4692962014-05-05 18:13:44 -07004977 //TODO: configure audio effect output stage here
4978
4979 // open a duplicating output thread for the new output and the primary output
Eric Laurent5babc4f2018-02-15 12:33:44 -08004980 sp<SwAudioOutputDescriptor> dupOutputDesc =
4981 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4982 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4983 &duplicatedOutput);
4984 if (status == NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -07004985 // add duplicated output descriptor
Eric Laurentd4692962014-05-05 18:13:44 -07004986 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentd4692962014-05-05 18:13:44 -07004987 } else {
4988 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004989 mPrimaryOutput->mIoHandle, output);
Eric Laurentfe231122017-11-17 17:48:06 -08004990 desc->close();
François Gaffie53615e22015-03-19 09:24:12 +01004991 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004993 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004994 }
Eric Laurente552edb2014-03-10 17:42:56 -07004995 }
4996 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004997 } else {
4998 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004999 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07005000 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005001 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005002 profiles.removeAt(profile_index);
5003 profile_index--;
5004 } else {
5005 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005006 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005007 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005008 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005009 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005010
François Gaffie11d30102018-11-02 16:09:09 +01005011 if (device_distinguishes_on_address(deviceType)) {
5012 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5013 device->toString().c_str());
5014 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5015 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005016 }
Eric Laurente552edb2014-03-10 17:42:56 -07005017 ALOGV("checkOutputsForDevice(): adding output %d", output);
5018 }
5019 }
5020
5021 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005022 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005023 return BAD_VALUE;
5024 }
Eric Laurentd4692962014-05-05 18:13:44 -07005025 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005026 // check if one opened output is not needed any more after disconnecting one device
5027 for (size_t i = 0; i < mOutputs.size(); i++) {
5028 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005029 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005030 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005031 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005032 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005033 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005034 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005035 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5036 mOutputs.keyAt(i));
5037 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005038 }
Eric Laurente552edb2014-03-10 17:42:56 -07005039 }
5040 }
Eric Laurentd4692962014-05-05 18:13:44 -07005041 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005042 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005043 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5044 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005045 if (profile->supportsDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07005046 ALOGV("checkOutputsForDevice(): "
Mikhail Naganovd4120142017-12-06 15:49:22 -08005047 "clearing direct output profile %zu on module %s",
5048 j, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005049 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07005050 }
5051 }
5052 }
5053 }
5054 return NO_ERROR;
5055}
5056
François Gaffie11d30102018-11-02 16:09:09 +01005057status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005058 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005059{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005060 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005061
François Gaffie11d30102018-11-02 16:09:09 +01005062 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005063 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005064 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005065 }
5066
Eric Laurentd4692962014-05-05 18:13:44 -07005067 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005068 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005069 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005070 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005071 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005072 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005073 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005074 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005075
François Gaffie11d30102018-11-02 16:09:09 +01005076 if (profile->supportsDevice(device)) {
5077 profiles.add(profile);
5078 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5079 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005080 }
5081 }
5082 }
5083
Eric Laurent0dd51852019-04-19 18:18:58 -07005084 if (profiles.isEmpty()) {
5085 ALOGW("%s: No input profile available for device %s",
5086 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005087 return BAD_VALUE;
5088 }
5089
5090 // open inputs for matching profiles if needed. Direct inputs are also opened to
5091 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5092 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5093
Eric Laurent1c333e22014-05-20 10:48:17 -07005094 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005095
Eric Laurentd4692962014-05-05 18:13:44 -07005096 // nothing to do if one input is already opened for this profile
5097 size_t input_index;
5098 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5099 desc = mInputs.valueAt(input_index);
5100 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005101 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005102 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005103 }
Eric Laurentd4692962014-05-05 18:13:44 -07005104 break;
5105 }
5106 }
5107 if (input_index != mInputs.size()) {
5108 continue;
5109 }
5110
Eric Laurent3974e3b2017-12-07 17:58:43 -08005111 if (!profile->canOpenNewIo()) {
5112 ALOGW("Max Input number %u already opened for this profile %s",
5113 profile->maxOpenCount, profile->getTagName().c_str());
5114 continue;
5115 }
5116
Eric Laurentfe231122017-11-17 17:48:06 -08005117 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005118 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005119 status_t status = desc->open(nullptr,
5120 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005121 AUDIO_SOURCE_MIC,
5122 AUDIO_INPUT_FLAG_NONE,
5123 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005124
Eric Laurentcf2c0212014-07-25 16:20:43 -07005125 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005126 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005127 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005128 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005129 mpClientInterface->setParameters(input, String8(param));
5130 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005131 }
François Gaffie11d30102018-11-02 16:09:09 +01005132 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005133 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005134 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005135 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005136 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005137 }
5138
Eric Laurent0dd51852019-04-19 18:18:58 -07005139 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005140 addInput(input, desc);
5141 }
5142 } // endif input != 0
5143
Eric Laurentcf2c0212014-07-25 16:20:43 -07005144 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005145 ALOGW("%s could not open input for device %s", __func__,
5146 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005147 profiles.removeAt(profile_index);
5148 profile_index--;
5149 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005150 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005151 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005152 }
Eric Laurentd4692962014-05-05 18:13:44 -07005153 ALOGV("checkInputsForDevice(): adding input %d", input);
5154 }
5155 } // end scan profiles
5156
5157 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005158 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005159 return BAD_VALUE;
5160 }
5161 } else {
5162 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005163 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005164 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005165 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005166 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005167 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005168 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005169 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005170 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5171 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005172 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005173 }
5174 }
5175 }
5176 } // end disconnect
5177
5178 return NO_ERROR;
5179}
5180
5181
Eric Laurente0720872014-03-11 09:30:41 -07005182void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005183{
5184 ALOGV("closeOutput(%d)", output);
5185
François Gaffie1c878552018-11-22 16:53:21 +01005186 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5187 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005188 ALOGW("closeOutput() unknown output %d", output);
5189 return;
5190 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005191 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005192 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005193
Eric Laurente552edb2014-03-10 17:42:56 -07005194 // look for duplicated outputs connected to the output being removed.
5195 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005196 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5197 if (dupOutput->isDuplicated() &&
5198 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5199 sp<SwAudioOutputDescriptor> remainingOutput =
5200 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005201 // As all active tracks on duplicated output will be deleted,
5202 // and as they were also referenced on the other output, the reference
5203 // count for their stream type must be adjusted accordingly on
5204 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005205 const bool wasActive = remainingOutput->isActive();
5206 // Note: no-op on the closing output where all clients has already been set inactive
5207 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005208 // stop() will be a no op if the output is still active but is needed in case all
5209 // active streams refcounts where cleared above
5210 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005211 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005212 }
Eric Laurente552edb2014-03-10 17:42:56 -07005213 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5214 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5215
5216 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005217 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005218 }
5219 }
5220
Eric Laurent05b90f82014-08-27 15:32:29 -07005221 nextAudioPortGeneration();
5222
François Gaffie1c878552018-11-22 16:53:21 +01005223 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005224 if (index >= 0) {
5225 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005226 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5227 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005228 mAudioPatches.removeItemsAt(index);
5229 mpClientInterface->onAudioPatchListUpdate();
5230 }
5231
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005232 if (closingOutputWasActive) {
5233 closingOutput->stop();
5234 }
François Gaffie1c878552018-11-22 16:53:21 +01005235 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005236
François Gaffie53615e22015-03-19 09:24:12 +01005237 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005238 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005239
5240 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5241 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005242 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005243 bool directOutputOpen = false;
5244 for (size_t i = 0; i < mOutputs.size(); i++) {
5245 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5246 directOutputOpen = true;
5247 break;
5248 }
5249 }
5250 if (!directOutputOpen) {
5251 ALOGV("no direct outputs open, reset MSD patch");
5252 setMsdPatch();
5253 }
5254 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005255}
5256
5257void AudioPolicyManager::closeInput(audio_io_handle_t input)
5258{
5259 ALOGV("closeInput(%d)", input);
5260
5261 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5262 if (inputDesc == NULL) {
5263 ALOGW("closeInput() unknown input %d", input);
5264 return;
5265 }
5266
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005268
François Gaffie11d30102018-11-02 16:09:09 +01005269 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005270 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005271 if (index >= 0) {
5272 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005273 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5274 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005275 mAudioPatches.removeItemsAt(index);
5276 mpClientInterface->onAudioPatchListUpdate();
5277 }
5278
Eric Laurentfe231122017-11-17 17:48:06 -08005279 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005280 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005281
François Gaffie11d30102018-11-02 16:09:09 +01005282 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5283 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005284 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005285 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005286 }
Eric Laurente552edb2014-03-10 17:42:56 -07005287}
5288
François Gaffie11d30102018-11-02 16:09:09 +01005289SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5290 const DeviceVector &devices,
5291 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005292{
5293 SortedVector<audio_io_handle_t> outputs;
5294
François Gaffie11d30102018-11-02 16:09:09 +01005295 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005296 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005297 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005298 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005299 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005300 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005301 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005302 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005303 outputs.add(openOutputs.keyAt(i));
5304 }
5305 }
5306 return outputs;
5307}
5308
Mikhail Naganov37977152018-07-11 15:54:44 -07005309void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5310{
5311 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5312 // output is suspended before any tracks are moved to it
5313 checkA2dpSuspend();
5314 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005315 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005316 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005317 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005318 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005319 setMsdPatch();
5320 }
Mikhail Naganov37977152018-07-11 15:54:44 -07005321}
5322
François Gaffiec005e562018-11-06 15:04:49 +01005323bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5324 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005325{
François Gaffiec005e562018-11-06 15:04:49 +01005326 return mEngine->getProductStrategyForAttributes(lAttr) ==
5327 mEngine->getProductStrategyForAttributes(rAttr);
5328}
5329
5330void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5331{
5332 auto psId = mEngine->getProductStrategyForAttributes(attr);
5333
5334 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5335 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005336
François Gaffie11d30102018-11-02 16:09:09 +01005337 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5338 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005339
Eric Laurentc209fe42020-06-05 18:11:23 -07005340 uint32_t maxLatency = 0;
5341 bool invalidate = false;
5342 // take into account dynamic audio policies related changes: if a client is now associated
5343 // to a different policy mix than at creation time, invalidate corresponding stream
5344 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5345 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5346 if (desc->isDuplicated()) {
5347 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005348 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005349 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5350 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5351 continue;
5352 }
5353 sp<AudioPolicyMix> primaryMix;
5354 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5355 client->flags(), primaryMix, nullptr);
5356 if (status != OK) {
5357 continue;
5358 }
yucliuf4de36d2020-09-14 14:57:56 -07005359 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005360 invalidate = true;
5361 if (desc->isStrategyActive(psId)) {
5362 maxLatency = desc->latency();
5363 }
5364 break;
5365 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005366 }
5367 }
5368
Eric Laurentc209fe42020-06-05 18:11:23 -07005369 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005370 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5371 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005372 for (audio_io_handle_t srcOut : srcOutputs) {
5373 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005374 if (desc == nullptr) continue;
5375
5376 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005377 maxLatency = desc->latency();
5378 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005379
5380 if (invalidate) continue;
5381
5382 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005383 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005384 // a client on a non direct outputs has necessarily a linear PCM format
5385 // so we can call selectOutput() safely
5386 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5387 client->flags(),
5388 client->config().format,
5389 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005390 client->config().sample_rate,
5391 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005392 if (newOutput != srcOut) {
5393 invalidate = true;
5394 break;
5395 }
5396 } else {
5397 sp<IOProfile> profile = getProfileForOutput(newDevices,
5398 client->config().sample_rate,
5399 client->config().format,
5400 client->config().channel_mask,
5401 client->flags(),
5402 true /* directOnly */);
5403 if (profile != desc->mProfile) {
5404 invalidate = true;
5405 break;
5406 }
5407 }
5408 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005409 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005410
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005411 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005412 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005413 std::to_string(srcOutputs[0]).c_str(),
5414 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005415 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005416 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005417 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005418 if (desc == nullptr) continue;
5419
5420 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005421 setStrategyMute(psId, true, desc);
5422 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005423 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005424 }
François Gaffiec005e562018-11-06 15:04:49 +01005425 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentd60560a2015-04-10 11:31:20 -07005426 if (source != 0){
5427 connectAudioSource(source);
5428 }
Eric Laurente552edb2014-03-10 17:42:56 -07005429 }
5430
François Gaffiec005e562018-11-06 15:04:49 +01005431 // Move effects associated to this stream from previous output to new output
5432 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005433 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005434 }
François Gaffiec005e562018-11-06 15:04:49 +01005435 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005436 if (invalidate) {
5437 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5438 mpClientInterface->invalidateStream(stream);
5439 }
Eric Laurente552edb2014-03-10 17:42:56 -07005440 }
5441 }
5442}
5443
Eric Laurente0720872014-03-11 09:30:41 -07005444void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005445{
François Gaffiec005e562018-11-06 15:04:49 +01005446 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5447 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5448 checkOutputForAttributes(attributes);
5449 }
Eric Laurente552edb2014-03-10 17:42:56 -07005450}
5451
Kevin Rocard153f92d2018-12-18 18:33:28 -08005452void AudioPolicyManager::checkSecondaryOutputs() {
5453 std::set<audio_stream_type_t> streamsToInvalidate;
5454 for (size_t i = 0; i < mOutputs.size(); i++) {
5455 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5456 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005457 sp<AudioPolicyMix> primaryMix;
5458 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005459 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005460 client->flags(), primaryMix, &secondaryMixes);
5461 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5462 for (auto &secondaryMix : secondaryMixes) {
5463 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5464 if (outputDesc != nullptr &&
5465 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5466 secondaryDescs.push_back(outputDesc);
5467 }
5468 }
5469
Kevin Rocard94114a22019-04-01 19:38:23 -07005470 if (status != OK ||
5471 !std::equal(client->getSecondaryOutputs().begin(),
Kevin Rocard153f92d2018-12-18 18:33:28 -08005472 client->getSecondaryOutputs().end(),
5473 secondaryDescs.begin(), secondaryDescs.end())) {
5474 streamsToInvalidate.insert(client->stream());
5475 }
5476 }
5477 }
5478 for (audio_stream_type_t stream : streamsToInvalidate) {
5479 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5480 mpClientInterface->invalidateStream(stream);
5481 }
5482}
5483
Eric Laurente0720872014-03-11 09:30:41 -07005484void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005485{
François Gaffie53615e22015-03-19 09:24:12 +01005486 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005487 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005488 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005489 return;
5490 }
5491
Eric Laurent3a4311c2014-03-17 12:00:47 -07005492 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005493 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5494 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurentf732e072016-08-03 19:30:28 -07005495
5496 // if suspended, restore A2DP output if:
5497 // ((SCO device is NOT connected) ||
5498 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
5499 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005500 //
Eric Laurentf732e072016-08-03 19:30:28 -07005501 // if not suspended, suspend A2DP output if:
5502 // (SCO device is connected) &&
5503 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
5504 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005505 //
5506 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005507 if (!isScoConnected ||
5508 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
5509 AUDIO_POLICY_FORCE_BT_SCO) &&
5510 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
5511 AUDIO_POLICY_FORCE_BT_SCO) &&
5512 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005513 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005514
5515 mpClientInterface->restoreOutput(a2dpOutput);
5516 mA2dpSuspended = false;
5517 }
5518 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005519 if (isScoConnected &&
5520 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
5521 AUDIO_POLICY_FORCE_BT_SCO) ||
5522 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
5523 AUDIO_POLICY_FORCE_BT_SCO) ||
5524 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005525 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005526
5527 mpClientInterface->suspendOutput(a2dpOutput);
5528 mA2dpSuspended = true;
5529 }
5530 }
5531}
5532
François Gaffie11d30102018-11-02 16:09:09 +01005533DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5534 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
François Gaffie11d30102018-11-02 16:09:09 +01005536 DeviceVector devices;
5537
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005538 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 if (index >= 0) {
5540 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005541 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005542 ALOGV("%s device %s forced by patch %d", __func__,
5543 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5544 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005545 }
5546 }
5547
Dean Wheatley514b4312020-06-17 21:45:00 +10005548 // Do not retrieve engine device for outputs through MSD
5549 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5550 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5551 return outputDesc->devices();
5552 }
5553
Eric Laurent97ac8712018-07-27 18:59:02 -07005554 // Honor explicit routing requests only if no client using default routing is active on this
5555 // input: a specific app can not force routing for other apps by setting a preferred device.
5556 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005557 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005558 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005559 if (device != nullptr) {
5560 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005561 }
5562
François Gaffiea807ef92018-11-05 10:44:33 +01005563 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5564 // of setForceUse / Default Bus device here
5565 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5566 if (device != nullptr) {
5567 return DeviceVector(device);
5568 }
5569
François Gaffiec005e562018-11-06 15:04:49 +01005570 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5571 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5572 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Eric Laurent484e9272018-06-07 17:29:23 -07005573
François Gaffiec005e562018-11-06 15:04:49 +01005574 if ((hasVoiceStream(streams) &&
Henrik Backlund019c1732019-09-30 14:48:38 +02005575 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5576 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0)) ||
Eric Laurentf23a7712019-02-28 17:15:40 -08005577 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
François Gaffiec005e562018-11-06 15:04:49 +01005578 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5579 outputDesc->isStrategyActive(productStrategy)) {
5580 // Retrieval of devices for voice DL is done on primary output profile, cannot
5581 // check the route (would force modifying configuration file for this profile)
5582 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5583 break;
5584 }
Eric Laurente552edb2014-03-10 17:42:56 -07005585 }
François Gaffiec005e562018-11-06 15:04:49 +01005586 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005587 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005588}
5589
François Gaffie11d30102018-11-02 16:09:09 +01005590sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5591 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005592{
François Gaffie11d30102018-11-02 16:09:09 +01005593 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005594
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005595 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005596 if (index >= 0) {
5597 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005598 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005599 ALOGV("getNewInputDevice() device %s forced by patch %d",
5600 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5601 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005602 }
5603 }
5604
Eric Laurent97ac8712018-07-27 18:59:02 -07005605 // Honor explicit routing requests only if no client using default routing is active on this
5606 // input: a specific app can not force routing for other apps by setting a preferred device.
5607 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005608 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5609 if (device != nullptr) {
5610 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005611 }
5612
Eric Laurentdc95a252018-04-12 12:46:56 -07005613 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005614 // a null sp<>, causing the patch on the input stream to be released.
Francois Gaffie716e1432019-01-14 16:58:59 +01005615 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5616 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5617 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005618 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005619 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
François Gaffiec005e562018-11-06 15:04:49 +01005620 device = mEngine->getInputDeviceForAttributes(attributes);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005621 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005622
Eric Laurente552edb2014-03-10 17:42:56 -07005623 return device;
5624}
5625
Eric Laurent794fde22016-03-11 09:50:45 -08005626bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5627 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005628 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005629}
5630
Eric Laurente0720872014-03-11 09:30:41 -07005631audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005632 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005633 // getOutputDevicesForStream's behavior for invalid streams.
5634 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5635 // device for music stream), but we want to return the empty set.
5636 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005637 return AUDIO_DEVICE_NONE;
5638 }
François Gaffie11d30102018-11-02 16:09:09 +01005639 DeviceVector activeDevices;
5640 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01005641 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5642 curStream = (audio_stream_type_t) (curStream + 1)) {
5643 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005644 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005645 }
François Gaffiec005e562018-11-06 15:04:49 +01005646 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005647 devices.merge(curDevices);
5648 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005649 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005650 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005651 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005652 }
5653 }
Eric Laurente552edb2014-03-10 17:42:56 -07005654 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005655
Eric Laurentb0688d62018-08-14 15:49:18 -07005656 // Favor devices selected on active streams if any to report correct device in case of
5657 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005658 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005659 devices = activeDevices;
5660 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005661 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5662 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005663 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005664 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005665 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005666 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005667 }
jiabin9a3361e2019-10-01 09:38:30 -07005668 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5669 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005670}
5671
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005672status_t AudioPolicyManager::getDevicesForAttributes(
5673 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5674 if (devices == nullptr) {
5675 return BAD_VALUE;
5676 }
5677 // check dynamic policies but only for primary descriptors (secondary not used for audible
5678 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005679 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005680 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005681 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005682 if (status != OK) {
5683 return status;
5684 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005685 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5686 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5687 devices->push_back(device);
5688 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005689 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005690 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5691 for (const auto& device : curDevices) {
5692 devices->push_back(device->getDeviceTypeAddr());
5693 }
5694 return NO_ERROR;
5695}
5696
Eric Laurente0720872014-03-11 09:30:41 -07005697void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005698 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005699 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005700 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005701 updateDevicesAndOutputs();
5702 break;
5703 default:
5704 break;
5705 }
5706}
5707
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005708uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07005709
5710 // skip beacon mute management if a dedicated TTS output is available
5711 if (mTtsOutputAvailable) {
5712 return 0;
5713 }
5714
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005715 switch(event) {
5716 case STARTING_OUTPUT:
5717 mBeaconMuteRefCount++;
5718 break;
5719 case STOPPING_OUTPUT:
5720 if (mBeaconMuteRefCount > 0) {
5721 mBeaconMuteRefCount--;
5722 }
5723 break;
5724 case STARTING_BEACON:
5725 mBeaconPlayingRefCount++;
5726 break;
5727 case STOPPING_BEACON:
5728 if (mBeaconPlayingRefCount > 0) {
5729 mBeaconPlayingRefCount--;
5730 }
5731 break;
5732 }
5733
5734 if (mBeaconMuteRefCount > 0) {
5735 // any playback causes beacon to be muted
5736 return setBeaconMute(true);
5737 } else {
5738 // no other playback: unmute when beacon starts playing, mute when it stops
5739 return setBeaconMute(mBeaconPlayingRefCount == 0);
5740 }
5741}
5742
5743uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5744 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5745 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5746 // keep track of muted state to avoid repeating mute/unmute operations
5747 if (mBeaconMuted != mute) {
5748 // mute/unmute AUDIO_STREAM_TTS on all outputs
5749 ALOGV("\t muting %d", mute);
5750 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01005751 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005752 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005753 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07005754 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005755 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07005756 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005757 maxLatency = latency;
5758 }
5759 }
5760 mBeaconMuted = mute;
5761 return maxLatency;
5762 }
5763 return 0;
5764}
5765
Eric Laurente0720872014-03-11 09:30:41 -07005766void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07005767{
François Gaffiec005e562018-11-06 15:04:49 +01005768 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07005769 mPreviousOutputs = mOutputs;
5770}
5771
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005772uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01005773 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07005774 uint32_t delayMs)
5775{
5776 // mute/unmute strategies using an incompatible device combination
5777 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5778 // if unmuting, unmute only after the specified delay
5779 if (outputDesc->isDuplicated()) {
5780 return 0;
5781 }
5782
5783 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01005784 DeviceVector devices = outputDesc->devices();
5785 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07005786
François Gaffiec005e562018-11-06 15:04:49 +01005787 auto productStrategies = mEngine->getOrderedProductStrategies();
5788 for (const auto &productStrategy : productStrategies) {
5789 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5790 DeviceVector curDevices =
5791 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5792 curDevices = curDevices.filter(outputDesc->supportedDevices());
5793 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005794 bool doMute = false;
5795
François Gaffiec005e562018-11-06 15:04:49 +01005796 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005797 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005798 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5799 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005800 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01005801 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07005802 }
Eric Laurent99401132014-05-07 19:48:15 -07005803 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07005804 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005805 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07005806 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01005807 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07005808 continue;
5809 }
François Gaffiec005e562018-11-06 15:04:49 +01005810 ALOGVV("%s() %s (curDevice %s)", __func__,
5811 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5812 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5813 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07005814 if (mute) {
5815 // FIXME: should not need to double latency if volume could be applied
5816 // immediately by the audioflinger mixer. We must account for the delay
5817 // between now and the next time the audioflinger thread for this output
5818 // will process a buffer (which corresponds to one buffer size,
5819 // usually 1/2 or 1/4 of the latency).
5820 if (muteWaitMs < desc->latency() * 2) {
5821 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07005822 }
5823 }
5824 }
5825 }
5826 }
5827 }
5828
Eric Laurent99401132014-05-07 19:48:15 -07005829 // temporary mute output if device selection changes to avoid volume bursts due to
5830 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01005831 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005832 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5833 // temporary mute duration is conservatively set to 4 times the reported latency
5834 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5835 if (muteWaitMs < tempMuteWaitMs) {
5836 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005837 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01005838 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5839 // make sure that we do not start the temporary mute period too early in case of
5840 // delayed device change
5841 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5842 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01005843 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07005844 }
5845 }
5846
Eric Laurente552edb2014-03-10 17:42:56 -07005847 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5848 if (muteWaitMs > delayMs) {
5849 muteWaitMs -= delayMs;
5850 usleep(muteWaitMs * 1000);
5851 return muteWaitMs;
5852 }
5853 return 0;
5854}
5855
François Gaffie11d30102018-11-02 16:09:09 +01005856uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5857 const DeviceVector &devices,
5858 bool force,
5859 int delayMs,
5860 audio_patch_handle_t *patchHandle,
5861 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07005862{
François Gaffie11d30102018-11-02 16:09:09 +01005863 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005864 uint32_t muteWaitMs;
5865
5866 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01005867 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5868 nullptr /* patchHandle */, requiresMuteCheck);
5869 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5870 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07005871 return muteWaitMs;
5872 }
Eric Laurente552edb2014-03-10 17:42:56 -07005873
5874 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01005875 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01005876 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07005877
François Gaffie11d30102018-11-02 16:09:09 +01005878 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5879
5880 if (!filteredDevices.isEmpty()) {
5881 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07005882 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005883
5884 // if the outputs are not materially active, there is no need to mute.
5885 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01005886 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00005887 } else {
5888 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5889 muteWaitMs = 0;
5890 }
Eric Laurente552edb2014-03-10 17:42:56 -07005891
Eric Laurent79ea9582020-06-11 18:49:24 -07005892 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5893 // output profile or if new device is not supported AND previous device(s) is(are) still
5894 // available (otherwise reset device must be done on the output)
5895 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5896 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5897 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5898 // restore previous device after evaluating strategy mute state
5899 outputDesc->setDevices(prevDevices);
5900 return muteWaitMs;
5901 }
5902
Eric Laurente552edb2014-03-10 17:42:56 -07005903 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005904 // the requested device is AUDIO_DEVICE_NONE
5905 // OR the requested device is the same as current device
5906 // AND force is not specified
5907 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01005908 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08005909 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01005910 !force && outputDesc->getPatchHandle() != 0) {
5911 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5912 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07005913 return muteWaitMs;
5914 }
5915
François Gaffie11d30102018-11-02 16:09:09 +01005916 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07005917
Eric Laurente552edb2014-03-10 17:42:56 -07005918 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01005919 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005920 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005921 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005922 PatchBuilder patchBuilder;
5923 patchBuilder.addSource(outputDesc);
5924 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5925 for (const auto &filteredDevice : filteredDevices) {
5926 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07005927 }
5928
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08005929 // Add half reported latency to delayMs when muteWaitMs is null in order
5930 // to avoid disordered sequence of muting volume and changing devices.
5931 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
5932 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005933 }
Eric Laurente552edb2014-03-10 17:42:56 -07005934
5935 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01005936 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005937
5938 return muteWaitMs;
5939}
5940
Eric Laurentc75307b2015-03-17 15:29:32 -07005941status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005942 int delayMs,
5943 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005944{
Eric Laurent6a94d692014-05-20 11:18:06 -07005945 ssize_t index;
5946 if (patchHandle) {
5947 index = mAudioPatches.indexOfKey(*patchHandle);
5948 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005949 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005950 }
5951 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005952 return INVALID_OPERATION;
5953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005954 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005955 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005956 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005957 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01005958 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005961 return status;
5962}
5963
5964status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01005965 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005966 bool force,
5967 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005968{
5969 status_t status = NO_ERROR;
5970
Eric Laurent1f2f2232014-06-02 12:01:23 -07005971 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01005972 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5973 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07005974
François Gaffie11d30102018-11-02 16:09:09 +01005975 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07005976 PatchBuilder patchBuilder;
5977 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005978 // AUDIO_SOURCE_HOTWORD is for internal use only:
5979 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07005980 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5981 auto result = usecase;
5982 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5983 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5984 }
5985 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07005986 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01005987 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005988 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005989 }
5990 }
5991 return status;
5992}
5993
Eric Laurent6a94d692014-05-20 11:18:06 -07005994status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5995 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005996{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005997 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005998 ssize_t index;
5999 if (patchHandle) {
6000 index = mAudioPatches.indexOfKey(*patchHandle);
6001 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006002 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006003 }
6004 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006005 return INVALID_OPERATION;
6006 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006007 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006008 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006009 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006010 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006011 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006012 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006013 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006014 return status;
6015}
6016
François Gaffie11d30102018-11-02 16:09:09 +01006017sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006018 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006019 audio_format_t& format,
6020 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006021 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006022{
6023 // Choose an input profile based on the requested capture parameters: select the first available
6024 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006025 //
6026 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6027 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006028
Glenn Kasten730b9262018-03-29 15:01:26 -07006029 sp<IOProfile> firstInexact;
6030 uint32_t updatedSamplingRate = 0;
6031 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6032 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006033 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006034 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006035 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006036 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006037 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006038 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006039 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006040 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006041 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006042 &channelMask /*updatedChannelMask*/,
6043 // FIXME ugly cast
6044 (audio_output_flags_t) flags,
6045 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006046 return profile;
6047 }
François Gaffie11d30102018-11-02 16:09:09 +01006048 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006049 samplingRate,
6050 &updatedSamplingRate,
6051 format,
6052 &updatedFormat,
6053 channelMask,
6054 &updatedChannelMask,
6055 // FIXME ugly cast
6056 (audio_output_flags_t) flags,
6057 false /*exactMatchRequiredForInputFlags*/)) {
6058 firstInexact = profile;
6059 }
6060
Eric Laurente552edb2014-03-10 17:42:56 -07006061 }
6062 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006063 if (firstInexact != nullptr) {
6064 samplingRate = updatedSamplingRate;
6065 format = updatedFormat;
6066 channelMask = updatedChannelMask;
6067 return firstInexact;
6068 }
Eric Laurente552edb2014-03-10 17:42:56 -07006069 return NULL;
6070}
6071
François Gaffieaaac0fd2018-11-22 17:56:39 +01006072float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6073 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006074 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006075 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006076{
jiabin9a3361e2019-10-01 09:38:30 -07006077 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006078
6079 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6080 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6081 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6082 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006083 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6084 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6085 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6086 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006087 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006088
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006089 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006090 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6091 mOutputs.isActive(ringVolumeSrc, 0)) {
6092 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006093 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006094 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006095 }
6096
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006097 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006098 if ((volumeSource != callVolumeSrc && (isInCall() ||
6099 mOutputs.isActiveLocally(callVolumeSrc))) &&
6100 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6101 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6102 volumeSource == alarmVolumeSrc ||
6103 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6104 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6105 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006106 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006107 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006108 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006109 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006110 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006111 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006112 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6113 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6114 // programmatically muted.
6115 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6116 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6117 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006118 bool exemptFromCapping =
6119 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6120 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006121 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6122 volumeSource, volumeDb);
6123 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006124 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6125 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6126 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006127 }
6128 }
Eric Laurente552edb2014-03-10 17:42:56 -07006129 // if a headset is connected, apply the following rules to ring tones and notifications
6130 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006131 // - always attenuate notifications volume by 6dB
6132 // - attenuate ring tones volume by 6dB unless music is not playing and
6133 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006134 // - if music is playing, always limit the volume to current music volume,
6135 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006136 if (!Intersection(deviceTypes,
6137 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6138 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006139 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6140 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006141 ((volumeSource == alarmVolumeSrc ||
6142 volumeSource == ringVolumeSrc) ||
6143 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6144 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6145 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6146 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6147 curves.canBeMuted()) {
6148
Eric Laurente552edb2014-03-10 17:42:56 -07006149 // when the phone is ringing we must consider that music could have been paused just before
6150 // by the music application and behave as if music was active if the last music track was
6151 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006152 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006153 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006154 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006155 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006156 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6157 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006158 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006159 float musicVolDb = computeVolume(musicCurves,
6160 musicVolumeSrc,
6161 musicCurves.getVolumeIndex(musicDevice),
6162 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006163 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6164 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6165 if (volumeDb > minVolDb) {
6166 volumeDb = minVolDb;
6167 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006168 }
jiabin9a3361e2019-10-01 09:38:30 -07006169 if (!Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6170 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006171 // on A2DP, also ensure notification volume is not too low compared to media when
6172 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006173 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006174 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006175 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6176 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006177 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6178 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006179 }
6180 }
jiabin9a3361e2019-10-01 09:38:30 -07006181 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006182 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006183 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006184 }
6185 }
6186
François Gaffie43c73442018-11-08 08:21:55 +01006187 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006188}
6189
Eric Laurent3839bc02018-07-10 18:33:34 -07006190int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006191 VolumeSource fromVolumeSource,
6192 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006193{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006194 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006195 return srcIndex;
6196 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006197 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6198 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006199 float minSrc = (float)srcCurves.getVolumeIndexMin();
6200 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6201 float minDst = (float)dstCurves.getVolumeIndexMin();
6202 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006203
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006204 // preserve mute request or correct range
6205 if (srcIndex < minSrc) {
6206 if (srcIndex == 0) {
6207 return 0;
6208 }
6209 srcIndex = minSrc;
6210 } else if (srcIndex > maxSrc) {
6211 srcIndex = maxSrc;
6212 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006213 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6214}
6215
François Gaffieaaac0fd2018-11-22 17:56:39 +01006216status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6217 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006218 int index,
6219 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006220 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006221 int delayMs,
6222 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006223{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006224 // do not change actual attributes volume if the attributes is muted
6225 if (outputDesc->isMuted(volumeSource)) {
6226 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6227 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006228 return NO_ERROR;
6229 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006230 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6231 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6232 bool isVoiceVolSrc = callVolSrc == volumeSource;
6233 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6234
François Gaffie2110e042015-03-24 08:41:51 +01006235 audio_policy_forced_cfg_t forceUseForComm =
6236 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07006237 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006238 // if sco and call follow same curves, bypass forceUseForComm
6239 if ((callVolSrc != btScoVolSrc) &&
6240 ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
6241 (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
6242 ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
6243 volumeSource, forceUseForComm);
Eric Laurent571ef962020-07-24 11:43:48 -07006244 // Do not return an error here as AudioService will always set both voice call
6245 // and bluetooth SCO volumes due to stream aliasing.
6246 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006247 }
jiabin9a3361e2019-10-01 09:38:30 -07006248 if (deviceTypes.empty()) {
6249 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006250 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006251
jiabin9a3361e2019-10-01 09:38:30 -07006252 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6253 if (outputDesc->isFixedVolume(deviceTypes) ||
HW Leeda7581e2018-05-22 18:31:34 +08006254 // Force VoIP volume to max for bluetooth SCO
jiabin9a3361e2019-10-01 09:38:30 -07006255
6256 ((isVoiceVolSrc || isBtScoVolSrc) &&
6257 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006258 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006259 }
jiabin9a3361e2019-10-01 09:38:30 -07006260 outputDesc->setVolume(
6261 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006262
François Gaffieaaac0fd2018-11-22 17:56:39 +01006263 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006264 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006265 // 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 +01006266 if (isVoiceVolSrc) {
6267 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006268 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006269 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006270 }
Eric Laurent18fba842016-03-31 14:41:26 -07006271 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006272 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6273 mLastVoiceVolume = voiceVolume;
6274 }
6275 }
Eric Laurente552edb2014-03-10 17:42:56 -07006276 return NO_ERROR;
6277}
6278
Eric Laurentc75307b2015-03-17 15:29:32 -07006279void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006280 const DeviceTypeSet& deviceTypes,
6281 int delayMs,
6282 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006283{
jiabincd510522020-01-22 09:40:55 -08006284 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006285 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6286 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6287 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006288 curves.getVolumeIndex(deviceTypes),
6289 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006290 }
6291}
6292
François Gaffiec005e562018-11-06 15:04:49 +01006293void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6294 bool on,
6295 const sp<AudioOutputDescriptor>& outputDesc,
6296 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006297 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006298{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006299 std::vector<VolumeSource> sourcesToMute;
6300 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6301 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6302 toString(attributes).c_str(), on, outputDesc->getId());
6303 VolumeSource source = toVolumeSource(attributes);
6304 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6305 sourcesToMute.push_back(source);
6306 }
Eric Laurente552edb2014-03-10 17:42:56 -07006307 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006308 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006309 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006310 }
6311
Eric Laurente552edb2014-03-10 17:42:56 -07006312}
6313
François Gaffieaaac0fd2018-11-22 17:56:39 +01006314void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6315 bool on,
6316 const sp<AudioOutputDescriptor>& outputDesc,
6317 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006318 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006319{
jiabin9a3361e2019-10-01 09:38:30 -07006320 if (deviceTypes.empty()) {
6321 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006322 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006323 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006324 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006325 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006326 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006327 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6328 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6329 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006330 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006331 }
6332 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006333 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6334 // ignored
6335 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006336 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006337 if (!outputDesc->isMuted(volumeSource)) {
6338 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006339 return;
6340 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006341 if (outputDesc->decMuteCount(volumeSource) == 0) {
6342 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006343 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006344 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006345 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006346 delayMs);
6347 }
6348 }
6349}
6350
François Gaffie53615e22015-03-19 09:24:12 +01006351bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6352{
François Gaffiec005e562018-11-06 15:04:49 +01006353 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006354 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6355 return true;
6356 }
6357
6358 // has known usage?
6359 switch (paa->usage) {
6360 case AUDIO_USAGE_UNKNOWN:
6361 case AUDIO_USAGE_MEDIA:
6362 case AUDIO_USAGE_VOICE_COMMUNICATION:
6363 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6364 case AUDIO_USAGE_ALARM:
6365 case AUDIO_USAGE_NOTIFICATION:
6366 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6367 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6368 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6369 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6370 case AUDIO_USAGE_NOTIFICATION_EVENT:
6371 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6372 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6373 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6374 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006375 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006376 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006377 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006378 case AUDIO_USAGE_EMERGENCY:
6379 case AUDIO_USAGE_SAFETY:
6380 case AUDIO_USAGE_VEHICLE_STATUS:
6381 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006382 break;
6383 default:
6384 return false;
6385 }
6386 return true;
6387}
6388
François Gaffie2110e042015-03-24 08:41:51 +01006389audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6390{
6391 return mEngine->getForceUse(usage);
6392}
6393
6394bool AudioPolicyManager::isInCall()
6395{
6396 return isStateInCall(mEngine->getPhoneState());
6397}
6398
6399bool AudioPolicyManager::isStateInCall(int state)
6400{
6401 return is_state_in_call(state);
6402}
6403
Eric Laurent74b71512019-11-06 17:21:57 -08006404bool AudioPolicyManager::isCallAudioAccessible()
6405{
6406 audio_mode_t mode = mEngine->getPhoneState();
6407 return (mode == AUDIO_MODE_IN_CALL)
6408 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6409 || (mode == AUDIO_MODE_CALL_SCREEN);
6410}
6411
Eric Laurentd60560a2015-04-10 11:31:20 -07006412void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6413{
6414 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006415 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6416 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
6417 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
6418 stopAudioSource(sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006419 }
6420 }
6421
6422 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6423 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6424 bool release = false;
6425 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6426 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6427 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6428 source->ext.device.type == deviceDesc->type()) {
6429 release = true;
6430 }
6431 }
6432 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6433 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6434 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6435 sink->ext.device.type == deviceDesc->type()) {
6436 release = true;
6437 }
6438 }
6439 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006440 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6441 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006442 }
6443 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006444
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006445 mInputs.clearSessionRoutesForDevice(deviceDesc);
6446
Francois Gaffie716e1432019-01-14 16:58:59 +01006447 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006448}
6449
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006450void AudioPolicyManager::modifySurroundFormats(
6451 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006452 std::unordered_set<audio_format_t> enforcedSurround(
6453 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006454 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6455 for (const auto& pair : mConfig.getSurroundFormats()) {
6456 allSurround.insert(pair.first);
6457 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6458 }
Phil Burk09bc4612016-02-24 15:58:15 -08006459
6460 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6461 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006462 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006463 // This is the resulting set of formats depending on the surround mode:
6464 // 'all surround' = allSurround
6465 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6466 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6467 // 'manual surround' = mManualSurroundFormats
6468 // AUTO: formats v 'enforced surround'
6469 // ALWAYS: formats v 'all surround' v 'enforced surround'
6470 // NEVER: formats ^ 'non-surround'
6471 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006472
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006473 std::unordered_set<audio_format_t> formatSet;
6474 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6475 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006476 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006477 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006478 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006479 formatSet.insert(*formatIter);
6480 }
6481 }
6482 } else {
6483 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6484 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006485 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006486
jiabin81772902018-04-02 17:52:27 -07006487 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006488 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006489 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6490 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6491 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006492 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006493 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6494 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6495 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006496 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006497 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006498 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006499 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006500 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006501 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006502}
6503
jiabin06e4bab2019-07-29 10:13:34 -07006504void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6505 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006506 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6507 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6508
6509 // If NEVER, then remove support for channelMasks > stereo.
6510 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006511 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6512 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006513 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6514 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006515 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006516 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006517 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006518 }
6519 }
jiabin81772902018-04-02 17:52:27 -07006520 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6521 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6522 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006523 bool supports5dot1 = false;
6524 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006525 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006526 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6527 supports5dot1 = true;
6528 break;
6529 }
6530 }
6531 // If not then add 5.1 support.
6532 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006533 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006534 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006535 }
Phil Burk09bc4612016-02-24 15:58:15 -08006536 }
6537}
6538
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006539void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006540 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006541 AudioProfileVector &profiles)
6542{
6543 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006544 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006545
François Gaffie112b0af2015-11-19 16:13:25 +01006546 // Format MUST be checked first to update the list of AudioProfile
6547 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006548 reply = mpClientInterface->getParameters(
6549 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006550 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006551 AudioParameter repliedParameters(reply);
6552 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006553 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006554 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6555 return;
6556 }
Phil Burk09bc4612016-02-24 15:58:15 -08006557 FormatVector formats = formatsFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006558 if (device == AUDIO_DEVICE_OUT_HDMI
6559 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006560 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006561 }
jiabin3e277cc2019-09-10 14:27:34 -07006562 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006563 }
François Gaffie112b0af2015-11-19 16:13:25 +01006564
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006565 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006566 ChannelMaskSet channelMasks;
6567 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006568 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006569 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006570
6571 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006572 reply = mpClientInterface->getParameters(
6573 ioHandle,
6574 requestedParameters.toString() + ";" +
6575 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006576 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006577 AudioParameter repliedParameters(reply);
6578 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006579 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006580 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006581 }
6582 }
6583 if (profiles.hasDynamicChannelsFor(format)) {
6584 reply = mpClientInterface->getParameters(ioHandle,
6585 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006586 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006587 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006588 AudioParameter repliedParameters(reply);
6589 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006590 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006591 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006592 if (device == AUDIO_DEVICE_OUT_HDMI
6593 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006594 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006595 }
François Gaffie112b0af2015-11-19 16:13:25 +01006596 }
6597 }
jiabin3e277cc2019-09-10 14:27:34 -07006598 addDynamicAudioProfileAndSort(
6599 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006600 }
6601}
Eric Laurentd60560a2015-04-10 11:31:20 -07006602
Mikhail Naganovdc769682018-05-04 15:34:08 -07006603status_t AudioPolicyManager::installPatch(const char *caller,
6604 audio_patch_handle_t *patchHandle,
6605 AudioIODescriptorInterface *ioDescriptor,
6606 const struct audio_patch *patch,
6607 int delayMs)
6608{
6609 ssize_t index = mAudioPatches.indexOfKey(
6610 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6611 *patchHandle : ioDescriptor->getPatchHandle());
6612 sp<AudioPatch> patchDesc;
6613 status_t status = installPatch(
6614 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6615 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006616 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006617 }
6618 return status;
6619}
6620
6621status_t AudioPolicyManager::installPatch(const char *caller,
6622 ssize_t index,
6623 audio_patch_handle_t *patchHandle,
6624 const struct audio_patch *patch,
6625 int delayMs,
6626 uid_t uid,
6627 sp<AudioPatch> *patchDescPtr)
6628{
6629 sp<AudioPatch> patchDesc;
6630 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6631 if (index >= 0) {
6632 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006633 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006634 }
6635
6636 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6637 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6638 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6639 if (status == NO_ERROR) {
6640 if (index < 0) {
6641 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006642 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006643 } else {
6644 patchDesc->mPatch = *patch;
6645 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006646 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006647 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006648 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006649 }
6650 nextAudioPortGeneration();
6651 mpClientInterface->onAudioPatchListUpdate();
6652 }
6653 if (patchDescPtr) *patchDescPtr = patchDesc;
6654 return status;
6655}
6656
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08006657} // namespace android