blob: 3cfb944595f5752b8cbd73d117e883405fff9c9a [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
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabinf042b9b2021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070041#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070043#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070044#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070045#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070046#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070047#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070048#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <utils/Log.h>
50
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurent3b73df72014-03-11 09:06:29 -070054namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070055
Svet Ganov33761132021-05-13 22:51:08 +000056using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110067static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
68 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110071static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110072 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
jiabin06e4bab2019-07-29 10:13:34 -070076template <typename T>
77bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
78{
79 if (left.size() != right.size()) {
80 return false;
81 }
82 for (size_t index = 0; index < right.size(); index++) {
83 if (left[index] != right[index]) {
84 return false;
85 }
86 }
87 return true;
88}
89
90template <typename T>
91bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
92{
93 return !(left == right);
94}
95
Eric Laurente552edb2014-03-10 17:42:56 -070096// ----------------------------------------------------------------------------
97// AudioPolicyInterface implementation
98// ----------------------------------------------------------------------------
99
Eric Laurente0720872014-03-11 09:30:41 -0700100status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800101 audio_policy_dev_state_t state,
102 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 const char *device_name,
104 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700105{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 status_t status = setDeviceConnectionStateInt(device, state, device_address,
107 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
François Gaffie11d30102018-11-02 16:09:09 +0100112void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
113 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200114{
Mikhail Naganovd7ba61d2022-02-01 23:53:59 +0000115 audio_port_v7 devicePort;
116 device->toAudioPort(&devicePort);
117 if (status_t status = mpClientInterface->setDeviceConnectedState(
118 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
119 status != OK) {
120 ALOGE("Error %d while setting connected state for device %s", status,
121 device->getDeviceTypeAddr().toString(false).c_str());
122 }
François Gaffie44481e72016-04-20 07:49:57 +0200123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800126 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800127 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800128 const char *device_name,
129 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800130{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800131 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
132 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700133
134 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100135 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700136
François Gaffie11d30102018-11-02 16:09:09 +0100137 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800138 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100139 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700140 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
141}
Paul McLeane743a472015-01-28 11:07:31 -0800142
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700143status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
144 audio_policy_dev_state_t state)
145{
Eric Laurente552edb2014-03-10 17:42:56 -0700146 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700147 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700148 SortedVector <audio_io_handle_t> outputs;
149
François Gaffie11d30102018-11-02 16:09:09 +0100150 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700151
Eric Laurente552edb2014-03-10 17:42:56 -0700152 // save a copy of the opened output descriptors before any output is opened or closed
153 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
154 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700155 switch (state)
156 {
157 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800158 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100160 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700161 return INVALID_OPERATION;
162 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800163 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700164 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700165
Eric Laurente552edb2014-03-10 17:42:56 -0700166 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200167 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700168 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700169 }
170
François Gaffie44481e72016-04-20 07:49:57 +0200171 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
172 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100173 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200174
François Gaffie11d30102018-11-02 16:09:09 +0100175 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
176 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200177
Francois Gaffie716e1432019-01-14 16:58:59 +0100178 mHwModules.cleanUpForDevice(device);
179
François Gaffie11d30102018-11-02 16:09:09 +0100180 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700181 return INVALID_OPERATION;
182 }
François Gaffie2110e042015-03-24 08:41:51 +0100183
jiabin1c4794b2020-05-05 10:08:05 -0700184 // Populate encapsulation information when a output device is connected.
185 device->setEncapsulationInfoFromHal(mpClientInterface);
186
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700187 // outputs should never be empty here
188 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
189 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100190 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800191
Eric Laurent3ae5f312015-02-03 17:12:08 -0800192 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700194 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
199
François Gaffie11d30102018-11-02 16:09:09 +0100200 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700201
Paul McLeane743a472015-01-28 11:07:31 -0800202 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100203 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700204
Eric Laurente552edb2014-03-10 17:42:56 -0700205 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100206 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700207
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100208 mOutputs.clearSessionRoutesForDevice(device);
209
François Gaffie11d30102018-11-02 16:09:09 +0100210 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100211
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800212 // Reset active device codec
213 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
214
Kriti Dangef6be8f2020-11-05 11:58:19 +0100215 // remove device from mReportedFormatsMap cache
216 mReportedFormatsMap.erase(device);
217
Eric Laurente552edb2014-03-10 17:42:56 -0700218 } break;
219
220 default:
François Gaffie11d30102018-11-02 16:09:09 +0100221 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700222 return BAD_VALUE;
223 }
224
Eric Laurent736a1022019-03-27 18:28:46 -0700225 // Propagate device availability to Engine
226 setEngineDeviceConnectionState(device, state);
227
Eric Laurentae970022019-01-29 14:25:04 -0800228 // No need to evaluate playback routing when connecting a remote submix
229 // output device used by a dynamic policy of type recorder as no
230 // playback use case is affected.
231 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700232 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800233 for (audio_io_handle_t output : outputs) {
234 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800235 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
236 if (policyMix != nullptr
237 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700238 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800239 doCheckForDeviceAndOutputChanges = false;
240 break;
241 }
242 }
243 }
244
245 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700246 // outputs must be closed after checkOutputForAllStrategies() is executed
247 if (!outputs.isEmpty()) {
248 for (audio_io_handle_t output : outputs) {
249 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100250 // close unused outputs after device disconnection or direct outputs that have
251 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200252 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
253 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800254 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200255 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 closeOutput(output);
257 }
Eric Laurente552edb2014-03-10 17:42:56 -0700258 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700259 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
260 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700261 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700262 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800263 };
264
265 if (doCheckForDeviceAndOutputChanges) {
266 checkForDeviceAndOutputChanges(checkCloseOutputs);
267 } else {
268 checkCloseOutputs();
269 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100270 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700271 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100272 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700273 const DeviceVector activeMediaDevices =
274 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700275 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700276 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530277 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
278 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100279 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700280 // do not force device change on duplicated output because if device is 0, it will
281 // also force a device 0 for the two outputs it is duplicated to which may override
282 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100283 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100284 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700285 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 // always force when disconnecting (a non-duplicated device)
287 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100288 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700289 }
jiabinbce0c1d2020-10-05 11:20:18 -0700290 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000291 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700292 desc->supportsDevicesForPlayback(activeMediaDevices)) {
293 // Reopen the output to query the dynamic profiles when there is not active
294 // clients or all active clients will be rerouted. Otherwise, set the flag
295 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
296 // can be reopened to query dynamic profiles when all clients are inactive.
297 if (areAllActiveTracksRerouted(desc)) {
298 outputsToReopen.push_back(mOutputs.keyAt(i));
299 } else {
300 desc->mPendingReopenToQueryProfiles = true;
301 }
302 }
303 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
304 // Clear the flag that previously set for re-querying profiles.
305 desc->mPendingReopenToQueryProfiles = false;
306 }
307 }
308 for (const auto& output : outputsToReopen) {
309 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
310 closeOutput(output);
311 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
313
Eric Laurentd60560a2015-04-10 11:31:20 -0700314 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100315 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700316 }
317
Eric Laurent72aa32f2014-05-30 18:51:48 -0700318 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700319 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700320 } // end if is output device
321
Eric Laurente552edb2014-03-10 17:42:56 -0700322 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100324 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700325 switch (state)
326 {
327 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700328 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700329 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100330 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700331 return INVALID_OPERATION;
332 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700333
334 if (mAvailableInputDevices.add(device) < 0) {
335 return NO_MEMORY;
336 }
337
François Gaffie44481e72016-04-20 07:49:57 +0200338 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
339 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100340 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200341
Eric Laurent0dd51852019-04-19 18:18:58 -0700342 if (checkInputsForDevice(device, state) != NO_ERROR) {
343 mAvailableInputDevices.remove(device);
344
François Gaffie11d30102018-11-02 16:09:09 +0100345 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100346
347 mHwModules.cleanUpForDevice(device);
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 return INVALID_OPERATION;
350 }
351
Eric Laurentd4692962014-05-05 18:13:44 -0700352 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700353
354 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700355 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700356 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100357 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700358 return INVALID_OPERATION;
359 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700360
François Gaffie11d30102018-11-02 16:09:09 +0100361 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
363 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100364 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700365
François Gaffie11d30102018-11-02 16:09:09 +0100366 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700367
368 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100369
370 // remove device from mReportedFormatsMap cache
371 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700372 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700373
374 default:
François Gaffie11d30102018-11-02 16:09:09 +0100375 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700376 return BAD_VALUE;
377 }
378
Eric Laurent736a1022019-03-27 18:28:46 -0700379 // Propagate device availability to Engine
380 setEngineDeviceConnectionState(device, state);
381
Eric Laurent0dd51852019-04-19 18:18:58 -0700382 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700383 // As the input device list can impact the output device selection, update
384 // getDeviceForStrategy() cache
385 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700386
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100387 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200388 // Reconnect Audio Source
389 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
390 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
391 checkAudioSourceForAttributes(attributes);
392 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700393 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100394 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700395 }
396
Eric Laurentb52c1522014-05-20 11:27:36 -0700397 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700399 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700400
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return BAD_VALUE;
403}
404
Eric Laurent736a1022019-03-27 18:28:46 -0700405void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
406 audio_policy_dev_state_t state) {
407
408 // the Engine does not have to know about remote submix devices used by dynamic audio policies
409 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
410 return;
411 }
412 mEngine->setDeviceConnectionState(device, state);
413}
414
415
Eric Laurente0720872014-03-11 09:30:41 -0700416audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100417 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700418{
Eric Laurent634b7142016-04-20 13:48:02 -0700419 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800420 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
421 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700422 (strlen(device_address) != 0)/*matchAddress*/);
423
424 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100425 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700426 device, device_address);
427 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
428 }
François Gaffie53615e22015-03-19 09:24:12 +0100429
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 DeviceVector *deviceVector;
431
Eric Laurente552edb2014-03-10 17:42:56 -0700432 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700433 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700434 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 deviceVector = &mAvailableInputDevices;
436 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700438 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700439 }
Eric Laurent634b7142016-04-20 13:48:02 -0700440
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800441 return (deviceVector->getDevice(
442 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700443 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800444}
445
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800446status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
447 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800448 const char *device_name,
449 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800450{
451 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700452 String8 reply;
453 AudioParameter param;
454 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800455
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800456 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
457 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800458
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800459 // connect/disconnect only 1 device at a time
460 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
461
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700463 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800464 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800465 // Nothing to do: device is not connected
466 return NO_ERROR;
467 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800469
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700470 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800471 // configure codecs.
472 // Handle two specific cases by sending a set parameter to
473 // configure A2DP codecs. No need to toggle device state.
474 // Case 1: A2DP active device switches from primary to primary
475 // module
476 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200477 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700478 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800479 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
480 if (availablePrimaryOutputDevices().contains(devDesc) &&
481 (module != 0 && module->getHandle() == primaryHandle)) {
482 reply = mpClientInterface->getParameters(
483 AUDIO_IO_HANDLE_NONE,
484 String8(AudioParameter::keyReconfigA2dpSupported));
485 AudioParameter repliedParameters(reply);
486 repliedParameters.getInt(
487 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
488 if (isReconfigA2dpSupported) {
489 const String8 key(AudioParameter::keyReconfigA2dp);
490 param.add(key, String8("true"));
491 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
492 devDesc->setEncodedFormat(encodedFormat);
493 return NO_ERROR;
494 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700495 }
496 }
cnx421bd2dcc42020-07-11 14:58:44 +0800497 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
498 for (size_t i = 0; i < mOutputs.size(); i++) {
499 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
500 // mute media strategies and delay device switch by the largest
501 // This avoid sending the music tail into the earpiece or headset.
502 setStrategyMute(musicStrategy, true, desc);
503 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
504 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
505 nullptr, true /*fromCache*/).types());
506 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507 // Toggle the device state: UNAVAILABLE -> AVAILABLE
508 // This will force reading again the device configuration
509 status = setDeviceConnectionState(device,
510 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 device_address, device_name,
512 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513 if (status != NO_ERROR) {
514 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
515 status);
516 return status;
517 }
518
519 status = setDeviceConnectionState(device,
520 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522 if (status != NO_ERROR) {
523 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
524 status);
525 return status;
526 }
527
528 return NO_ERROR;
529}
530
Pattye4981552021-11-04 21:01:03 +0800531status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
532 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800533{
Pattye4981552021-11-04 21:01:03 +0800534 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800535 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800536 std::unordered_set<audio_format_t> formatSet;
537 sp<HwModule> primaryModule =
538 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700539 if (primaryModule == nullptr) {
540 ALOGE("%s() unable to get primary module", __func__);
541 return NO_INIT;
542 }
Pattye4981552021-11-04 21:01:03 +0800543
544 DeviceTypeSet audioDeviceSet;
545
546 switch(device) {
547 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
548 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
549 break;
550 case AUDIO_DEVICE_OUT_BLE_HEADSET:
551 audioDeviceSet = getAudioDeviceOutAllBleSet();
552 break;
553 default:
554 ALOGE("%s() device type 0x%08x not supported", __func__, device);
555 return BAD_VALUE;
556 }
557
jiabin9a3361e2019-10-01 09:38:30 -0700558 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattye4981552021-11-04 21:01:03 +0800559 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800560 for (const auto& device : declaredDevices) {
561 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800562 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800563 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800564 return status;
565}
566
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100567DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
568{
569 DeviceVector rxSinkdevices{};
570 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
571 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
572 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
573 auto rxSinkDevice = rxSinkdevices.itemAt(0);
574 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
575 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
576 // retrieve Rx Source device descriptor
577 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
578 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
579
580 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
581 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
582 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
583 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
584 return DeviceVector(rxSinkDevice);
585 }
586 }
587 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
588 // the device returned is not necessarily reachable via this output
589 // (filter later by setOutputDevices())
590 return getNewOutputDevices(mPrimaryOutput, fromCache);
591}
592
593status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
594{
595 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
596 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
597 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
598 }
599 return INVALID_OPERATION;
600}
601
602status_t AudioPolicyManager::updateCallRoutingInternal(
603 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604{
605 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100606 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700607 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700608 if(!hasPrimaryOutput() ||
609 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100610 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700611 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100612 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100613
Francois Gaffie716e1432019-01-14 16:58:59 +0100614 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100615 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100616 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100617
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100618 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100619 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700620
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200621 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 // release TX patch if any
623 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100624 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700625 mCallTxPatch.clear();
626 }
627
François Gaffie9eb18552018-11-05 10:33:26 +0100628 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700629 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100630 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700631 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100632 // retrieve Rx Source and Tx Sink device descriptors
633 sp<DeviceDescriptor> rxSourceDevice =
634 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
635 String8(),
636 AUDIO_FORMAT_DEFAULT);
637 sp<DeviceDescriptor> txSinkDevice =
638 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
639 String8(),
640 AUDIO_FORMAT_DEFAULT);
641
642 // RX and TX Telephony device are declared by Primary Audio HAL
643 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
644 (telephonyRxModule->getHalVersionMajor() >= 3)) {
645 if (rxSourceDevice == 0 || txSinkDevice == 0) {
646 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100647 ALOGE("%s() no telephony Tx and/or RX device", __func__);
648 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100649 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100650 // createAudioPatchInternal now supports both HW / SW bridging
651 createRxPatch = true;
652 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100653 } else {
654 // If the RX device is on the primary HW module, then use legacy routing method for
655 // voice calls via setOutputDevice() on primary output.
656 // Otherwise, create two audio patches for TX and RX path.
657 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
658 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700659 // If the TX device is also on the primary HW module, setOutputDevice() will take care
660 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100661 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
662 (txSinkDevice != 0);
663 }
664 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
665 // Otherwise, create two audio patches for TX and RX path.
666 if (!createRxPatch) {
667 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700668 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200669 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800670 // If the TX device is on the primary HW module but RX device is
671 // on other HW module, SinkMetaData of telephony input should handle it
672 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700674 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100675 // terminate active capture if on the same HW module as the call TX source device
676 // FIXME: would be better to refine to only inputs whose profile connects to the
677 // call TX device but this information is not in the audio patch and logic here must be
678 // symmetric to the one in startInput()
679 for (const auto& activeDesc : mInputs.getActiveInputs()) {
680 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
681 closeActiveClients(activeDesc);
682 }
683 }
François Gaffie9eb18552018-11-05 10:33:26 +0100684 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800685 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100686 if (waitMs != nullptr) {
687 *waitMs = muteWaitMs;
688 }
689 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800690}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800692sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100693 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700694 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695
François Gaffie11d30102018-11-02 16:09:09 +0100696 if (device == nullptr) {
697 return nullptr;
698 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100699
700 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800701 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100702 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800703 addSource(mAvailableInputDevices.getDevice(
704 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800705 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100706 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800707 addSink(mAvailableOutputDevices.getDevice(
708 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800709 }
710
François Gaffieafd4cea2019-11-18 15:50:22 +0100711 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
712 status_t status =
713 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
714 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
715 if (status != NO_ERROR || index < 0) {
716 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
717 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800720}
721
Mikhail Naganov100f0122018-11-29 11:22:16 -0800722bool AudioPolicyManager::isDeviceOfModule(
723 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
724 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
725 if (module != 0) {
726 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
727 .indexOf(devDesc) != NAME_NOT_FOUND
728 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
729 .indexOf(devDesc) != NAME_NOT_FOUND;
730 }
731 return false;
732}
733
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200734void AudioPolicyManager::connectTelephonyRxAudioSource()
735{
736 disconnectTelephonyRxAudioSource();
737 const struct audio_port_config source = {
738 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
739 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
740 };
741 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
742 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
743 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
744}
745
746void AudioPolicyManager::disconnectTelephonyRxAudioSource()
747{
748 stopAudioSource(mCallRxSourceClientPort);
749 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
750}
751
Eric Laurente0720872014-03-11 09:30:41 -0700752void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700753{
754 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100755 // store previous phone state for management of sonification strategy below
756 int oldState = mEngine->getPhoneState();
757
758 if (mEngine->setPhoneState(state) != NO_ERROR) {
759 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700760 return;
761 }
François Gaffie2110e042015-03-24 08:41:51 +0100762 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700763 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700764 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700765 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800766 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700767 }
768
François Gaffie2110e042015-03-24 08:41:51 +0100769 /**
770 * Switching to or from incall state or switching between telephony and VoIP lead to force
771 * routing command.
772 */
Eric Laurent74b71512019-11-06 17:21:57 -0800773 bool force = ((isStateInCall(oldState) != isStateInCall(state))
774 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700775
776 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700777 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700778
Eric Laurente552edb2014-03-10 17:42:56 -0700779 int delayMs = 0;
780 if (isStateInCall(state)) {
781 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100782 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
783 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700784 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700785 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700786 // mute media and sonification strategies and delay device switch by the largest
787 // latency of any output where either strategy is active.
788 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100789 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
790 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
791 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700792 (delayMs < (int)desc->latency()*2)) {
793 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700794 }
François Gaffiec005e562018-11-06 15:04:49 +0100795 setStrategyMute(musicStrategy, true, desc);
796 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
797 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
798 nullptr, true /*fromCache*/).types());
799 setStrategyMute(sonificationStrategy, true, desc);
800 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
801 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
802 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700803 }
804 }
805
Eric Laurent87ffa392015-05-22 10:32:38 -0700806 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700807 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100808 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700809 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100810 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
811 // force routing command to audio hardware when ending call
812 // even if no device change is needed
813 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
814 rxDevices = mPrimaryOutput->devices();
815 }
816 if (oldState == AUDIO_MODE_IN_CALL) {
817 disconnectTelephonyRxAudioSource();
818 if (mCallTxPatch != 0) {
819 releaseAudioPatchInternal(mCallTxPatch->getHandle());
820 mCallTxPatch.clear();
821 }
822 }
François Gaffie11d30102018-11-02 16:09:09 +0100823 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700824 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700825 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700826
827 // reevaluate routing on all outputs in case tracks have been started during the call
828 for (size_t i = 0; i < mOutputs.size(); i++) {
829 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100830 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700831 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100832 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700833 }
834 }
835
Eric Laurente552edb2014-03-10 17:42:56 -0700836 if (isStateInCall(state)) {
837 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700838 // force reevaluating accessibility routing when call starts
839 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 }
841
842 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100843 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
844 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700845}
846
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700847audio_mode_t AudioPolicyManager::getPhoneState() {
848 return mEngine->getPhoneState();
849}
850
Eric Laurente0720872014-03-11 09:30:41 -0700851void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100852 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700853{
François Gaffie2110e042015-03-24 08:41:51 +0100854 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700855 if (config == mEngine->getForceUse(usage)) {
856 return;
857 }
Eric Laurente552edb2014-03-10 17:42:56 -0700858
François Gaffie2110e042015-03-24 08:41:51 +0100859 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
860 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
861 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700862 }
François Gaffie2110e042015-03-24 08:41:51 +0100863 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
864 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
865 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700866
867 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700868 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800869
Eric Laurent22fcda22019-05-17 16:28:47 -0700870 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
871 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
872 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
873 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
874 }
875
Eric Laurentdc462862016-07-19 12:29:53 -0700876 //FIXME: workaround for truncated touch sounds
877 // to be removed when the problem is handled by system UI
878 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700879 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
880 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
881 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700882
883 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100884 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700885}
886
Eric Laurente0720872014-03-11 09:30:41 -0700887void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700888{
889 ALOGV("setSystemProperty() property %s, value %s", property, value);
890}
891
Michael Chana94fbb22018-04-24 14:31:19 +1000892// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
893// search to profiles for direct outputs.
894sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100895 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000896 uint32_t samplingRate,
897 audio_format_t format,
898 audio_channel_mask_t channelMask,
899 audio_output_flags_t flags,
900 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700901{
Michael Chana94fbb22018-04-24 14:31:19 +1000902 if (directOnly) {
903 // only retain flags that will drive the direct output profile selection
904 // if explicitly requested
905 static const uint32_t kRelevantFlags =
906 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700907 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000908 flags =
909 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
910 }
Eric Laurent861a6282015-05-18 15:40:16 -0700911
912 sp<IOProfile> profile;
913
Mikhail Naganovd4120142017-12-06 15:49:22 -0800914 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800915 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100916 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700917 samplingRate, NULL /*updatedSamplingRate*/,
918 format, NULL /*updatedFormat*/,
919 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700920 flags)) {
921 continue;
922 }
923 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100924 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700925 continue;
926 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800927 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700928 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800929 continue;
930 }
Michael Chana94fbb22018-04-24 14:31:19 +1000931 if (!directOnly) return curProfile;
932 // when searching for direct outputs, if several profiles are compatible, give priority
933 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100934 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700935 continue;
936 }
937 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100938 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700939 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700940 }
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942 }
Eric Laurent861a6282015-05-18 15:40:16 -0700943 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700944}
945
Eric Laurentfa0f6742021-08-17 18:39:44 +0200946sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200947 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200948{
949 for (const auto& hwModule : mHwModules) {
950 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200951 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200952 continue;
953 }
954 // reject profiles not corresponding to a device currently available
955 DeviceVector supportedDevices = curProfile->getSupportedDevices();
956 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
957 continue;
958 }
959 if (!devices.empty()) {
960 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
961 != devices.size()) {
962 continue;
963 }
964 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200965 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
966 return curProfile;
967 }
968 }
969 return nullptr;
970}
971
Eric Laurentf4e63452017-11-06 19:31:46 +0000972audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700973{
François Gaffiec005e562018-11-06 15:04:49 +0100974 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800975
976 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
977 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
978 // format, flags, etc. This may result in some discrepancy for functions that utilize
979 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
980 // and AudioSystem::getOutputSamplingRate().
981
François Gaffie11d30102018-11-02 16:09:09 +0100982 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700983 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700984
François Gaffie11d30102018-11-02 16:09:09 +0100985 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
986 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000987 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700988}
989
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700990status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
991 const audio_attributes_t *srcAttr,
992 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700993{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700994 if (srcAttr != NULL) {
995 if (!isValidAttributes(srcAttr)) {
996 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
997 __func__,
998 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
999 srcAttr->tags);
1000 return BAD_VALUE;
1001 }
1002 *dstAttr = *srcAttr;
1003 } else {
1004 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1005 ALOGE("%s: invalid stream type", __func__);
1006 return BAD_VALUE;
1007 }
François Gaffiec005e562018-11-06 15:04:49 +01001008 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001009 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001010
1011 // Only honor audibility enforced when required. The client will be
1012 // forced to reconnect if the forced usage changes.
1013 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001014 dstAttr->flags = static_cast<audio_flags_mask_t>(
1015 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001016 }
1017
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001018 return NO_ERROR;
1019}
1020
Kevin Rocard153f92d2018-12-18 18:33:28 -08001021status_t AudioPolicyManager::getOutputForAttrInt(
1022 audio_attributes_t *resultAttr,
1023 audio_io_handle_t *output,
1024 audio_session_t session,
1025 const audio_attributes_t *attr,
1026 audio_stream_type_t *stream,
1027 uid_t uid,
1028 const audio_config_t *config,
1029 audio_output_flags_t *flags,
1030 audio_port_handle_t *selectedDeviceId,
1031 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001032 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001033 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001034{
François Gaffiec005e562018-11-06 15:04:49 +01001035 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001036 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001037 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001038 const sp<DeviceDescriptor> requestedDevice =
1039 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1040
Eric Laurent8a1095a2019-11-08 14:44:16 -08001041 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001042 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1043 if (status != NO_ERROR) {
1044 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001045 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001046 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001047 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001048 }
François Gaffiec005e562018-11-06 15:04:49 +01001049 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001050
François Gaffiec005e562018-11-06 15:04:49 +01001051 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1052 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001053
Kevin Rocard153f92d2018-12-18 18:33:28 -08001054 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1055 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1056 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001057 sp<AudioPolicyMix> primaryMix;
1058 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001059 if (status != OK) {
1060 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001061 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001062
Kevin Rocard153f92d2018-12-18 18:33:28 -08001063 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001064 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001065
1066 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001067 if ((usePrimaryOutputFromPolicyMixes
1068 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001069 && !audio_is_linear_pcm(config->format)) {
1070 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001071 return BAD_VALUE;
1072 }
1073 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001074 sp<DeviceDescriptor> deviceDesc =
1075 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1076 primaryMix->mDeviceAddress,
1077 AUDIO_FORMAT_DEFAULT);
1078 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001079 if (deviceDesc != nullptr
1080 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001081 audio_io_handle_t newOutput;
1082 status = openDirectOutput(
1083 *stream, session, config,
1084 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1085 DeviceVector(deviceDesc), &newOutput);
1086 if (status != NO_ERROR) {
1087 policyDesc = nullptr;
1088 } else {
1089 policyDesc = mOutputs.valueFor(newOutput);
1090 primaryMix->setOutput(policyDesc);
1091 }
1092 }
1093 if (policyDesc != nullptr) {
1094 policyDesc->mPolicyMix = primaryMix;
1095 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001096 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001097
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001098 ALOGV("getOutputForAttr() returns output %d", *output);
1099 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1100 *outputType = API_OUT_MIX_PLAYBACK;
1101 } else {
1102 *outputType = API_OUTPUT_LEGACY;
1103 }
1104 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001105 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001106 }
François Gaffiec005e562018-11-06 15:04:49 +01001107 // Virtual sources must always be dynamicaly or explicitly routed
1108 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1109 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1110 return BAD_VALUE;
1111 }
1112 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1113 // in order to let the choice of the order to future vendor engine
1114 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001115
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001116 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001117 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001118 }
1119
Nadav Barb2f18162018-07-18 13:01:53 +03001120 // Set incall music only if device was explicitly set, and fallback to the device which is
1121 // chosen by the engine if not.
1122 // FIXME: provide a more generic approach which is not device specific and move this back
1123 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001124 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001125 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001126 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001127 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001128 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001129 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001130 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001131 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001132 }
1133 }
1134
François Gaffiec005e562018-11-06 15:04:49 +01001135 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1136 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1137 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001138
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001139 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001140 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001141 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001142 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001143 ALOGV("%s() Using MSD devices %s instead of devices %s",
1144 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001145 } else {
1146 *output = AUDIO_IO_HANDLE_NONE;
1147 }
1148 }
1149 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001150 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001151 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001152 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001153 if (*output == AUDIO_IO_HANDLE_NONE) {
1154 return INVALID_OPERATION;
1155 }
Paul McLeanaa981192015-03-21 09:55:15 -07001156
François Gaffiec005e562018-11-06 15:04:49 +01001157 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001158 for (auto &outputDevice : outputDevices) {
1159 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1160 *selectedDeviceId = outputDevice->getId();
1161 break;
1162 }
1163 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001164
Eric Laurent8a1095a2019-11-08 14:44:16 -08001165 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1166 *outputType = API_OUTPUT_TELEPHONY_TX;
1167 } else {
1168 *outputType = API_OUTPUT_LEGACY;
1169 }
1170
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001171 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1172
1173 return NO_ERROR;
1174}
1175
1176status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1177 audio_io_handle_t *output,
1178 audio_session_t session,
1179 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001180 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001181 const audio_config_t *config,
1182 audio_output_flags_t *flags,
1183 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001185 std::vector<audio_io_handle_t> *secondaryOutputs,
1186 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001187{
1188 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1189 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1190 return INVALID_OPERATION;
1191 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001192 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001193 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001194 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001196 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001197 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001198 const sp<DeviceDescriptor> requestedDevice =
1199 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1200
1201 // Prevent from storing invalid requested device id in clients
1202 const audio_port_handle_t sanitizedRequestedPortId =
1203 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1204 *selectedDeviceId = sanitizedRequestedPortId;
1205
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001206 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001207 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001209 if (status != NO_ERROR) {
1210 return status;
1211 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001212 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 if (secondaryOutputs != nullptr) {
1214 for (auto &secondaryMix : secondaryMixes) {
1215 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1216 if (outputDesc != nullptr &&
1217 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1218 secondaryOutputs->push_back(outputDesc->mIoHandle);
1219 weakSecondaryOutputDescs.push_back(outputDesc);
1220 }
1221 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001222 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223
Eric Laurent8fc147b2018-07-22 19:13:55 -07001224 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001225 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001226 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001227 };
jiabin4ef93452019-09-10 14:29:54 -07001228 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001229
Eric Laurentc209fe42020-06-05 18:11:23 -07001230 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001231 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001233 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001234 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001235 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001236 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001237 std::move(weakSecondaryOutputDescs),
1238 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001239 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001240
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001241 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1242 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001243
Eric Laurente83b55d2014-11-14 10:06:21 -08001244 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001245}
1246
Eric Laurentc529cf62020-04-17 18:19:10 -07001247status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1248 audio_session_t session,
1249 const audio_config_t *config,
1250 audio_output_flags_t flags,
1251 const DeviceVector &devices,
1252 audio_io_handle_t *output) {
1253
1254 *output = AUDIO_IO_HANDLE_NONE;
1255
1256 // skip direct output selection if the request can obviously be attached to a mixed output
1257 // and not explicitly requested
1258 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1259 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1260 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1261 return NAME_NOT_FOUND;
1262 }
1263
1264 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1265 // This prevents creating an offloaded track and tearing it down immediately after start
1266 // when audioflinger detects there is an active non offloadable effect.
1267 // FIXME: We should check the audio session here but we do not have it in this context.
1268 // This may prevent offloading in rare situations where effects are left active by apps
1269 // in the background.
1270 sp<IOProfile> profile;
1271 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1272 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1273 profile = getProfileForOutput(
1274 devices, config->sample_rate, config->format, config->channel_mask,
1275 flags, true /* directOnly */);
1276 }
1277
1278 if (profile == nullptr) {
1279 return NAME_NOT_FOUND;
1280 }
1281
1282 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1283 for (size_t i = 0; i < mOutputs.size(); i++) {
1284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1285 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1286 // reuse direct output if currently open by the same client
1287 // and configured with same parameters
1288 if ((config->sample_rate == desc->getSamplingRate()) &&
1289 (config->format == desc->getFormat()) &&
1290 (config->channel_mask == desc->getChannelMask()) &&
1291 (session == desc->mDirectClientSession)) {
1292 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001293 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001294 mOutputs.keyAt(i), session);
1295 *output = mOutputs.keyAt(i);
1296 return NO_ERROR;
1297 }
1298 }
1299 }
1300
1301 if (!profile->canOpenNewIo()) {
1302 return NAME_NOT_FOUND;
1303 }
1304
1305 sp<SwAudioOutputDescriptor> outputDesc =
1306 new SwAudioOutputDescriptor(profile, mpClientInterface);
1307
Michael Chan6fb34492020-12-08 15:44:49 +11001308 // An MSD patch may be using the only output stream that can service this request. Release
1309 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001310 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001311
Eric Laurentf1f22e72021-07-13 14:04:14 +02001312 status_t status =
1313 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001314
1315 // only accept an output with the requested parameters
1316 if (status != NO_ERROR ||
1317 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1318 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1319 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1320 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1321 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1322 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1323 config->channel_mask, outputDesc->getChannelMask());
1324 if (*output != AUDIO_IO_HANDLE_NONE) {
1325 outputDesc->close();
1326 }
1327 // fall back to mixer output if possible when the direct output could not be open
1328 if (audio_is_linear_pcm(config->format) &&
1329 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1330 return NAME_NOT_FOUND;
1331 }
1332 *output = AUDIO_IO_HANDLE_NONE;
1333 return BAD_VALUE;
1334 }
1335 outputDesc->mDirectOpenCount = 1;
1336 outputDesc->mDirectClientSession = session;
1337
1338 addOutput(*output, outputDesc);
1339 mPreviousOutputs = mOutputs;
1340 ALOGV("%s returns new direct output %d", __func__, *output);
1341 mpClientInterface->onAudioPortListUpdate();
1342 return NO_ERROR;
1343}
1344
François Gaffie11d30102018-11-02 16:09:09 +01001345audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1346 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001347 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001348 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001349 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001350 audio_output_flags_t *flags,
1351 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001352{
Andy Hungc88b0642018-04-27 15:42:35 -07001353 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001354
jiabine375d412019-02-26 12:54:53 -08001355 // Discard haptic channel mask when forcing muting haptic channels.
1356 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001357 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1358 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001359
Eric Laurente552edb2014-03-10 17:42:56 -07001360 // open a direct output if required by specified parameters
1361 //force direct flag if offload flag is set: offloading implies a direct output stream
1362 // and all common behaviors are driven by checking only the direct flag
1363 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001364 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1365 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001366 }
Nadav Bar766fb022018-01-07 12:18:03 +02001367 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1368 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001369 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001370
1371 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1372
Eric Laurente83b55d2014-11-14 10:06:21 -08001373 // only allow deep buffering for music stream type
1374 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001375 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001376 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001377 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001378 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1379 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001380 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001381 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001382 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001383 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001384 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001385 audio_is_linear_pcm(config->format) &&
1386 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001387 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001388 AUDIO_OUTPUT_FLAG_DIRECT);
1389 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001390 }
Eric Laurente552edb2014-03-10 17:42:56 -07001391
Eric Laurentfa0f6742021-08-17 18:39:44 +02001392 if (mSpatializerOutput != nullptr
1393 && canBeSpatialized(attr, config, devices.toTypeAddrVector())) {
1394 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001395 }
1396
Eric Laurentc529cf62020-04-17 18:19:10 -07001397 audio_config_t directConfig = *config;
1398 directConfig.channel_mask = channelMask;
1399 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1400 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001401 return output;
1402 }
1403
Eric Laurent14cbfca2016-03-17 09:42:16 -07001404 // A request for HW A/V sync cannot fallback to a mixed output because time
1405 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001406 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001407 return AUDIO_IO_HANDLE_NONE;
1408 }
1409
Eric Laurente552edb2014-03-10 17:42:56 -07001410 // ignoring channel mask due to downmix capability in mixer
1411
1412 // open a non direct output
1413
1414 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001415 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001416 // get which output is suitable for the specified stream. The actual
1417 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001418 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001419
Eric Laurent8838a382014-09-08 16:44:28 -07001420 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001421 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001422 output = selectOutput(
1423 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001424 }
François Gaffie11d30102018-11-02 16:09:09 +01001425 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001426 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001427 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001428
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return output;
1430}
1431
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001432sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001433 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1434 mAvailableInputDevices);
1435 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1436}
1437
1438DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1439 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1440 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441}
1442
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001443const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001444 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001445 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1446 if (msdModule != 0) {
1447 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1448 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1449 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1450 const struct audio_port_config *source = &patch->mPatch.sources[j];
1451 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1452 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001453 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001454 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001455 }
1456 }
1457 }
1458 return msdPatches;
1459}
1460
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001461status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1462 const InputProfileCollection &inputProfiles,
1463 const OutputProfileCollection &outputProfiles,
1464 const sp<DeviceDescriptor> &sourceDevice,
1465 const sp<DeviceDescriptor> &sinkDevice,
1466 AudioProfileVector& sourceProfiles,
1467 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001468 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001469 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001470 return NO_INIT;
1471 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001472 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001473 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001474 return NO_INIT;
1475 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001476 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001477 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1478 inProfile->supportsDevice(sourceDevice)) {
1479 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001480 }
1481 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001482 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001483 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001484 outProfile->supportsDevice(sinkDevice)) {
1485 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001486 }
1487 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001488 return NO_ERROR;
1489}
1490
1491status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1492 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1493 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1494{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001495 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001496 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1497 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1498 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001499 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001500 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1501 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001502 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001503 }
1504 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1505 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1506 sinkConfig->format = bestSinkConfig.format;
1507 // For encoded streams force direct flag to prevent downstream mixing.
1508 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1509 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001510 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1511 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001512 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001513 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1514 // raw and IEC61937 framed streams.
1515 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1516 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1517 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001518 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1519 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1520 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1521 sourceConfig->format = bestSinkConfig.format;
1522 // Copy input stream directly without any processing (e.g. resampling).
1523 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1524 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1525 if (hwAvSync) {
1526 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1527 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1528 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1529 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1530 }
1531 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1532 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1533 sinkConfig->config_mask |= config_mask;
1534 sourceConfig->config_mask |= config_mask;
1535 return NO_ERROR;
1536}
1537
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001538PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1539 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001540{
1541 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1543 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1544 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1545 if (deviceModule == nullptr) {
1546 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1547 return patchBuilder;
1548 }
1549 const InputProfileCollection inputProfiles = msdIsSource ?
1550 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1551 const OutputProfileCollection outputProfiles = msdIsSource ?
1552 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1553
1554 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1555 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1556 device : getMsdAudioOutDevices().itemAt(0);
1557 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1558
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001559 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1560 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001561 AudioProfileVector sourceProfiles;
1562 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001563 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1564 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001565 for (auto hwAvSync : { true, false }) {
1566 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1567 sourceProfiles, sinkProfiles) != NO_ERROR) {
1568 continue;
1569 }
1570 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1571 &sinkConfig) == NO_ERROR) {
1572 // Found a matching config. Re-create PatchBuilder with this config.
1573 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1574 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001575 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001576 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001577 " supporting PCM format conversion.", __func__);
1578 return patchBuilder;
1579}
1580
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001581status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001582 DeviceVector devices;
1583 if (outputDevices != nullptr && outputDevices->size() > 0) {
1584 devices.add(*outputDevices);
1585 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001586 // Use media strategy for unspecified output device. This should only
1587 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1588 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001589 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001590 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001591 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001592 }
Michael Chan6fb34492020-12-08 15:44:49 +11001593 std::vector<PatchBuilder> patchesToCreate;
1594 for (auto i = 0u; i < devices.size(); ++i) {
1595 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001596 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001597 }
1598 // Retain only the MSD patches associated with outputDevices request.
1599 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001600 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001601 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1602 auto retainedPatch = false;
1603 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1604 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1605 patchesToRemove.removeItemsAt(i);
1606 retainedPatch = true;
1607 break;
1608 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001609 }
Michael Chan6fb34492020-12-08 15:44:49 +11001610 if (retainedPatch) {
1611 it = patchesToCreate.erase(it);
1612 continue;
1613 }
1614 ++it;
1615 }
1616 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1617 return NO_ERROR;
1618 }
1619 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1620 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001621 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 }
Michael Chan6fb34492020-12-08 15:44:49 +11001623 status_t status = NO_ERROR;
1624 for (const auto &p : patchesToCreate) {
1625 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1626 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1627 char message[256];
1628 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1629 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1630 currStatus == NO_ERROR ? "Success" : "Error",
1631 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1632 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1633 if (currStatus == NO_ERROR) {
1634 ALOGD("%s", message);
1635 } else {
1636 ALOGE("%s", message);
1637 if (status == NO_ERROR) {
1638 status = currStatus;
1639 }
1640 }
1641 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 return status;
1643}
1644
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1646 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001647 for (size_t i = 0; i < msdPatches.size(); i++) {
1648 const auto& patch = msdPatches[i];
1649 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1650 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1651 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1652 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1653 releaseAudioPatch(patch->getHandle(), mUidCached);
1654 break;
1655 }
1656 }
1657 }
1658}
1659
Eric Laurente0720872014-03-11 09:30:41 -07001660audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001661 audio_output_flags_t flags,
1662 audio_format_t format,
1663 audio_channel_mask_t channelMask,
1664 uint32_t samplingRate,
1665 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001666{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001667 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1668 "%s called with format %#x", __func__, format);
1669
jiabinebb6af42020-06-09 17:31:17 -07001670 // Return the output that haptic-generating attached to when 1) session id is specified,
1671 // 2) haptic-generating effect exists for given session id and 3) the output that
1672 // haptic-generating effect attached to is in given outputs.
1673 if (sessionId != AUDIO_SESSION_NONE) {
1674 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1675 sessionId, FX_IID_HAPTICGENERATOR);
1676 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1677 return hapticGeneratingOutput;
1678 }
1679 }
1680
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 // Flags disqualifying an output: the match must happen before calling selectOutput()
1682 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1683 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1684
1685 // Flags expressing a functional request: must be honored in priority over
1686 // other criteria
1687 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1688 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1689 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1690 // Flags expressing a performance request: have lower priority than serving
1691 // requested sampling rate or channel mask
1692 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1693 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1694 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1695
1696 const audio_output_flags_t functionalFlags =
1697 (audio_output_flags_t)(flags & kFunctionalFlags);
1698 const audio_output_flags_t performanceFlags =
1699 (audio_output_flags_t)(flags & kPerformanceFlags);
1700
1701 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001704 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001705 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001706 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 // 2: the output with the highest number of requested functional flags
1708 // 3: the output supporting the exact channel mask
1709 // 4: the output with a higher channel count than requested
1710 // 5: the output with a higher sampling rate than requested
1711 // 6: the output with the highest number of requested performance flags
1712 // 7: the output with the bit depth the closest to the requested one
1713 // 8: the primary output
1714 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 // matching criteria values in priority order for best matching output so far
1717 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001718
Eric Laurent16c66dd2019-05-01 17:54:10 -07001719 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1720 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1721 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001722
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001723 for (audio_io_handle_t output : outputs) {
1724 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001725 // matching criteria values in priority order for current output
1726 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001727
Eric Laurent16c66dd2019-05-01 17:54:10 -07001728 if (outputDesc->isDuplicated()) {
1729 continue;
1730 }
1731 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1732 continue;
1733 }
Eric Laurent8838a382014-09-08 16:44:28 -07001734
Eric Laurent16c66dd2019-05-01 17:54:10 -07001735 // If haptic channel is specified, use the haptic output if present.
1736 // When using haptic output, same audio format and sample rate are required.
1737 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001738 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001739 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1740 continue;
1741 }
1742 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001743 && format == outputDesc->getFormat()
1744 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001745 currentMatchCriteria[0] = outputHapticChannelCount;
1746 }
1747
1748 // functional flags match
1749 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1750
1751 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001752 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1753 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001754 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1755 channelCount <= outputChannelCount) {
1756 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001757 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1758 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001759 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001760 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001761 currentMatchCriteria[3] = outputChannelCount;
1762 }
1763
1764 // sampling rate match
1765 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001766 samplingRate <= outputDesc->getSamplingRate()) {
1767 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001768 }
1769
1770 // performance flags match
1771 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1772
1773 // format match
1774 if (format != AUDIO_FORMAT_INVALID) {
1775 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001776 PolicyAudioPort::kFormatDistanceMax -
1777 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001778 }
1779
1780 // primary output match
1781 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1782
1783 // compare match criteria by priority then value
1784 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1785 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1786 bestMatchCriteria = currentMatchCriteria;
1787 bestOutput = output;
1788
1789 std::stringstream result;
1790 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1791 std::ostream_iterator<int>(result, " "));
1792 ALOGV("%s new bestOutput %d criteria %s",
1793 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001794 }
1795 }
1796
Eric Laurent16c66dd2019-05-01 17:54:10 -07001797 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001798}
1799
Eric Laurent8fc147b2018-07-22 19:13:55 -07001800status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001801{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001802 ALOGV("%s portId %d", __FUNCTION__, portId);
1803
1804 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1805 if (outputDesc == 0) {
1806 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001807 return BAD_VALUE;
1808 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001809 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001810
Eric Laurent8fc147b2018-07-22 19:13:55 -07001811 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001812 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001813
Eric Laurent733ce942017-12-07 12:18:25 -08001814 status_t status = outputDesc->start();
1815 if (status != NO_ERROR) {
1816 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001817 }
1818
Eric Laurent97ac8712018-07-27 18:59:02 -07001819 uint32_t delayMs;
1820 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001821
1822 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001823 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001824 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001825 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001826 if (delayMs != 0) {
1827 usleep(delayMs * 1000);
1828 }
1829
1830 return status;
1831}
1832
Eric Laurent97ac8712018-07-27 18:59:02 -07001833status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1834 const sp<TrackClientDescriptor>& client,
1835 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001836{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001837 // cannot start playback of STREAM_TTS if any other output is being used
1838 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001839
1840 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001841 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001842 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001843 auto clientStrategy = client->strategy();
1844 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001845 if (stream == AUDIO_STREAM_TTS) {
1846 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001847 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001848 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001849 return INVALID_OPERATION;
1850 } else {
1851 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1852 }
1853 } else {
1854 // some playback other than beacon starts
1855 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1856 }
1857
Eric Laurent77305a62016-07-25 16:39:22 -07001858 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001859 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001860 bool force = !outputDesc->isActive() &&
1861 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001862
François Gaffie11d30102018-11-02 16:09:09 +01001863 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001864 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001865 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001866 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001867 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001868 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001869 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001870 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001871 } else {
1872 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001873 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001874 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1875 AUDIO_FORMAT_DEFAULT);
1876 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1877 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001878 }
1879
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001880 // requiresMuteCheck is false when we can bypass mute strategy.
1881 // It covers a common case when there is no materially active audio
1882 // and muting would result in unnecessary delay and dropped audio.
1883 const uint32_t outputLatencyMs = outputDesc->latency();
1884 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1885
Eric Laurente552edb2014-03-10 17:42:56 -07001886 // increment usage count for this stream on the requested output:
1887 // NOTE that the usage count is the same for duplicated output and hardware output which is
1888 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001889 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001890
1891 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001892 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1893 client->isPreferredDeviceForExclusiveUse()) {
1894 // Preferred device may be exclusive, use only if no other active clients on this output
1895 devices = DeviceVector(
1896 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1897 } else {
1898 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1899 }
François Gaffie11d30102018-11-02 16:09:09 +01001900 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001901 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001902 }
1903 }
Eric Laurente552edb2014-03-10 17:42:56 -07001904
François Gaffiec005e562018-11-06 15:04:49 +01001905 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001906 selectOutputForMusicEffects();
1907 }
1908
François Gaffie1c878552018-11-22 16:53:21 +01001909 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001910 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001911 if (devices.isEmpty()) {
1912 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001913 }
François Gaffiec005e562018-11-06 15:04:49 +01001914 bool shouldWait =
1915 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1916 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1917 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001918 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001919 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001920 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001921 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001922 // An output has a shared device if
1923 // - managed by the same hw module
1924 // - supports the currently selected device
1925 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001926 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001927
Eric Laurent77305a62016-07-25 16:39:22 -07001928 // force a device change if any other output is:
1929 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001930 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001931 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001932 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001933 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001934 // change the device currently selected by the other output.
1935 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001936 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001937 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001938 force = true;
1939 }
1940 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001941 // a notification so that audio focus effect can propagate, or that a mute/unmute
1942 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001943 const uint32_t latencyMs = desc->latency();
1944 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1945
1946 if (shouldWait && isActive && (waitMs < latencyMs)) {
1947 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001948 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001949
1950 // Require mute check if another output is on a shared device
1951 // and currently active to have proper drain and avoid pops.
1952 // Note restoring AudioTracks onto this output needs to invoke
1953 // a volume ramp if there is no mute.
1954 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001955 }
1956 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001957
1958 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001959 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001960
Eric Laurente552edb2014-03-10 17:42:56 -07001961 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001962 auto &curves = getVolumeCurves(client->attributes());
1963 checkAndSetVolume(curves, client->volumeSource(),
1964 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001965 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001966 outputDesc->devices().types(), 0 /*delay*/,
1967 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001968
1969 // update the outputs if starting an output with a stream that can affect notification
1970 // routing
1971 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001972
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001973 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001974 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001975 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1976 }
Eric Laurentdc462862016-07-19 12:29:53 -07001977
1978 if (waitMs > muteWaitMs) {
1979 *delayMs = waitMs - muteWaitMs;
1980 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001981
1982 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1983 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1984 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1985 // change occurs after the MixerThread starts and causes a stream volume
1986 // glitch.
1987 //
1988 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001989 }
Eric Laurentdc462862016-07-19 12:29:53 -07001990
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001991 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001992 mEngine->getForceUse(
1993 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001994 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001995 }
1996
Eric Laurent97ac8712018-07-27 18:59:02 -07001997 // Automatically enable the remote submix input when output is started on a re routing mix
1998 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001999 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2000 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002001 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2002 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2003 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002004 "remote-submix",
2005 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002006 }
2007
Eric Laurente552edb2014-03-10 17:42:56 -07002008 return NO_ERROR;
2009}
2010
Eric Laurent8fc147b2018-07-22 19:13:55 -07002011status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002012{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002013 ALOGV("%s portId %d", __FUNCTION__, portId);
2014
2015 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2016 if (outputDesc == 0) {
2017 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002018 return BAD_VALUE;
2019 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002020 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurent97ac8712018-07-27 18:59:02 -07002022 ALOGV("stopOutput() output %d, stream %d, session %d",
2023 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002024
Eric Laurent97ac8712018-07-27 18:59:02 -07002025 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002026
Eric Laurent733ce942017-12-07 12:18:25 -08002027 if (status == NO_ERROR ) {
2028 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002029 }
2030 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002031}
2032
Eric Laurent97ac8712018-07-27 18:59:02 -07002033status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2034 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002035{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002036 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002037 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002038 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002039
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002040 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2041
François Gaffie1c878552018-11-22 16:53:21 +01002042 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2043 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002044 // Automatically disable the remote submix input when output is stopped on a
2045 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002046 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002047 if (isSingleDeviceType(
2048 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002049 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002050 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002051 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2052 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002053 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002054 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002055 }
2056 }
2057 bool forceDeviceUpdate = false;
2058 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002059 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002060 forceDeviceUpdate = true;
2061 }
2062
Eric Laurente552edb2014-03-10 17:42:56 -07002063 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002064 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002065
Eric Laurente552edb2014-03-10 17:42:56 -07002066 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002067 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002068 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002069 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002070
2071 // If the routing does not change, if an output is routed on a device using HwGain
2072 // (aka setAudioPortConfig) and there are still active clients following different
2073 // volume group(s), force reapply volume
2074 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2075 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2076
Eric Laurente552edb2014-03-10 17:42:56 -07002077 // delay the device switch by twice the latency because stopOutput() is executed when
2078 // the track stop() command is received and at that time the audio track buffer can
2079 // still contain data that needs to be drained. The latency only covers the audio HAL
2080 // and kernel buffers. Also the latency does not always include additional delay in the
2081 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002082 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2083 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002084
2085 // force restoring the device selection on other active outputs if it differs from the
2086 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002087 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002088 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002089 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002090 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002091 desc->isActive() &&
2092 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002093 (newDevices != desc->devices())) {
2094 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2095 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002096
François Gaffie11d30102018-11-02 16:09:09 +01002097 setOutputDevices(desc, newDevices2, force, delayMs);
2098
Eric Laurent57de36c2016-09-28 16:59:11 -07002099 // re-apply device specific volume if not done by setOutputDevice()
2100 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002101 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002102 }
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
2104 }
2105 // update the outputs if stopping one with a stream that can affect notification routing
2106 handleNotificationRoutingForStream(stream);
2107 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002108
2109 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2110 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002111 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002112 }
2113
François Gaffiec005e562018-11-06 15:04:49 +01002114 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002115 selectOutputForMusicEffects();
2116 }
Eric Laurente552edb2014-03-10 17:42:56 -07002117 return NO_ERROR;
2118 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002119 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002120 return INVALID_OPERATION;
2121 }
2122}
2123
jiabinbce0c1d2020-10-05 11:20:18 -07002124bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002125{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002126 ALOGV("%s portId %d", __FUNCTION__, portId);
2127
2128 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2129 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002130 // If an output descriptor is closed due to a device routing change,
2131 // then there are race conditions with releaseOutput from tracks
2132 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2133 // destroyed shortly thereafter.
2134 //
2135 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002136 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002137 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002138 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139
2140 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002141
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302142 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2143 if (outputDesc->isClientActive(client)) {
2144 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2145 stopOutput(portId);
2146 }
2147
Eric Laurent8fc147b2018-07-22 19:13:55 -07002148 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2149 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002150 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002151 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002152 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002153 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154 if (--outputDesc->mDirectOpenCount == 0) {
2155 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002156 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002157 }
2158 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302159
Andy Hung39efb7a2018-09-26 15:39:28 -07002160 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002161 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2162 // The output is pending reopened to query dynamic profiles and
2163 // there is no active clients
2164 closeOutput(outputDesc->mIoHandle);
2165 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2166 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2167 if (newOutputDesc == nullptr) {
2168 ALOGE("%s failed to open output", __func__);
2169 }
2170 return true;
2171 }
2172 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002173}
2174
Eric Laurentcaf7f482014-11-25 17:50:47 -08002175status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2176 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002177 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002178 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002179 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002180 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002181 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002182 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002183 input_type_t *inputType,
2184 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002185{
François Gaffiec005e562018-11-06 15:04:49 +01002186 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2187 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2188 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002189
Eric Laurentad2e7b92017-09-14 20:06:42 -07002190 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002191 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002192 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002193 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002194 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002195 sp<AudioInputDescriptor> inputDesc;
2196 sp<RecordClientDescriptor> clientDesc;
2197 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002198 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002199 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200
2201 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2202 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2203 return INVALID_OPERATION;
2204 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002205
Francois Gaffie716e1432019-01-14 16:58:59 +01002206 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2207 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002208 }
2209
Paul McLean466dc8e2015-04-17 13:15:36 -06002210 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002211 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002212 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002213
Eric Laurentad2e7b92017-09-14 20:06:42 -07002214 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2215 // possible
2216 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2217 *input != AUDIO_IO_HANDLE_NONE) {
2218 ssize_t index = mInputs.indexOfKey(*input);
2219 if (index < 0) {
2220 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2221 status = BAD_VALUE;
2222 goto error;
2223 }
2224 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 RecordClientVector clients = inputDesc->getClientsForSession(session);
2226 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002227 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2228 status = BAD_VALUE;
2229 goto error;
2230 }
2231 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2232 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002233 // corresponds to a new client and is only permitted from the same UID.
2234 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002235 if (clients.size() > 1) {
2236 for (const auto& client : clients) {
2237 // The client map is ordered by key values (portId) and portIds are allocated
2238 // incrementaly. So the first client in this list is the one opened by audio flinger
2239 // when the mmap stream is created and should be ignored as it does not correspond
2240 // to an actual client
2241 if (client == *clients.cbegin()) {
2242 continue;
2243 }
2244 if (uid != client->uid() && !client->isSilenced()) {
2245 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2246 uid, client->portId(), client->uid());
2247 status = INVALID_OPERATION;
2248 goto error;
2249 }
Eric Laurent331679c2018-04-16 17:03:16 -07002250 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002251 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002252 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002253 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002254
Eric Laurentfecbceb2021-02-09 14:46:43 +01002255 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002256 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002257 }
2258
2259 *input = AUDIO_IO_HANDLE_NONE;
2260 *inputType = API_INPUT_INVALID;
2261
Francois Gaffie716e1432019-01-14 16:58:59 +01002262 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002263
Francois Gaffie716e1432019-01-14 16:58:59 +01002264 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2265 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2266 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002267 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002268 ALOGW("%s could not find input mix for attr %s",
2269 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002270 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002271 }
jiabinc1de2df2019-05-07 14:26:40 -07002272 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2273 String8(attr->tags + strlen("addr=")),
2274 AUDIO_FORMAT_DEFAULT);
2275 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002276 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002277 __func__, attributes.source, attributes.tags);
2278 status = BAD_VALUE;
2279 goto error;
2280 }
2281
Kevin Rocard25f9b052019-02-27 15:08:54 -08002282 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2283 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2284 } else {
2285 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2286 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002287 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002288 if (explicitRoutingDevice != nullptr) {
2289 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002290 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002291 // Prevent from storing invalid requested device id in clients
2292 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002293 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002294 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2295 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 }
François Gaffie11d30102018-11-02 16:09:09 +01002297 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002298 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002299 status = BAD_VALUE;
2300 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002301 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002302 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2303 *inputType = API_INPUT_MIX_CAPTURE;
2304 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002305 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2306 // there is an external policy, but this input is attached to a mix of recorders,
2307 // meaning it receives audio injected into the framework, so the recorder doesn't
2308 // know about it and is therefore considered "legacy"
2309 *inputType = API_INPUT_LEGACY;
2310 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002311 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002312 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002313 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002314 } else {
2315 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002316 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002317
Eric Laurent599c7582015-12-07 18:05:55 -08002318 }
2319
François Gaffiec005e562018-11-06 15:04:49 +01002320 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002321 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002322 status = INVALID_OPERATION;
2323 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002324 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002325
Eric Laurent8f42ea12018-08-08 09:08:25 -07002326exit:
2327
François Gaffiec005e562018-11-06 15:04:49 +01002328 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2329 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002330
Francois Gaffie716e1432019-01-14 16:58:59 +01002331 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002332 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002333 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002334
Mikhail Naganov2996f672019-04-18 12:29:59 -07002335 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002336 requestedDeviceId, attributes.source, flags,
2337 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002338 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002339 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002340
2341 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2342 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002343
Eric Laurent599c7582015-12-07 18:05:55 -08002344 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002345
2346error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002347 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002348}
2349
2350
François Gaffie11d30102018-11-02 16:09:09 +01002351audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002352 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002353 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002354 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002355 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002356 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002357{
2358 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002359 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002360 bool isSoundTrigger = false;
2361
François Gaffiec005e562018-11-06 15:04:49 +01002362 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002363 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2364 if (index >= 0) {
2365 input = mSoundTriggerSessions.valueFor(session);
2366 isSoundTrigger = true;
2367 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2368 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2369 } else {
2370 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002371 }
François Gaffiec005e562018-11-06 15:04:49 +01002372 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002373 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002374 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002375 }
2376
Andy Hungf129b032015-04-07 13:45:50 -07002377 // find a compatible input profile (not necessarily identical in parameters)
2378 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002379 // sampling rate and flags may be updated by getInputProfile
2380 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2381 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002382 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002383 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002384 audio_input_flags_t profileFlags = flags;
2385 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002386 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002387 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002388 profileFlags);
2389 if (profile != 0) {
2390 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002391 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2392 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002393 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2394 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2395 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002396 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002397 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002398 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002399 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002400 }
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002402 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002403 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002404 if (samplingRate == 0) {
2405 samplingRate = profileSamplingRate;
2406 }
Eric Laurente552edb2014-03-10 17:42:56 -07002407
Eric Laurent322b4d22015-04-03 15:57:54 -07002408 if (profile->getModuleHandle() == 0) {
2409 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002410 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002411 }
2412
Eric Laurentec376dc2021-04-08 20:41:22 +02002413 // Reuse an already opened input if a client with the same session ID already exists
2414 // on that input
2415 for (size_t i = 0; i < mInputs.size(); i++) {
2416 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2417 if (desc->mProfile != profile) {
2418 continue;
2419 }
2420 RecordClientVector clients = desc->clientsList();
2421 for (const auto &client : clients) {
2422 if (session == client->session()) {
2423 return desc->mIoHandle;
2424 }
2425 }
2426 }
2427
Eric Laurent3974e3b2017-12-07 17:58:43 -08002428 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002429 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002430 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002431 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002432 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002433 continue;
2434 }
2435 // if sound trigger, reuse input if used by other sound trigger on same session
2436 // else
2437 // reuse input if active client app is not in IDLE state
2438 //
2439 RecordClientVector clients = desc->clientsList();
2440 bool doClose = false;
2441 for (const auto& client : clients) {
2442 if (isSoundTrigger != client->isSoundTrigger()) {
2443 continue;
2444 }
2445 if (client->isSoundTrigger()) {
2446 if (session == client->session()) {
2447 return desc->mIoHandle;
2448 }
2449 continue;
2450 }
2451 if (client->active() && client->appState() != APP_STATE_IDLE) {
2452 return desc->mIoHandle;
2453 }
2454 doClose = true;
2455 }
2456 if (doClose) {
2457 closeInput(desc->mIoHandle);
2458 } else {
2459 i++;
2460 }
2461 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002462 }
2463
Eric Laurentfe231122017-11-17 17:48:06 -08002464 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002465
Eric Laurentfe231122017-11-17 17:48:06 -08002466 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2467 lConfig.sample_rate = profileSamplingRate;
2468 lConfig.channel_mask = profileChannelMask;
2469 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002470
François Gaffie11d30102018-11-02 16:09:09 +01002471 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002472
2473 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002474 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002475 (profileSamplingRate != lConfig.sample_rate) ||
2476 !audio_formats_match(profileFormat, lConfig.format) ||
2477 (profileChannelMask != lConfig.channel_mask)) {
2478 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002479 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002480 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002481 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002482 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002483 }
Eric Laurent599c7582015-12-07 18:05:55 -08002484 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002485 }
2486
Eric Laurentc722f302014-12-10 11:21:49 -08002487 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002488
Eric Laurent599c7582015-12-07 18:05:55 -08002489 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002490 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002491
Eric Laurent599c7582015-12-07 18:05:55 -08002492 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002493}
2494
Eric Laurent4eb58f12018-12-07 16:41:02 -08002495status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002496{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002497 ALOGV("%s portId %d", __FUNCTION__, portId);
2498
2499 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2500 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002502 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002503 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002504 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002505 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002506 if (client->active()) {
2507 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2508 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002509 }
2510
Eric Laurent8f42ea12018-08-08 09:08:25 -07002511 audio_session_t session = client->session();
2512
Eric Laurent4eb58f12018-12-07 16:41:02 -08002513 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514
Eric Laurent4eb58f12018-12-07 16:41:02 -08002515 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002516
Eric Laurent4eb58f12018-12-07 16:41:02 -08002517 status_t status = inputDesc->start();
2518 if (status != NO_ERROR) {
2519 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002520 }
Eric Laurente552edb2014-03-10 17:42:56 -07002521
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002522 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002523 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002525
Eric Laurent8f42ea12018-08-08 09:08:25 -07002526 // indicate active capture to sound trigger service if starting capture from a mic on
2527 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002528 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002529 if (device != nullptr) {
2530 status = setInputDevice(input, device, true /* force */);
2531 } else {
2532 ALOGW("%s no new input device can be found for descriptor %d",
2533 __FUNCTION__, inputDesc->getId());
2534 status = BAD_VALUE;
2535 }
Eric Laurente552edb2014-03-10 17:42:56 -07002536
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002537 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002538 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002539 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002540 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002541 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2542 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002543 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002544 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002545
François Gaffie11d30102018-11-02 16:09:09 +01002546 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2547 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002548 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002549 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002550 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002551
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552 // automatically enable the remote submix output when input is started if not
2553 // used by a policy mix of type MIX_TYPE_RECORDERS
2554 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002555 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002557 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002558 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002559 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2560 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002561 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002562 if (address != "") {
2563 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2564 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002565 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002566 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002567 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002568 } else if (status != NO_ERROR) {
2569 // Restore client activity state.
2570 inputDesc->setClientActive(client, false);
2571 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002572 }
2573
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002574 ALOGV("%s input %d source = %d status = %d exit",
2575 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002576
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002577 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002578}
2579
Eric Laurent8fc147b2018-07-22 19:13:55 -07002580status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002581{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002582 ALOGV("%s portId %d", __FUNCTION__, portId);
2583
2584 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2585 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002587 return BAD_VALUE;
2588 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002589 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002590 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002591 if (!client->active()) {
2592 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002593 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002594 }
Carter Hsue6139d52021-07-08 10:30:20 +08002595 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002596 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002597
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598 inputDesc->stop();
2599 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002600 auto current_source = inputDesc->source();
2601 setInputDevice(input, getNewInputDevice(inputDesc),
2602 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002603 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002604 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002606 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002607 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2608 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002609 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002610 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002611
2612 // automatically disable the remote submix output when input is stopped if not
2613 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002614 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002615 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002616 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002617 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002618 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2619 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002620 }
2621 if (address != "") {
2622 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2623 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002624 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625 }
2626 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002627 resetInputDevice(input);
2628
2629 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2630 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002631 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2632 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002634 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002635 }
2636 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002637 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002638 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002639}
2640
Eric Laurent8fc147b2018-07-22 19:13:55 -07002641void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002642{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002643 ALOGV("%s portId %d", __FUNCTION__, portId);
2644
2645 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2646 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002648 return;
2649 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002650 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651 audio_io_handle_t input = inputDesc->mIoHandle;
2652
Eric Laurent8f42ea12018-08-08 09:08:25 -07002653 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002654
Andy Hung39efb7a2018-09-26 15:39:28 -07002655 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002656
Andy Hung39efb7a2018-09-26 15:39:28 -07002657 if (inputDesc->getClientCount() > 0) {
2658 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002659 return;
2660 }
2661
Eric Laurent05b90f82014-08-27 15:32:29 -07002662 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002663 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002664 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002665}
2666
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002668{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002669 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002670
2671 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002672 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002673 }
2674}
2675
Eric Laurent8f42ea12018-08-08 09:08:25 -07002676void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2677{
2678 stopInput(portId);
2679 releaseInput(portId);
2680}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681
Eric Laurent0dd51852019-04-19 18:18:58 -07002682void AudioPolicyManager::checkCloseInputs() {
2683 // After connecting or disconnecting an input device, close input if:
2684 // - it has no client (was just opened to check profile) OR
2685 // - none of its supported devices are connected anymore OR
2686 // - one of its clients cannot be routed to one of its supported
2687 // devices anymore. Otherwise update device selection
2688 std::vector<audio_io_handle_t> inputsToClose;
2689 for (size_t i = 0; i < mInputs.size(); i++) {
2690 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2691 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002692 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002693 inputsToClose.push_back(mInputs.keyAt(i));
2694 } else {
2695 bool close = false;
2696 for (const auto& client : input->clientsList()) {
2697 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002698 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002699 if (!input->supportedDevices().contains(device)) {
2700 close = true;
2701 break;
2702 }
2703 }
2704 if (close) {
2705 inputsToClose.push_back(mInputs.keyAt(i));
2706 } else {
2707 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2708 }
2709 }
2710 }
2711
2712 for (const audio_io_handle_t handle : inputsToClose) {
2713 ALOGV("%s closing input %d", __func__, handle);
2714 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002715 }
Eric Laurentd4692962014-05-05 18:13:44 -07002716}
2717
François Gaffie251c7f02018-11-07 10:41:08 +01002718void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
2720 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002721 if (indexMin < 0 || indexMax < 0) {
2722 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2723 return;
2724 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002725 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002726
2727 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002728 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2729 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002730 continue;
2731 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002732 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002733 }
Eric Laurente552edb2014-03-10 17:42:56 -07002734}
2735
Eric Laurente0720872014-03-11 09:30:41 -07002736status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002737 int index,
2738 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002739{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002740 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002741 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2742 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2743 return NO_ERROR;
2744 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002745 ALOGV("%s: stream %s attributes=%s", __func__,
2746 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002747 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002748}
2749
Eric Laurente0720872014-03-11 09:30:41 -07002750status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002751 int *index,
2752 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002753{
François Gaffiec005e562018-11-06 15:04:49 +01002754 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2755 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002756 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002757 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002758 deviceTypes = mEngine->getOutputDevicesForStream(
2759 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002760 }
jiabin9a3361e2019-10-01 09:38:30 -07002761 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002762}
2763
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002764status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002765 int index,
2766 audio_devices_t device)
2767{
2768 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002769 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2770 if (group == VOLUME_GROUP_NONE) {
2771 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002772 return BAD_VALUE;
2773 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002774 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002775 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002776 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002777 VolumeSource vs = toVolumeSource(group);
2778 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2779
2780 status = setVolumeCurveIndex(index, device, curves);
2781 if (status != NO_ERROR) {
2782 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2783 return status;
2784 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002785
jiabin9a3361e2019-10-01 09:38:30 -07002786 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002787 auto curCurvAttrs = curves.getAttributes();
2788 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2789 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002790 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002791 } else if (!curves.getStreamTypes().empty()) {
2792 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002793 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002794 } else {
2795 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2796 return BAD_VALUE;
2797 }
jiabin9a3361e2019-10-01 09:38:30 -07002798 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2799 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002800
François Gaffiecfe17322018-11-07 13:41:29 +01002801 // update volume on all outputs and streams matching the following:
2802 // - The requested stream (or a stream matching for volume control) is active on the output
2803 // - The device (or devices) selected by the engine for this stream includes
2804 // the requested device
2805 // - For non default requested device, currently selected device on the output is either the
2806 // requested device or one of the devices selected by the engine for this stream
2807 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2808 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002809 for (size_t i = 0; i < mOutputs.size(); i++) {
2810 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002811 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002812
jiabin9a3361e2019-10-01 09:38:30 -07002813 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2814 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002815 }
François Gaffieed91f582020-01-31 10:35:37 +01002816 if (!(desc->isActive(vs) || isInCall())) {
2817 continue;
2818 }
2819 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2820 curDevices.find(device) == curDevices.end()) {
2821 continue;
2822 }
2823 bool applyVolume = false;
2824 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2825 curSrcDevices.insert(device);
2826 applyVolume = (curSrcDevices.find(
2827 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2828 } else {
2829 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2830 }
2831 if (!applyVolume) {
2832 continue; // next output
2833 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002834 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2835 // If a higher priority strategy is active, and the output is routed to a device with a
2836 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002837 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002838 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002839 // If the volume source is active with higher priority source, ensure at least Sw Muted
2840 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002841 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2842 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2843 false /*preferredDevice*/);
2844 if (activeClients.empty()) {
2845 continue;
2846 }
2847 bool isPreempted = false;
2848 bool isHigherPriority = productStrategy < strategy;
2849 for (const auto &client : activeClients) {
2850 if (isHigherPriority && (client->volumeSource() != vs)) {
2851 ALOGV("%s: Strategy=%d (\nrequester:\n"
2852 " group %d, volumeGroup=%d attributes=%s)\n"
2853 " higher priority source active:\n"
2854 " volumeGroup=%d attributes=%s) \n"
2855 " on output %zu, bailing out", __func__, productStrategy,
2856 group, group, toString(attributes).c_str(),
2857 client->volumeSource(), toString(client->attributes()).c_str(), i);
2858 applyVolume = false;
2859 isPreempted = true;
2860 break;
2861 }
2862 // However, continue for loop to ensure no higher prio clients running on output
2863 if (client->volumeSource() == vs) {
2864 applyVolume = true;
2865 }
2866 }
2867 if (isPreempted || applyVolume) {
2868 break;
2869 }
2870 }
2871 if (!applyVolume) {
2872 continue; // next output
2873 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002874 }
François Gaffieed91f582020-01-31 10:35:37 +01002875 //FIXME: workaround for truncated touch sounds
2876 // delayed volume change for system stream to be removed when the problem is
2877 // handled by system UI
2878 status_t volStatus = checkAndSetVolume(
2879 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002880 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002881 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2882 if (volStatus != NO_ERROR) {
2883 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002884 }
2885 }
François Gaffiecfe17322018-11-07 13:41:29 +01002886 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2887 return status;
2888}
2889
François Gaffieaaac0fd2018-11-22 17:56:39 +01002890status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002891 audio_devices_t device,
2892 IVolumeCurves &volumeCurves)
2893{
2894 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2895 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002896 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2897 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002898 (index > volumeCurves.getVolumeIndexMax())) {
2899 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2900 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2901 return BAD_VALUE;
2902 }
2903 if (!audio_is_output_device(device)) {
2904 return BAD_VALUE;
2905 }
2906
2907 // Force max volume if stream cannot be muted
2908 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2909
François Gaffieaaac0fd2018-11-22 17:56:39 +01002910 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002911 volumeCurves.addCurrentVolumeIndex(device, index);
2912 return NO_ERROR;
2913}
2914
2915status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2916 int &index,
2917 audio_devices_t device)
2918{
2919 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2920 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002921 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002922 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002923 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2924 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002925 }
jiabin9a3361e2019-10-01 09:38:30 -07002926 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002927}
2928
2929status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2930 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002931 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002932{
jiabin9a3361e2019-10-01 09:38:30 -07002933 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002934 return BAD_VALUE;
2935 }
jiabin9a3361e2019-10-01 09:38:30 -07002936 index = curves.getVolumeIndex(deviceTypes);
2937 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002938 return NO_ERROR;
2939}
2940
2941status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2942 int &index)
2943{
2944 index = getVolumeCurves(attr).getVolumeIndexMin();
2945 return NO_ERROR;
2946}
2947
2948status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2949 int &index)
2950{
2951 index = getVolumeCurves(attr).getVolumeIndexMax();
2952 return NO_ERROR;
2953}
2954
Eric Laurent36829f92017-04-07 19:04:42 -07002955audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002956{
2957 // select one output among several suitable for global effects.
2958 // The priority is as follows:
2959 // 1: An offloaded output. If the effect ends up not being offloadable,
2960 // AudioFlinger will invalidate the track and the offloaded output
2961 // will be closed causing the effect to be moved to a PCM output.
2962 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002963 // 3: The primary output
2964 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002965
François Gaffiec005e562018-11-06 15:04:49 +01002966 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2967 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002968 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002969
Eric Laurent36829f92017-04-07 19:04:42 -07002970 if (outputs.size() == 0) {
2971 return AUDIO_IO_HANDLE_NONE;
2972 }
Eric Laurente552edb2014-03-10 17:42:56 -07002973
Eric Laurent36829f92017-04-07 19:04:42 -07002974 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2975 bool activeOnly = true;
2976
2977 while (output == AUDIO_IO_HANDLE_NONE) {
2978 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2979 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2980 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2981
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002982 for (audio_io_handle_t output : outputs) {
2983 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002984 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002985 continue;
2986 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002987 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2988 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002989 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002990 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002991 }
2992 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002993 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002994 }
2995 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002996 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002997 }
2998 }
2999 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3000 output = outputOffloaded;
3001 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3002 output = outputDeepBuffer;
3003 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3004 output = outputPrimary;
3005 } else {
3006 output = outputs[0];
3007 }
3008 activeOnly = false;
3009 }
3010
3011 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003012 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003013 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3014 mMusicEffectOutput = output;
3015 }
3016
3017 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003018 return output;
3019}
3020
Eric Laurent36829f92017-04-07 19:04:42 -07003021audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3022{
3023 return selectOutputForMusicEffects();
3024}
3025
Eric Laurente0720872014-03-11 09:30:41 -07003026status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003027 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003028 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003029 int session,
3030 int id)
3031{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003032 if (session != AUDIO_SESSION_DEVICE) {
3033 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003034 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003035 index = mInputs.indexOfKey(io);
3036 if (index < 0) {
3037 ALOGW("registerEffect() unknown io %d", io);
3038 return INVALID_OPERATION;
3039 }
Eric Laurente552edb2014-03-10 17:42:56 -07003040 }
3041 }
François Gaffiec005e562018-11-06 15:04:49 +01003042 return mEffects.registerEffect(desc, io, session, id,
3043 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3044 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003045}
3046
Eric Laurentc241b0d2018-11-28 09:08:49 -08003047status_t AudioPolicyManager::unregisterEffect(int id)
3048{
3049 if (mEffects.getEffect(id) == nullptr) {
3050 return INVALID_OPERATION;
3051 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003052 if (mEffects.isEffectEnabled(id)) {
3053 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3054 setEffectEnabled(id, false);
3055 }
3056 return mEffects.unregisterEffect(id);
3057}
3058
3059status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3060{
3061 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3062 if (effect == nullptr) {
3063 return INVALID_OPERATION;
3064 }
3065
3066 status_t status = mEffects.setEffectEnabled(id, enabled);
3067 if (status == NO_ERROR) {
3068 mInputs.trackEffectEnabled(effect, enabled);
3069 }
3070 return status;
3071}
3072
Eric Laurent6c796322019-04-09 14:13:17 -07003073
3074status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3075{
3076 mEffects.moveEffects(ids, io);
3077 return NO_ERROR;
3078}
3079
Eric Laurentc75307b2015-03-17 15:29:32 -07003080bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3081{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003082 auto vs = toVolumeSource(stream, false);
3083 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003084}
3085
3086bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3087{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003088 auto vs = toVolumeSource(stream, false);
3089 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003090}
3091
Eric Laurente0720872014-03-11 09:30:41 -07003092bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003093{
3094 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003095 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003096 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003097 return true;
3098 }
3099 }
3100 return false;
3101}
3102
Eric Laurent275e8e92014-11-30 15:14:47 -08003103// Register a list of custom mixes with their attributes and format.
3104// When a mix is registered, corresponding input and output profiles are
3105// added to the remote submix hw module. The profile contains only the
3106// parameters (sampling rate, format...) specified by the mix.
3107// The corresponding input remote submix device is also connected.
3108//
3109// When a remote submix device is connected, the address is checked to select the
3110// appropriate profile and the corresponding input or output stream is opened.
3111//
3112// When capture starts, getInputForAttr() will:
3113// - 1 look for a mix matching the address passed in attribtutes tags if any
3114// - 2 if none found, getDeviceForInputSource() will:
3115// - 2.1 look for a mix matching the attributes source
3116// - 2.2 if none found, default to device selection by policy rules
3117// At this time, the corresponding output remote submix device is also connected
3118// and active playback use cases can be transferred to this mix if needed when reconnecting
3119// after AudioTracks are invalidated
3120//
3121// When playback starts, getOutputForAttr() will:
3122// - 1 look for a mix matching the address passed in attribtutes tags if any
3123// - 2 if none found, look for a mix matching the attributes usage
3124// - 3 if none found, default to device and output selection by policy rules.
3125
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003126status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003127{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3129 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003130 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003131 sp<HwModule> rSubmixModule;
3132 // examine each mix's route type
3133 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003134 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003135 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3136 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3137 ALOGE("Unsupported Policy Mix %zu of %zu: "
3138 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3139 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003140 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003141 break;
3142 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003143 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3144 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003145 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003146 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3147 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003148 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003149 rSubmixModule = mHwModules.getModuleFromName(
3150 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3151 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003152 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003153 i);
3154 res = INVALID_OPERATION;
3155 break;
3156 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003158
Eric Laurent97ac8712018-07-27 18:59:02 -07003159 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003160 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003161 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003162 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003163 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3164 } else {
3165 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3166 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003167 }
François Gaffie036e1e92015-03-19 10:16:24 +01003168
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003169 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003170 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003171 res = INVALID_OPERATION;
3172 break;
3173 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003174 audio_config_t outputConfig = mix.mFormat;
3175 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003176 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3177 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003178 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3179 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003180 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003181 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003182 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003184
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003185 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003186 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3187 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3188 ALOGE("Failed to set remote submix device available, type %u, address %s",
3189 mix.mDeviceType, address.string());
3190 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003191 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003192 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3193 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003194 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003195 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003196 i, mixes.size(), type, address.string());
3197
3198 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3199 mix.mDeviceType, mix.mDeviceAddress,
3200 String8(), AUDIO_FORMAT_DEFAULT);
3201 if (device == nullptr) {
3202 res = INVALID_OPERATION;
3203 break;
3204 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003205
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003206 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003207 // First try to find an already opened output supporting the device
3208 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003209 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003210
Eric Laurentc529cf62020-04-17 18:19:10 -07003211 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003212 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003213 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3214 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003215 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003216 } else {
3217 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003218 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003219 }
3220 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003221 // If no output found, try to find a direct output profile supporting the device
3222 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3223 sp<HwModule> module = mHwModules[i];
3224 for (size_t j = 0;
3225 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3226 j++) {
3227 sp<IOProfile> profile = module->getOutputProfiles()[j];
3228 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3229 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3230 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3231 address.string());
3232 res = INVALID_OPERATION;
3233 } else {
3234 foundOutput = true;
3235 }
3236 }
3237 }
3238 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003239 if (res != NO_ERROR) {
3240 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003241 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003242 res = INVALID_OPERATION;
3243 break;
3244 } else if (!foundOutput) {
3245 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003246 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003247 res = INVALID_OPERATION;
3248 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003249 } else {
3250 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003251 }
Eric Laurentc722f302014-12-10 11:21:49 -08003252 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003253 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003254 if (res != NO_ERROR) {
3255 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003256 } else if (checkOutputs) {
3257 checkForDeviceAndOutputChanges();
3258 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003259 }
3260 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003261}
3262
3263status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3264{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003265 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003266 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003267 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268 sp<HwModule> rSubmixModule;
3269 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003270 for (const auto& mix : mixes) {
3271 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003272
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003273 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003274 rSubmixModule = mHwModules.getModuleFromName(
3275 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3276 if (rSubmixModule == 0) {
3277 res = INVALID_OPERATION;
3278 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003279 }
3280 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003281
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003282 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003283
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003284 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003285 res = INVALID_OPERATION;
3286 continue;
3287 }
3288
Kevin Rocard04ed0462019-05-02 17:53:24 -07003289 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3290 if (getDeviceConnectionState(device, address.string()) ==
3291 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3292 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3293 address.string(), "remote-submix",
3294 AUDIO_FORMAT_DEFAULT);
3295 if (res != OK) {
3296 ALOGE("Error making RemoteSubmix device unavailable for mix "
3297 "with type %d, address %s", device, address.string());
3298 }
3299 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003300 }
jiabin5740f082019-08-19 15:08:30 -07003301 rSubmixModule->removeOutputProfile(address.c_str());
3302 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003303
Kevin Rocard153f92d2018-12-18 18:33:28 -08003304 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003305 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003306 res = INVALID_OPERATION;
3307 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003308 } else {
3309 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003310 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003311 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003312 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003313 if (res == NO_ERROR && checkOutputs) {
3314 checkForDeviceAndOutputChanges();
3315 updateCallAndOutputRouting();
3316 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003317 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003318}
3319
Mikhail Naganov100f0122018-11-29 11:22:16 -08003320void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3321{
3322 size_t i = 0;
3323 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3324 for (const auto& fmt : mManualSurroundFormats) {
3325 if (i++ != 0) dst->append(", ");
3326 std::string sfmt;
3327 FormatConverter::toString(fmt, sfmt);
3328 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3329 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3330 }
3331}
3332
Eric Laurentc529cf62020-04-17 18:19:10 -07003333// Returns true if all devices types match the predicate and are supported by one HW module
3334bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003335 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003336 std::function<bool(audio_devices_t)> predicate,
3337 const char *context) {
3338 for (size_t i = 0; i < devices.size(); i++) {
3339 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003340 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003341 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003342 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003343 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003344 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003345 return false;
3346 }
3347 }
3348 return true;
3349}
3350
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003351status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003352 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003353 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003354 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3355 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003356 }
3357 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003358 if (res != NO_ERROR) {
3359 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3360 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003361 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003362
3363 checkForDeviceAndOutputChanges();
3364 updateCallAndOutputRouting();
3365
3366 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003367}
3368
3369status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3370 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003371 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3372 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003373 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003374 __FUNCTION__, uid);
3375 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003376 }
3377
Eric Laurentc529cf62020-04-17 18:19:10 -07003378 checkForDeviceAndOutputChanges();
3379 updateCallAndOutputRouting();
3380
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003381 return res;
3382}
3383
Eric Laurent2517af32020-11-25 15:31:27 +01003384
jiabin0a488932020-08-07 17:32:40 -07003385status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3386 device_role_t role,
3387 const AudioDeviceTypeAddrVector &devices) {
3388 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3389 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003390
Eric Laurentc529cf62020-04-17 18:19:10 -07003391 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003392 return BAD_VALUE;
3393 }
jiabin0a488932020-08-07 17:32:40 -07003394 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003395 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003396 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3397 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003398 return status;
3399 }
3400
3401 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003402
3403 bool forceVolumeReeval = false;
3404 // FIXME: workaround for truncated touch sounds
3405 // to be removed when the problem is handled by system UI
3406 uint32_t delayMs = 0;
3407 if (strategy == mCommunnicationStrategy) {
3408 forceVolumeReeval = true;
3409 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3410 updateInputRouting();
3411 }
3412 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003413
3414 return NO_ERROR;
3415}
3416
3417void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3418{
3419 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003420 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003421 // Only apply special touch sound delay once
3422 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003423 }
3424 for (size_t i = 0; i < mOutputs.size(); i++) {
3425 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3426 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3427 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3428 // As done in setDeviceConnectionState, we could also fix default device issue by
3429 // preventing the force re-routing in case of default dev that distinguishes on address.
3430 // Let's give back to engine full device choice decision however.
3431 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003432 // Only apply special touch sound delay once
3433 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003434 }
3435 if (forceVolumeReeval && !newDevices.isEmpty()) {
3436 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3437 }
3438 }
3439}
3440
Eric Laurent2517af32020-11-25 15:31:27 +01003441void AudioPolicyManager::updateInputRouting() {
3442 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303443 // Skip for hotword recording as the input device switch
3444 // is handled within sound trigger HAL
3445 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3446 continue;
3447 }
Eric Laurent2517af32020-11-25 15:31:27 +01003448 auto newDevice = getNewInputDevice(activeDesc);
3449 // Force new input selection if the new device can not be reached via current input
3450 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3451 setInputDevice(activeDesc->mIoHandle, newDevice);
3452 } else {
3453 closeInput(activeDesc->mIoHandle);
3454 }
3455 }
3456}
3457
jiabin0a488932020-08-07 17:32:40 -07003458status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3459 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003460{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003461 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003462
jiabin0a488932020-08-07 17:32:40 -07003463 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003464 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003465 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3466 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003467 return status;
3468 }
3469
3470 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003471
3472 bool forceVolumeReeval = false;
3473 // FIXME: workaround for truncated touch sounds
3474 // to be removed when the problem is handled by system UI
3475 uint32_t delayMs = 0;
3476 if (strategy == mCommunnicationStrategy) {
3477 forceVolumeReeval = true;
3478 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3479 updateInputRouting();
3480 }
3481 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003482
3483 return NO_ERROR;
3484}
3485
jiabin0a488932020-08-07 17:32:40 -07003486status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3487 device_role_t role,
3488 AudioDeviceTypeAddrVector &devices) {
3489 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003490}
3491
Jiabin Huang3b98d322020-09-03 17:54:16 +00003492status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3493 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3494 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3495 dumpAudioDeviceTypeAddrVector(devices).c_str());
3496
Mikhail Naganov55773032020-10-01 15:08:13 -07003497 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003498 return BAD_VALUE;
3499 }
3500 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3501 ALOGW_IF(status != NO_ERROR,
3502 "Engine could not set preferred devices %s for audio source %d role %d",
3503 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3504
3505 return status;
3506}
3507
3508status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3509 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3510 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3511 dumpAudioDeviceTypeAddrVector(devices).c_str());
3512
Mikhail Naganov55773032020-10-01 15:08:13 -07003513 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003514 return BAD_VALUE;
3515 }
3516 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3517 ALOGW_IF(status != NO_ERROR,
3518 "Engine could not add preferred devices %s for audio source %d role %d",
3519 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3520
Eric Laurent2517af32020-11-25 15:31:27 +01003521 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003522 return status;
3523}
3524
3525status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3526 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3527{
3528 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3529 dumpAudioDeviceTypeAddrVector(devices).c_str());
3530
Mikhail Naganov55773032020-10-01 15:08:13 -07003531 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003532 return BAD_VALUE;
3533 }
3534
3535 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3536 audioSource, role, devices);
3537 ALOGW_IF(status != NO_ERROR,
3538 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3539
Eric Laurent2517af32020-11-25 15:31:27 +01003540 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003541 return status;
3542}
3543
3544status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3545 device_role_t role) {
3546 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3547
3548 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3549 ALOGW_IF(status != NO_ERROR,
3550 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3551
Eric Laurent2517af32020-11-25 15:31:27 +01003552 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003553 return status;
3554}
3555
3556status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3557 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3558 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3559}
3560
Oscar Azucena90e77632019-11-27 17:12:28 -08003561status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003562 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003563 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003564 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3565 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003566 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003567 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3568 if (status != NO_ERROR) {
3569 ALOGE("%s() could not set device affinity for userId %d",
3570 __FUNCTION__, userId);
3571 return status;
3572 }
3573
3574 // reevaluate outputs for all devices
3575 checkForDeviceAndOutputChanges();
3576 updateCallAndOutputRouting();
3577
3578 return NO_ERROR;
3579}
3580
3581status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003582 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003583 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3584 if (status != NO_ERROR) {
3585 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3586 __FUNCTION__, userId);
3587 return status;
3588 }
3589
3590 // reevaluate outputs for all devices
3591 checkForDeviceAndOutputChanges();
3592 updateCallAndOutputRouting();
3593
3594 return NO_ERROR;
3595}
3596
Andy Hungc29d82b2018-10-05 12:23:17 -07003597void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003598{
Andy Hungc29d82b2018-10-05 12:23:17 -07003599 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3600 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003601 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003602 std::string stateLiteral;
3603 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003604 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003605 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3606 "communications", "media", "record", "dock", "system",
3607 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3608 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3609 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003610 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3611 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3612 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3613 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3614 dst->append(" (MANUAL: ");
3615 dumpManualSurroundFormats(dst);
3616 dst->append(")");
3617 }
3618 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003619 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003620 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3621 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003622 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003623 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003624
Andy Hungc29d82b2018-10-05 12:23:17 -07003625 mAvailableOutputDevices.dump(dst, String8("Available output"));
3626 mAvailableInputDevices.dump(dst, String8("Available input"));
3627 mHwModulesAll.dump(dst);
3628 mOutputs.dump(dst);
3629 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003630 mEffects.dump(dst);
3631 mAudioPatches.dump(dst);
3632 mPolicyMixes.dump(dst);
3633 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003634
Kevin Rocardb99cc752019-03-21 20:52:24 -07003635 dst->appendFormat(" AllowedCapturePolicies:\n");
3636 for (auto& policy : mAllowedCapturePolicies) {
3637 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3638 }
3639
François Gaffiec005e562018-11-06 15:04:49 +01003640 dst->appendFormat("\nPolicy Engine dump:\n");
3641 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003642}
3643
3644status_t AudioPolicyManager::dump(int fd)
3645{
3646 String8 result;
3647 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003648 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003649 return NO_ERROR;
3650}
3651
Kevin Rocardb99cc752019-03-21 20:52:24 -07003652status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3653{
3654 mAllowedCapturePolicies[uid] = capturePolicy;
3655 return NO_ERROR;
3656}
3657
Eric Laurente552edb2014-03-10 17:42:56 -07003658// This function checks for the parameters which can be offloaded.
3659// This can be enhanced depending on the capability of the DSP and policy
3660// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003661audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003662{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003663 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003664 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003665 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003666 offloadInfo.format,
3667 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3668 offloadInfo.has_video);
3669
Andy Hung2ddee192015-12-18 17:34:44 -08003670 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003671 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003672 }
3673
Eric Laurente552edb2014-03-10 17:42:56 -07003674 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003675 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003676 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3677 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003678 }
3679
3680 // Check if stream type is music, then only allow offload as of now.
3681 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3682 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003683 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3684 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003685 }
3686
3687 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003688 const bool allowOffloadWithVideo =
3689 property_get_bool("audio.offload.video", false /* default_value */);
3690 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003691 ALOGV("%s: has_video == true, returning false", __func__);
3692 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003693 }
3694
3695 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003696 const int min_duration_secs = property_get_int32(
3697 "audio.offload.min.duration.secs", -1 /* default_value */);
3698 if (min_duration_secs >= 0) {
3699 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003700 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3701 __func__, min_duration_secs);
3702 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003703 }
3704 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003705 ALOGV("%s: Offload denied by duration < default min(=%u)",
3706 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3707 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003708 }
3709
3710 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3711 // creating an offloaded track and tearing it down immediately after start when audioflinger
3712 // detects there is an active non offloadable effect.
3713 // FIXME: We should check the audio session here but we do not have it in this context.
3714 // This may prevent offloading in rare situations where effects are left active by apps
3715 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003716 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003717 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003718 }
3719
3720 // See if there is a profile to support this.
3721 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003722 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003723 offloadInfo.sample_rate,
3724 offloadInfo.format,
3725 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003726 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3727 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003728 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3729 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3730 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003731 if (profile == nullptr) {
3732 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3733 }
3734 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3735 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3736 }
3737 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003738}
3739
Michael Chana94fbb22018-04-24 14:31:19 +10003740bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3741 const audio_attributes_t& attributes) {
3742 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003743 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003744 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003745 config.sample_rate,
3746 config.format,
3747 config.channel_mask,
3748 output_flags,
3749 true /* directOnly */);
3750 ALOGV("%s() profile %sfound with name: %s, "
3751 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3752 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003753 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003754 config.sample_rate, config.format, config.channel_mask, output_flags);
3755 return (profile != 0);
3756}
3757
Eric Laurent6a94d692014-05-20 11:18:06 -07003758status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3759 audio_port_type_t type,
3760 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003761 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003762 unsigned int *generation)
3763{
jiabin19cdba52020-11-24 11:28:58 -08003764 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3765 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003766 return BAD_VALUE;
3767 }
3768 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003769 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 *num_ports = 0;
3771 }
3772
3773 size_t portsWritten = 0;
3774 size_t portsMax = *num_ports;
3775 *num_ports = 0;
3776 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003777 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3778 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003779 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003780 for (const auto& dev : mAvailableOutputDevices) {
3781 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003782 continue;
3783 }
3784 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003785 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003786 }
3787 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003789 }
3790 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003791 for (const auto& dev : mAvailableInputDevices) {
3792 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003793 continue;
3794 }
3795 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003796 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003797 }
3798 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003799 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003800 }
3801 }
3802 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3803 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3804 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3805 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3806 }
3807 *num_ports += mInputs.size();
3808 }
3809 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003810 size_t numOutputs = 0;
3811 for (size_t i = 0; i < mOutputs.size(); i++) {
3812 if (!mOutputs[i]->isDuplicated()) {
3813 numOutputs++;
3814 if (portsWritten < portsMax) {
3815 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3816 }
3817 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003818 }
Eric Laurent84c70242014-06-23 08:46:27 -07003819 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003820 }
3821 }
3822 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003823 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003824 return NO_ERROR;
3825}
3826
jiabin19cdba52020-11-24 11:28:58 -08003827status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003828{
Eric Laurent99fcae42018-05-17 16:59:18 -07003829 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3830 return BAD_VALUE;
3831 }
3832 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3833 if (dev != 0) {
3834 dev->toAudioPort(port);
3835 return NO_ERROR;
3836 }
3837 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3838 if (dev != 0) {
3839 dev->toAudioPort(port);
3840 return NO_ERROR;
3841 }
3842 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3843 if (out != 0) {
3844 out->toAudioPort(port);
3845 return NO_ERROR;
3846 }
3847 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3848 if (in != 0) {
3849 in->toAudioPort(port);
3850 return NO_ERROR;
3851 }
3852 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003853}
3854
François Gaffieafd4cea2019-11-18 15:50:22 +01003855status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3856 audio_patch_handle_t *handle,
3857 uid_t uid, uint32_t delayMs,
3858 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003859{
François Gaffieafd4cea2019-11-18 15:50:22 +01003860 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003861 if (handle == NULL || patch == NULL) {
3862 return BAD_VALUE;
3863 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003864 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003865
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003866 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003867 return BAD_VALUE;
3868 }
3869 // only one source per audio patch supported for now
3870 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003871 return INVALID_OPERATION;
3872 }
Eric Laurent874c42872014-08-08 15:13:39 -07003873
3874 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003875 return INVALID_OPERATION;
3876 }
Eric Laurent874c42872014-08-08 15:13:39 -07003877 for (size_t i = 0; i < patch->num_sinks; i++) {
3878 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3879 return INVALID_OPERATION;
3880 }
3881 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003882
3883 sp<AudioPatch> patchDesc;
3884 ssize_t index = mAudioPatches.indexOfKey(*handle);
3885
François Gaffieafd4cea2019-11-18 15:50:22 +01003886 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3887 patch->sources[0].role,
3888 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003889#if LOG_NDEBUG == 0
3890 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003891 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3892 patch->sinks[i].role,
3893 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003894 }
3895#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003896
3897 if (index >= 0) {
3898 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003899 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3900 __func__, mUidCached, patchDesc->getUid(), uid);
3901 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003902 return INVALID_OPERATION;
3903 }
3904 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003905 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003906 }
3907
3908 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003909 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003910 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003911 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003912 return BAD_VALUE;
3913 }
Eric Laurent84c70242014-06-23 08:46:27 -07003914 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3915 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003916 if (patchDesc != 0) {
3917 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003918 ALOGV("%s source id differs for patch current id %d new id %d",
3919 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 return BAD_VALUE;
3921 }
3922 }
Eric Laurent874c42872014-08-08 15:13:39 -07003923 DeviceVector devices;
3924 for (size_t i = 0; i < patch->num_sinks; i++) {
3925 // Only support mix to devices connection
3926 // TODO add support for mix to mix connection
3927 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003928 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003929 return INVALID_OPERATION;
3930 }
3931 sp<DeviceDescriptor> devDesc =
3932 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3933 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003934 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003935 return BAD_VALUE;
3936 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003937
François Gaffie11d30102018-11-02 16:09:09 +01003938 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003939 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003940 NULL, // updatedSamplingRate
3941 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003942 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003943 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003944 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003945 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003946 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003947 return INVALID_OPERATION;
3948 }
3949 devices.add(devDesc);
3950 }
3951 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003952 return INVALID_OPERATION;
3953 }
Eric Laurent874c42872014-08-08 15:13:39 -07003954
Eric Laurent6a94d692014-05-20 11:18:06 -07003955 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003956 ALOGV("%s setting device %s on output %d",
3957 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003958 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003959 index = mAudioPatches.indexOfKey(*handle);
3960 if (index >= 0) {
3961 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003962 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003963 }
3964 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003965 patchDesc->setUid(uid);
3966 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003967 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003968 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003969 return INVALID_OPERATION;
3970 }
3971 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3972 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3973 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003974 // only one sink supported when connecting an input device to a mix
3975 if (patch->num_sinks > 1) {
3976 return INVALID_OPERATION;
3977 }
François Gaffie53615e22015-03-19 09:24:12 +01003978 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003979 if (inputDesc == NULL) {
3980 return BAD_VALUE;
3981 }
3982 if (patchDesc != 0) {
3983 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3984 return BAD_VALUE;
3985 }
3986 }
François Gaffie11d30102018-11-02 16:09:09 +01003987 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003989 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 return BAD_VALUE;
3991 }
3992
François Gaffie11d30102018-11-02 16:09:09 +01003993 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003994 patch->sinks[0].sample_rate,
3995 NULL, /*updatedSampleRate*/
3996 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003997 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003998 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003999 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004000 // FIXME for the parameter type,
4001 // and the NONE
4002 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004003 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004004 return INVALID_OPERATION;
4005 }
4006 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004007 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004008 device->toString().c_str(), inputDesc->mIoHandle);
4009 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004010 index = mAudioPatches.indexOfKey(*handle);
4011 if (index >= 0) {
4012 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004013 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004014 }
4015 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004016 patchDesc->setUid(uid);
4017 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004018 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004019 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004020 return INVALID_OPERATION;
4021 }
4022 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4023 // device to device connection
4024 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004025 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004026 return BAD_VALUE;
4027 }
4028 }
François Gaffie11d30102018-11-02 16:09:09 +01004029 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004030 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004031 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004032 return BAD_VALUE;
4033 }
Eric Laurent874c42872014-08-08 15:13:39 -07004034
Eric Laurent6a94d692014-05-20 11:18:06 -07004035 //update source and sink with our own data as the data passed in the patch may
4036 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004037 PatchBuilder patchBuilder;
4038 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004039
4040 // if first sink is to MSD, establish single MSD patch
4041 if (getMsdAudioOutDevices().contains(
4042 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4043 ALOGV("%s patching to MSD", __FUNCTION__);
4044 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4045 goto installPatch;
4046 }
4047
François Gaffieafd4cea2019-11-18 15:50:22 +01004048 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4049 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004050
Eric Laurent874c42872014-08-08 15:13:39 -07004051 for (size_t i = 0; i < patch->num_sinks; i++) {
4052 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004053 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004054 return INVALID_OPERATION;
4055 }
François Gaffie11d30102018-11-02 16:09:09 +01004056 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004057 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004058 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004059 return BAD_VALUE;
4060 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004061 audio_port_config sinkPortConfig = {};
4062 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4063 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004064
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004065 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4066 // volume management purpose (tracking activity)
4067 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4068 // in config XML to reach the sink so that is can be declared as available.
4069 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4070 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4071 if (sourceDesc != nullptr) {
4072 // take care of dynamic routing for SwOutput selection,
4073 audio_attributes_t attributes = sourceDesc->attributes();
4074 audio_stream_type_t stream = sourceDesc->stream();
4075 audio_attributes_t resultAttr;
4076 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4077 config.sample_rate = sourceDesc->config().sample_rate;
4078 config.channel_mask = sourceDesc->config().channel_mask;
4079 config.format = sourceDesc->config().format;
4080 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4081 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4082 bool isRequestedDeviceForExclusiveUse = false;
4083 output_type_t outputType;
4084 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4085 &stream, sourceDesc->uid(), &config, &flags,
4086 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4087 nullptr, &outputType);
4088 if (output == AUDIO_IO_HANDLE_NONE) {
4089 ALOGV("%s no output for device %s",
4090 __FUNCTION__, sinkDevice->toString().c_str());
4091 return INVALID_OPERATION;
4092 }
4093 outputDesc = mOutputs.valueFor(output);
4094 if (outputDesc->isDuplicated()) {
4095 ALOGE("%s output is duplicated", __func__);
4096 return INVALID_OPERATION;
4097 }
4098 sourceDesc->setSwOutput(outputDesc);
4099 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004100 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004101 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004102 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004103 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004104 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4105 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004106 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4107 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004108 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4109 (sourceDesc != nullptr &&
4110 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004111 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004112 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004113 return INVALID_OPERATION;
4114 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004115 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004116 SortedVector<audio_io_handle_t> outputs =
4117 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4118 // if the sink device is reachable via an opened output stream, request to
4119 // go via this output stream by adding a second source to the patch
4120 // description
4121 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004122 if (output != AUDIO_IO_HANDLE_NONE) {
4123 outputDesc = mOutputs.valueFor(output);
4124 if (outputDesc->isDuplicated()) {
4125 ALOGV("%s output for device %s is duplicated",
4126 __FUNCTION__, sinkDevice->toString().c_str());
4127 return INVALID_OPERATION;
4128 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004129 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004130 }
4131 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004132 audio_port_config srcMixPortConfig = {};
4133 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004134 // for volume control, we may need a valid stream
4135 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4136 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4137 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004138 }
Eric Laurent83b88082014-06-20 18:31:16 -07004139 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004140 }
4141 // TODO: check from routing capabilities in config file and other conflicting patches
4142
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004143installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004144 status_t status = installPatch(
4145 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004146 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004147 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004148 return INVALID_OPERATION;
4149 }
4150 } else {
4151 return BAD_VALUE;
4152 }
4153 } else {
4154 return BAD_VALUE;
4155 }
4156 return NO_ERROR;
4157}
4158
4159status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4160 uid_t uid)
4161{
4162 ALOGV("releaseAudioPatch() patch %d", handle);
4163
4164 ssize_t index = mAudioPatches.indexOfKey(handle);
4165
4166 if (index < 0) {
4167 return BAD_VALUE;
4168 }
4169 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004170 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4171 __func__, mUidCached, patchDesc->getUid(), uid);
4172 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004173 return INVALID_OPERATION;
4174 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004175 return releaseAudioPatchInternal(handle);
4176}
Eric Laurent6a94d692014-05-20 11:18:06 -07004177
François Gaffieafd4cea2019-11-18 15:50:22 +01004178status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4179 uint32_t delayMs)
4180{
4181 ALOGV("%s patch %d", __func__, handle);
4182 if (mAudioPatches.indexOfKey(handle) < 0) {
4183 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4184 return BAD_VALUE;
4185 }
4186 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004188 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004190 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004192 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 return BAD_VALUE;
4194 }
4195
François Gaffie11d30102018-11-02 16:09:09 +01004196 setOutputDevices(outputDesc,
4197 getNewOutputDevices(outputDesc, true /*fromCache*/),
4198 true,
4199 0,
4200 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004201 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4202 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004203 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004204 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004205 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004206 return BAD_VALUE;
4207 }
4208 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004209 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 true,
4211 NULL);
4212 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004213 status_t status =
4214 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4215 ALOGV("%s patch panel returned %d patchHandle %d",
4216 __func__, status, patchDesc->getAfHandle());
4217 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004219 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004220 // SW Bridge
4221 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4222 sp<SwAudioOutputDescriptor> outputDesc =
4223 mOutputs.getOutputFromId(patch->sources[1].id);
4224 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004225 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4226 // releaseOutput has already called closeOuput in case of direct output
4227 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004228 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004229 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4230 // force SwOutput patch removal as AF counter part patch has already gone.
4231 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4232 removeAudioPatch(outputDesc->getPatchHandle());
4233 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004234 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4235 setOutputDevices(outputDesc,
4236 getNewOutputDevices(outputDesc, true /*fromCache*/),
4237 true, /*force*/
4238 0,
4239 NULL);
4240 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004241 } else {
4242 return BAD_VALUE;
4243 }
4244 } else {
4245 return BAD_VALUE;
4246 }
4247 return NO_ERROR;
4248}
4249
4250status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4251 struct audio_patch *patches,
4252 unsigned int *generation)
4253{
François Gaffie53615e22015-03-19 09:24:12 +01004254 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004255 return BAD_VALUE;
4256 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004257 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004258 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004259}
4260
Eric Laurente1715a42014-05-20 11:30:42 -07004261status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004262{
Eric Laurente1715a42014-05-20 11:30:42 -07004263 ALOGV("setAudioPortConfig()");
4264
4265 if (config == NULL) {
4266 return BAD_VALUE;
4267 }
4268 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4269 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004270 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4271 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004272 }
4273
Eric Laurenta121f902014-06-03 13:32:54 -07004274 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004275 if (config->type == AUDIO_PORT_TYPE_MIX) {
4276 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004277 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004278 if (outputDesc == NULL) {
4279 return BAD_VALUE;
4280 }
Eric Laurent84c70242014-06-23 08:46:27 -07004281 ALOG_ASSERT(!outputDesc->isDuplicated(),
4282 "setAudioPortConfig() called on duplicated output %d",
4283 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004284 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004285 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004286 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004287 if (inputDesc == NULL) {
4288 return BAD_VALUE;
4289 }
Eric Laurenta121f902014-06-03 13:32:54 -07004290 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004291 } else {
4292 return BAD_VALUE;
4293 }
4294 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4295 sp<DeviceDescriptor> deviceDesc;
4296 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4297 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4298 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4299 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4300 } else {
4301 return BAD_VALUE;
4302 }
4303 if (deviceDesc == NULL) {
4304 return BAD_VALUE;
4305 }
Eric Laurenta121f902014-06-03 13:32:54 -07004306 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004307 } else {
4308 return BAD_VALUE;
4309 }
4310
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004311 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004312 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4313 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004314 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004315 audioPortConfig->toAudioPortConfig(&newConfig, config);
4316 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004317 }
Eric Laurenta121f902014-06-03 13:32:54 -07004318 if (status != NO_ERROR) {
4319 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004320 }
Eric Laurente1715a42014-05-20 11:30:42 -07004321
4322 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004323}
4324
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004325void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4326{
Eric Laurentd60560a2015-04-10 11:31:20 -07004327 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004328 clearAudioPatches(uid);
4329 clearSessionRoutes(uid);
4330}
4331
Eric Laurent6a94d692014-05-20 11:18:06 -07004332void AudioPolicyManager::clearAudioPatches(uid_t uid)
4333{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004334 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004335 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004336 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004337 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004338 }
4339 }
4340}
4341
François Gaffiec005e562018-11-06 15:04:49 +01004342void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004343{
François Gaffiec005e562018-11-06 15:04:49 +01004344 // Take the first attributes following the product strategy as it is used to retrieve the routed
4345 // device. All attributes wihin a strategy follows the same "routing strategy"
4346 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4347 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004348 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004349 for (size_t j = 0; j < mOutputs.size(); j++) {
4350 if (mOutputs.keyAt(j) == ouptutToSkip) {
4351 continue;
4352 }
4353 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004354 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004355 continue;
4356 }
4357 // If the default device for this strategy is on another output mix,
4358 // invalidate all tracks in this strategy to force re connection.
4359 // Otherwise select new device on the output mix.
4360 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004361 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4362 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004363 }
4364 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004365 setOutputDevices(
4366 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004367 }
4368 }
4369}
4370
4371void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4372{
4373 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004374 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004375 for (size_t i = 0; i < mOutputs.size(); i++) {
4376 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004377 for (const auto& client : outputDesc->getClientIterable()) {
4378 if (client->hasPreferredDevice() && client->uid() == uid) {
4379 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004380 auto clientStrategy = client->strategy();
4381 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4382 end(affectedStrategies)) {
4383 continue;
4384 }
4385 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004386 }
4387 }
4388 }
4389 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004390 for (const auto& strategy : affectedStrategies) {
4391 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004392 }
4393
4394 // remove input routes associated with this uid
4395 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004396 for (size_t i = 0; i < mInputs.size(); i++) {
4397 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004398 for (const auto& client : inputDesc->getClientIterable()) {
4399 if (client->hasPreferredDevice() && client->uid() == uid) {
4400 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4401 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004402 }
4403 }
4404 }
4405 // reroute inputs if necessary
4406 SortedVector<audio_io_handle_t> inputsToClose;
4407 for (size_t i = 0; i < mInputs.size(); i++) {
4408 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004409 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004410 inputsToClose.add(inputDesc->mIoHandle);
4411 }
4412 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004413 for (const auto& input : inputsToClose) {
4414 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004415 }
4416}
4417
Eric Laurentd60560a2015-04-10 11:31:20 -07004418void AudioPolicyManager::clearAudioSources(uid_t uid)
4419{
4420 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004421 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4422 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004423 stopAudioSource(mAudioSources.keyAt(i));
4424 }
4425 }
4426}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004427
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004428status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4429 audio_io_handle_t *ioHandle,
4430 audio_devices_t *device)
4431{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004432 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4433 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004434 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004435 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004436
François Gaffiedf372692015-03-19 10:43:27 +01004437 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004438}
4439
Eric Laurentd60560a2015-04-10 11:31:20 -07004440status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004441 const audio_attributes_t *attributes,
4442 audio_port_handle_t *portId,
4443 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004444{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004445 ALOGV("%s", __FUNCTION__);
4446 *portId = AUDIO_PORT_HANDLE_NONE;
4447
4448 if (source == NULL || attributes == NULL || portId == NULL) {
4449 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4450 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004451 return BAD_VALUE;
4452 }
4453
Eric Laurentd60560a2015-04-10 11:31:20 -07004454 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4455 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004456 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4457 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004458 return INVALID_OPERATION;
4459 }
4460
François Gaffie11d30102018-11-02 16:09:09 +01004461 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004462 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004463 String8(source->ext.device.address),
4464 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004465 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004466 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004467 return BAD_VALUE;
4468 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004469
jiabin4ef93452019-09-10 14:29:54 -07004470 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004471
François Gaffieaaac0fd2018-11-22 17:56:39 +01004472 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004473 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004474 mEngine->getStreamTypeForAttributes(*attributes),
4475 mEngine->getProductStrategyForAttributes(*attributes),
4476 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004477
4478 status_t status = connectAudioSource(sourceDesc);
4479 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004480 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004481 }
4482 return status;
4483}
4484
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004485status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004486{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004487 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004488
4489 // make sure we only have one patch per source.
4490 disconnectAudioSource(sourceDesc);
4491
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004492 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004493 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4494 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4495 sourceDesc->srcDevice()->type(),
4496 String8(sourceDesc->srcDevice()->address().c_str()),
4497 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004498 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004499 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004500 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004501 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004502 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4503 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4504 return INVALID_OPERATION;
4505 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004506 PatchBuilder patchBuilder;
4507 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4508 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4509 status_t status =
4510 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4511 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4512 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4513 return INVALID_OPERATION;
4514 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004515 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004516 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4517 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4518 if (swOutput != 0) {
4519 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004520 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004521 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004522 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004523 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004524 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004525 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004526 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004527 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004528 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004529 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004530 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004531 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4532 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004533 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004534 if (delayMs != 0) {
4535 usleep(delayMs * 1000);
4536 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004537 } else {
4538 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4539 if (hwOutputDesc != 0) {
4540 // create Hwoutput and add to mHwOutputs
4541 } else {
4542 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4543 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004544 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004545 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004546
4547FailureSourceActive:
4548 swOutput->stop();
4549 releaseOutput(sourceDesc->portId());
4550FailureSourceAdded:
4551 sourceDesc->setSwOutput(nullptr);
4552FailureReleasePatch:
4553 releaseAudioPatchInternal(handle);
4554 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004555}
4556
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004557status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004558{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004559 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4560 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004561 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004562 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004563 return BAD_VALUE;
4564 }
4565 status_t status = disconnectAudioSource(sourceDesc);
4566
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004567 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004568 return status;
4569}
4570
Andy Hung2ddee192015-12-18 17:34:44 -08004571status_t AudioPolicyManager::setMasterMono(bool mono)
4572{
4573 if (mMasterMono == mono) {
4574 return NO_ERROR;
4575 }
4576 mMasterMono = mono;
4577 // if enabling mono we close all offloaded devices, which will invalidate the
4578 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4579 // for recreating the new AudioTrack as non-offloaded PCM.
4580 //
4581 // If disabling mono, we leave all tracks as is: we don't know which clients
4582 // and tracks are able to be recreated as offloaded. The next "song" should
4583 // play back offloaded.
4584 if (mMasterMono) {
4585 Vector<audio_io_handle_t> offloaded;
4586 for (size_t i = 0; i < mOutputs.size(); ++i) {
4587 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4588 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4589 offloaded.push(desc->mIoHandle);
4590 }
4591 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004592 for (const auto& handle : offloaded) {
4593 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004594 }
4595 }
4596 // update master mono for all remaining outputs
4597 for (size_t i = 0; i < mOutputs.size(); ++i) {
4598 updateMono(mOutputs.keyAt(i));
4599 }
4600 return NO_ERROR;
4601}
4602
4603status_t AudioPolicyManager::getMasterMono(bool *mono)
4604{
4605 *mono = mMasterMono;
4606 return NO_ERROR;
4607}
4608
Eric Laurentac9cef52017-06-09 15:46:26 -07004609float AudioPolicyManager::getStreamVolumeDB(
4610 audio_stream_type_t stream, int index, audio_devices_t device)
4611{
jiabin9a3361e2019-10-01 09:38:30 -07004612 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004613}
4614
jiabin81772902018-04-02 17:52:27 -07004615status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4616 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004617 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004618{
Kriti Dang6537def2021-03-02 13:46:59 +01004619 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4620 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004621 return BAD_VALUE;
4622 }
Kriti Dang6537def2021-03-02 13:46:59 +01004623 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4624 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004625
4626 size_t formatsWritten = 0;
4627 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004628
Kriti Dang6537def2021-03-02 13:46:59 +01004629 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004630 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4631 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004632 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004633 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004634 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004635 bool formatEnabled = true;
4636 switch (forceUse) {
4637 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004638 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004639 break;
4640 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4641 formatEnabled = false;
4642 break;
4643 default: // AUTO or ALWAYS => true
4644 break;
jiabin81772902018-04-02 17:52:27 -07004645 }
4646 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4647 }
jiabin81772902018-04-02 17:52:27 -07004648 }
4649 return NO_ERROR;
4650}
4651
Kriti Dang6537def2021-03-02 13:46:59 +01004652status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4653 audio_format_t *surroundFormats) {
4654 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4655 return BAD_VALUE;
4656 }
4657 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4658 __func__, *numSurroundFormats, surroundFormats);
4659
4660 size_t formatsWritten = 0;
4661 size_t formatsMax = *numSurroundFormats;
4662 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4663
4664 // Return formats from all device profiles that have already been resolved by
4665 // checkOutputsForDevice().
4666 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4667 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4668 audio_devices_t deviceType = device->type();
4669 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4670 // returns formats reported by HDMI devices.
4671 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4672 continue;
4673 }
4674 // Formats reported by sink devices
4675 std::unordered_set<audio_format_t> formatset;
4676 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4677 formatset.insert(it->second.begin(), it->second.end());
4678 }
4679
4680 // Formats hard-coded in the in policy configuration file (if any).
4681 FormatVector encodedFormats = device->encodedFormats();
4682 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4683 // Filter the formats which are supported by the vendor hardware.
4684 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4685 if (mConfig.getSurroundFormats().count(*it) != 0) {
4686 formats.insert(*it);
4687 } else {
4688 for (const auto& pair : mConfig.getSurroundFormats()) {
4689 if (pair.second.count(*it) != 0) {
4690 formats.insert(pair.first);
4691 break;
4692 }
4693 }
4694 }
4695 }
4696 }
4697 *numSurroundFormats = formats.size();
4698 for (const auto& format: formats) {
4699 if (formatsWritten < formatsMax) {
4700 surroundFormats[formatsWritten++] = format;
4701 }
4702 }
4703 return NO_ERROR;
4704}
4705
jiabin81772902018-04-02 17:52:27 -07004706status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4707{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004708 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004709 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4710 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004711 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004712 return BAD_VALUE;
4713 }
4714
Mikhail Naganov100f0122018-11-29 11:22:16 -08004715 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4716 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004717 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004718 return INVALID_OPERATION;
4719 }
4720
Mikhail Naganov100f0122018-11-29 11:22:16 -08004721 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004722 return NO_ERROR;
4723 }
4724
Mikhail Naganov100f0122018-11-29 11:22:16 -08004725 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004726 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004727 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004728 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004729 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004730 }
4731 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004732 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004733 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004734 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004735 }
4736 }
4737
4738 sp<SwAudioOutputDescriptor> outputDesc;
4739 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004740 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4741 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004742 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4743 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004744 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004745 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004746 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4747 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4748 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004749 name.c_str(),
4750 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004751 if (status != NO_ERROR) {
4752 continue;
4753 }
4754 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4755 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4756 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004757 name.c_str(),
4758 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004759 profileUpdated |= (status == NO_ERROR);
4760 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004761 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004762 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004763 AUDIO_DEVICE_IN_HDMI);
4764 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4765 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004766 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004767 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004768 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4769 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4770 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004771 name.c_str(),
4772 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004773 if (status != NO_ERROR) {
4774 continue;
4775 }
4776 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4777 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4778 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004779 name.c_str(),
4780 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004781 profileUpdated |= (status == NO_ERROR);
4782 }
4783
jiabin81772902018-04-02 17:52:27 -07004784 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004785 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004786 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004787 }
4788
4789 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4790}
4791
Eric Laurent5ada82e2019-08-29 17:53:54 -07004792void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004793{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004794 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004795 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004796 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004797 }
4798}
4799
jiabin6012f912018-11-02 17:06:30 -07004800bool AudioPolicyManager::isHapticPlaybackSupported()
4801{
4802 for (const auto& hwModule : mHwModules) {
4803 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4804 for (const auto &outProfile : outputProfiles) {
4805 struct audio_port audioPort;
4806 outProfile->toAudioPort(&audioPort);
4807 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4808 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4809 return true;
4810 }
4811 }
4812 }
4813 }
4814 return false;
4815}
4816
Eric Laurent8340e672019-11-06 11:01:08 -08004817bool AudioPolicyManager::isCallScreenModeSupported()
4818{
4819 return getConfig().isCallScreenModeSupported();
4820}
4821
4822
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004823status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004824{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004825 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004826 if (!sourceDesc->isConnected()) {
4827 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4828 return NO_ERROR;
4829 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004830 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4831 if (swOutput != 0) {
4832 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004833 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004834 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004835 }
jiabinbce0c1d2020-10-05 11:20:18 -07004836 if (releaseOutput(sourceDesc->portId())) {
4837 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4838 // no need to release audio patch here but just return NO_ERROR.
4839 return NO_ERROR;
4840 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004841 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004842 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004843 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004844 // close Hwoutput and remove from mHwOutputs
4845 } else {
4846 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4847 }
4848 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004849 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4850 sourceDesc->disconnect();
4851 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004852}
4853
François Gaffiec005e562018-11-06 15:04:49 +01004854sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4855 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004856{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004857 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004858 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004859 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004860 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004861 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4862 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004863 source = sourceDesc;
4864 break;
4865 }
4866 }
4867 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004868}
4869
Eric Laurent39095982021-08-24 18:29:27 +02004870/* static */
4871bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
4872 switch (channels) {
4873 case AUDIO_CHANNEL_OUT_5POINT1:
4874 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
4875 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
4876 case AUDIO_CHANNEL_OUT_7POINT1:
4877 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
4878 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
4879 return true;
4880 default:
4881 return false;
4882 }
4883}
4884
Eric Laurentfa0f6742021-08-17 18:39:44 +02004885bool AudioPolicyManager::canBeSpatialized(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004886 const audio_config_t *config,
4887 const AudioDeviceTypeAddrVector &devices) const
4888{
4889 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4890 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004891 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004892 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02004893 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
4894 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4895 return false;
4896 }
4897 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
4898 return false;
4899 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004900 }
4901
4902 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004903 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4904 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004905 // to the specified devices must exist.
4906 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004907 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004908 if (profile == nullptr) {
4909 return false;
4910 }
4911
4912 // The caller can have the audio config criteria ignored by either passing a null ptr or
4913 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004914 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02004915 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004916 // If the spatializer output is already opened, only channel masks included in the
4917 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02004918
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004919 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02004920 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004921 return false;
4922 }
Eric Laurent39095982021-08-24 18:29:27 +02004923 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004924 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004925 != config->channel_mask) {
4926 return false;
4927 }
4928 }
4929 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004930 return true;
4931}
4932
4933void AudioPolicyManager::checkVirtualizerClientRoutes() {
4934 std::set<audio_stream_type_t> streamsToInvalidate;
4935 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02004936 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
4937 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004938 audio_attributes_t attr = client->attributes();
4939 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4940 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4941 audio_config_base_t clientConfig = client->config();
4942 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02004943 if (desc != mSpatializerOutput
4944 && canBeSpatialized(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004945 streamsToInvalidate.insert(client->stream());
4946 }
4947 }
4948 }
4949
4950 for (audio_stream_type_t stream : streamsToInvalidate) {
4951 mpClientInterface->invalidateStream(stream);
4952 }
4953}
4954
Eric Laurentfa0f6742021-08-17 18:39:44 +02004955status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004956 const audio_attributes_t *attr,
4957 audio_io_handle_t *output) {
4958 *output = AUDIO_IO_HANDLE_NONE;
4959
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004960 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4961 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4962 audio_config_t *configPtr = nullptr;
4963 audio_config_t config;
4964 if (mixerConfig != nullptr) {
4965 config = audio_config_initializer(mixerConfig);
4966 configPtr = &config;
4967 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004968 if (!canBeSpatialized(attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02004969 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004970 return BAD_VALUE;
4971 }
4972
4973 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004974 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004975 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02004976 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004977 return BAD_VALUE;
4978 }
4979
Eric Laurent39095982021-08-24 18:29:27 +02004980 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
4981 && configPtr != nullptr
4982 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
4983 *output = mSpatializerOutput->mIoHandle;
4984 ALOGV("%s returns current spatializer output %d", __func__, *output);
4985 return NO_ERROR;
4986 }
4987 mSpatializerOutput.clear();
4988 for (size_t i = 0; i < mOutputs.size(); i++) {
4989 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4990 if (!desc->isDuplicated() && desc->mProfile == profile) {
4991 mSpatializerOutput = desc;
4992 break;
4993 }
4994 }
4995 if (mSpatializerOutput == nullptr) {
4996 ALOGW("%s no opened spatializer output for profile %s",
4997 __func__, profile->getName().c_str());
4998 return BAD_VALUE;
4999 }
5000
5001 if (configPtr != nullptr
5002 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5003 audio_config_base_t savedMixerConfig = {
5004 .sample_rate = mSpatializerOutput->getSamplingRate(),
5005 .format = mSpatializerOutput->getFormat(),
5006 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5007 };
5008 DeviceVector savedDevices = mSpatializerOutput->devices();
5009
5010 closeOutput(mSpatializerOutput->mIoHandle);
5011 mSpatializerOutput.clear();
5012
5013 const sp<SwAudioOutputDescriptor> desc =
5014 new SwAudioOutputDescriptor(profile, mpClientInterface);
5015 status_t status = desc->open(nullptr, mixerConfig, devices,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005016 mEngine->getStreamTypeForAttributes(*attr),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02005017 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
Eric Laurent39095982021-08-24 18:29:27 +02005018 if (status != NO_ERROR) {
5019 ALOGW("%s failed opening output: status %d, output %d", __func__, status, *output);
5020 if (*output != AUDIO_IO_HANDLE_NONE) {
5021 desc->close();
5022 }
5023 // re open the spatializer output with previous channel mask
5024 status_t newStatus = desc->open(nullptr, &savedMixerConfig, savedDevices,
5025 mEngine->getStreamTypeForAttributes(*attr),
5026 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
5027 if (newStatus != NO_ERROR) {
5028 if (*output != AUDIO_IO_HANDLE_NONE) {
5029 desc->close();
5030 }
5031 ALOGE("%s failed to re-open mSpatializerOutput, status %d", __func__, newStatus);
5032 } else {
5033 mSpatializerOutput = desc;
5034 addOutput(*output, desc);
5035 }
5036 mPreviousOutputs = mOutputs;
5037 mpClientInterface->onAudioPortListUpdate();
5038 *output = AUDIO_IO_HANDLE_NONE;
5039 return status;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005040 }
Eric Laurent39095982021-08-24 18:29:27 +02005041 mSpatializerOutput = desc;
5042 addOutput(*output, desc);
5043 mPreviousOutputs = mOutputs;
5044 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005045 }
5046
5047 checkVirtualizerClientRoutes();
5048
Eric Laurent39095982021-08-24 18:29:27 +02005049 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005050 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005051 return NO_ERROR;
5052}
5053
Eric Laurentfa0f6742021-08-17 18:39:44 +02005054status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5055 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005056 return INVALID_OPERATION;
5057 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005058 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005059 return BAD_VALUE;
5060 }
Eric Laurent39095982021-08-24 18:29:27 +02005061
Eric Laurentfa0f6742021-08-17 18:39:44 +02005062 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005063
5064 checkVirtualizerClientRoutes();
5065
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005066 return NO_ERROR;
5067}
5068
Eric Laurente552edb2014-03-10 17:42:56 -07005069// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005070// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005071// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005072uint32_t AudioPolicyManager::nextAudioPortGeneration()
5073{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005074 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005075}
5076
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005077static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005078 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5079 !audioPolicyXmlConfigFile.empty()) {
5080 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5081 if (ret == NO_ERROR) {
5082 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005083 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005084 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005085 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005086 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005087}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005088
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005089AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5090 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005091 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005092 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005093 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005094 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005095 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005096 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005097 mAudioPortGeneration(1),
5098 mBeaconMuteRefCount(0),
5099 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005100 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005101 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005102 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005103 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005104{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005105}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005106
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005107AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5108 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5109{
5110 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005111}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005112
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005113void AudioPolicyManager::loadConfig() {
5114 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005115 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005116 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005117 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005118 //TODO: b/193496180 use spatializer flag at audio HAL when available
5119 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005120}
5121
5122status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005123 {
5124 auto engLib = EngineLibrary::load(
5125 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5126 if (!engLib) {
5127 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5128 return NO_INIT;
5129 }
5130 mEngine = engLib->createEngine();
5131 if (mEngine == nullptr) {
5132 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5133 return NO_INIT;
5134 }
François Gaffie2110e042015-03-24 08:41:51 +01005135 }
5136 mEngine->setObserver(this);
5137 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005138 if (status != NO_ERROR) {
5139 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5140 return status;
5141 }
François Gaffie2110e042015-03-24 08:41:51 +01005142
Eric Laurent1d69c872021-01-11 18:53:01 +01005143 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5144 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5145
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005146 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005147 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005148 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005149
Eric Laurent3a4311c2014-03-17 12:00:47 -07005150 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005151 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5152 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5153 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005154 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005155 }
jiabin9ff780e2018-03-19 18:19:52 -07005156 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005157 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005158 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005159 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005160 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005161 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005162 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005163 }
5164 }
5165 }
Eric Laurente552edb2014-03-10 17:42:56 -07005166
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005167 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005168
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005169 // Silence ALOGV statements
5170 property_set("log.tag." LOG_TAG, "D");
5171
Eric Laurente552edb2014-03-10 17:42:56 -07005172 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005173 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005174}
5175
Eric Laurente0720872014-03-11 09:30:41 -07005176AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005177{
Eric Laurente552edb2014-03-10 17:42:56 -07005178 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005179 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005180 }
5181 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005182 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005184 mAvailableOutputDevices.clear();
5185 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005186 mOutputs.clear();
5187 mInputs.clear();
5188 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005189 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005190 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005191}
5192
Eric Laurente0720872014-03-11 09:30:41 -07005193status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005194{
Eric Laurent87ffa392015-05-22 10:32:38 -07005195 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005196}
5197
Eric Laurente552edb2014-03-10 17:42:56 -07005198// ---
5199
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005200void AudioPolicyManager::onNewAudioModulesAvailable()
5201{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005202 DeviceVector newDevices;
5203 onNewAudioModulesAvailableInt(&newDevices);
5204 if (!newDevices.empty()) {
5205 nextAudioPortGeneration();
5206 mpClientInterface->onAudioPortListUpdate();
5207 }
5208}
5209
5210void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5211{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005212 for (const auto& hwModule : mHwModulesAll) {
5213 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5214 continue;
5215 }
5216 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5217 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5218 ALOGW("could not open HW module %s", hwModule->getName());
5219 continue;
5220 }
5221 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005222 // open all output streams needed to access attached devices.
5223 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005224 // This also validates mAvailableOutputDevices list
5225 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5226 if (!outProfile->canOpenNewIo()) {
5227 ALOGE("Invalid Output profile max open count %u for profile %s",
5228 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5229 continue;
5230 }
5231 if (!outProfile->hasSupportedDevices()) {
5232 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5233 continue;
5234 }
5235 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5236 mTtsOutputAvailable = true;
5237 }
5238
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005239 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5240 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5241 sp<DeviceDescriptor> supportedDevice = 0;
5242 if (supportedDevices.contains(mDefaultOutputDevice)) {
5243 supportedDevice = mDefaultOutputDevice;
5244 } else {
5245 // choose first device present in profile's SupportedDevices also part of
5246 // mAvailableOutputDevices.
5247 if (availProfileDevices.isEmpty()) {
5248 continue;
5249 }
5250 supportedDevice = availProfileDevices.itemAt(0);
5251 }
5252 if (!mOutputDevicesAll.contains(supportedDevice)) {
5253 continue;
5254 }
5255 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5256 mpClientInterface);
5257 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005258 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5259 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005260 AUDIO_STREAM_DEFAULT,
5261 AUDIO_OUTPUT_FLAG_NONE, &output);
5262 if (status != NO_ERROR) {
5263 ALOGW("Cannot open output stream for devices %s on hw module %s",
5264 supportedDevice->toString().c_str(), hwModule->getName());
5265 continue;
5266 }
5267 for (const auto &device : availProfileDevices) {
5268 // give a valid ID to an attached device once confirmed it is reachable
5269 if (!device->isAttached()) {
5270 device->attach(hwModule);
5271 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005272 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005273 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005274 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5275 }
5276 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005277 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005278 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5279 mPrimaryOutput = outputDesc;
5280 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005281 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5282 outputDesc->close();
5283 } else {
5284 addOutput(output, outputDesc);
5285 setOutputDevices(outputDesc,
5286 DeviceVector(supportedDevice),
5287 true,
5288 0,
5289 NULL);
5290 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005291 }
5292 // open input streams needed to access attached devices to validate
5293 // mAvailableInputDevices list
5294 for (const auto& inProfile : hwModule->getInputProfiles()) {
5295 if (!inProfile->canOpenNewIo()) {
5296 ALOGE("Invalid Input profile max open count %u for profile %s",
5297 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5298 continue;
5299 }
5300 if (!inProfile->hasSupportedDevices()) {
5301 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5302 continue;
5303 }
5304 // chose first device present in profile's SupportedDevices also part of
5305 // available input devices
5306 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5307 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5308 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005309 ALOGV("%s: Input device list is empty! for profile %s",
5310 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005311 continue;
5312 }
5313 sp<AudioInputDescriptor> inputDesc =
5314 new AudioInputDescriptor(inProfile, mpClientInterface);
5315
5316 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5317 status_t status = inputDesc->open(nullptr,
5318 availProfileDevices.itemAt(0),
5319 AUDIO_SOURCE_MIC,
5320 AUDIO_INPUT_FLAG_NONE,
5321 &input);
5322 if (status != NO_ERROR) {
5323 ALOGW("Cannot open input stream for device %s on hw module %s",
5324 availProfileDevices.toString().c_str(),
5325 hwModule->getName());
5326 continue;
5327 }
5328 for (const auto &device : availProfileDevices) {
5329 // give a valid ID to an attached device once confirmed it is reachable
5330 if (!device->isAttached()) {
5331 device->attach(hwModule);
5332 device->importAudioPortAndPickAudioProfile(inProfile, true);
5333 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005334 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005335 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5336 }
5337 }
5338 inputDesc->close();
5339 }
5340 }
5341}
5342
Eric Laurent98e38192018-02-15 18:31:53 -08005343void AudioPolicyManager::addOutput(audio_io_handle_t output,
5344 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005345{
Eric Laurent1c333e22014-05-20 10:48:17 -07005346 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005347 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005348 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005349 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005351}
5352
François Gaffie53615e22015-03-19 09:24:12 +01005353void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5354{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005355 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5356 ALOGV("%s: removing primary output", __func__);
5357 mPrimaryOutput = nullptr;
5358 }
François Gaffie53615e22015-03-19 09:24:12 +01005359 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005360 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005361}
5362
Eric Laurent98e38192018-02-15 18:31:53 -08005363void AudioPolicyManager::addInput(audio_io_handle_t input,
5364 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005365{
Eric Laurent1c333e22014-05-20 10:48:17 -07005366 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005367 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005368}
Eric Laurente552edb2014-03-10 17:42:56 -07005369
François Gaffie11d30102018-11-02 16:09:09 +01005370status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005371 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005372 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005373{
François Gaffie11d30102018-11-02 16:09:09 +01005374 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005375 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005376 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005377
François Gaffie11d30102018-11-02 16:09:09 +01005378 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005379 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005380 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005381 }
Eric Laurente552edb2014-03-10 17:42:56 -07005382
Eric Laurent3b73df72014-03-11 09:06:29 -07005383 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005384 // first call getAudioPort to get the supported attributes from the HAL
5385 struct audio_port_v7 port = {};
5386 device->toAudioPort(&port);
5387 status_t status = mpClientInterface->getAudioPort(&port);
5388 if (status == NO_ERROR) {
5389 device->importAudioPort(port);
5390 }
5391
5392 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005393 for (size_t i = 0; i < mOutputs.size(); i++) {
5394 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005395 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005396 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005397 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5398 mOutputs.keyAt(i), device->toString().c_str());
5399 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005400 }
5401 }
5402 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005403 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005404 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005405 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5406 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005407 if (profile->supportsDevice(device)) {
5408 profiles.add(profile);
5409 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5410 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005411 }
5412 }
5413 }
5414
Eric Laurent7b279bb2015-12-14 10:18:23 -08005415 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005416
Eric Laurente552edb2014-03-10 17:42:56 -07005417 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005418 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005419 return BAD_VALUE;
5420 }
5421
5422 // open outputs for matching profiles if needed. Direct outputs are also opened to
5423 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5424 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005425 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005426
5427 // nothing to do if one output is already opened for this profile
5428 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005429 for (j = 0; j < outputs.size(); j++) {
5430 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005431 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005432 // matching profile: save the sample rates, format and channel masks supported
5433 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005434 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005435 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005436 }
Eric Laurente552edb2014-03-10 17:42:56 -07005437 break;
5438 }
5439 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005440 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005441 continue;
5442 }
5443
Eric Laurent3974e3b2017-12-07 17:58:43 -08005444 if (!profile->canOpenNewIo()) {
5445 ALOGW("Max Output number %u already opened for this profile %s",
5446 profile->maxOpenCount, profile->getTagName().c_str());
5447 continue;
5448 }
5449
Eric Laurent83efe1c2017-07-09 16:51:08 -07005450 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005451 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005452 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5453 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005454 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005455 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005456 profiles.removeAt(profile_index);
5457 profile_index--;
5458 } else {
5459 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005460 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005461 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005462 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5463 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005464 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005465 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005466
François Gaffie11d30102018-11-02 16:09:09 +01005467 if (device_distinguishes_on_address(deviceType)) {
5468 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5469 device->toString().c_str());
5470 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5471 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005472 }
Eric Laurente552edb2014-03-10 17:42:56 -07005473 ALOGV("checkOutputsForDevice(): adding output %d", output);
5474 }
5475 }
5476
5477 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005478 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005479 return BAD_VALUE;
5480 }
Eric Laurentd4692962014-05-05 18:13:44 -07005481 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005482 // check if one opened output is not needed any more after disconnecting one device
5483 for (size_t i = 0; i < mOutputs.size(); i++) {
5484 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005485 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005486 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005487 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005488 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005489 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005490 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005491 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5492 mOutputs.keyAt(i));
5493 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005494 }
Eric Laurente552edb2014-03-10 17:42:56 -07005495 }
5496 }
Eric Laurentd4692962014-05-05 18:13:44 -07005497 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005498 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005499 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5500 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005501 if (!profile->supportsDevice(device)) {
5502 continue;
5503 }
5504 ALOGV("checkOutputsForDevice(): "
5505 "clearing direct output profile %zu on module %s",
5506 j, hwModule->getName());
5507 profile->clearAudioProfiles();
5508 if (!profile->hasDynamicAudioProfile()) {
5509 continue;
5510 }
5511 // When a device is disconnected, if there is an IOProfile that contains dynamic
5512 // profiles and supports the disconnected device, call getAudioPort to repopulate
5513 // the capabilities of the devices that is supported by the IOProfile.
5514 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5515 if (supportedDevice == device ||
5516 !mAvailableOutputDevices.contains(supportedDevice)) {
5517 continue;
5518 }
5519 struct audio_port_v7 port;
5520 supportedDevice->toAudioPort(&port);
5521 status_t status = mpClientInterface->getAudioPort(&port);
5522 if (status == NO_ERROR) {
5523 supportedDevice->importAudioPort(port);
5524 }
Eric Laurente552edb2014-03-10 17:42:56 -07005525 }
5526 }
5527 }
5528 }
5529 return NO_ERROR;
5530}
5531
François Gaffie11d30102018-11-02 16:09:09 +01005532status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005533 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005534{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005535 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005536
François Gaffie11d30102018-11-02 16:09:09 +01005537 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005538 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005539 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005540 }
5541
Eric Laurentd4692962014-05-05 18:13:44 -07005542 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005543 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005544 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005545 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005546 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005547 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005548 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005549 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005550
François Gaffie11d30102018-11-02 16:09:09 +01005551 if (profile->supportsDevice(device)) {
5552 profiles.add(profile);
5553 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5554 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005555 }
5556 }
5557 }
5558
Eric Laurent0dd51852019-04-19 18:18:58 -07005559 if (profiles.isEmpty()) {
5560 ALOGW("%s: No input profile available for device %s",
5561 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005562 return BAD_VALUE;
5563 }
5564
5565 // open inputs for matching profiles if needed. Direct inputs are also opened to
5566 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5567 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5568
Eric Laurent1c333e22014-05-20 10:48:17 -07005569 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005570
Eric Laurentd4692962014-05-05 18:13:44 -07005571 // nothing to do if one input is already opened for this profile
5572 size_t input_index;
5573 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5574 desc = mInputs.valueAt(input_index);
5575 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005576 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005577 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005578 }
Eric Laurentd4692962014-05-05 18:13:44 -07005579 break;
5580 }
5581 }
5582 if (input_index != mInputs.size()) {
5583 continue;
5584 }
5585
Eric Laurent3974e3b2017-12-07 17:58:43 -08005586 if (!profile->canOpenNewIo()) {
5587 ALOGW("Max Input number %u already opened for this profile %s",
5588 profile->maxOpenCount, profile->getTagName().c_str());
5589 continue;
5590 }
5591
Eric Laurentfe231122017-11-17 17:48:06 -08005592 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005593 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005594 status_t status = desc->open(nullptr,
5595 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005596 AUDIO_SOURCE_MIC,
5597 AUDIO_INPUT_FLAG_NONE,
5598 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005599
Eric Laurentcf2c0212014-07-25 16:20:43 -07005600 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005601 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005602 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005603 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005604 mpClientInterface->setParameters(input, String8(param));
5605 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005606 }
François Gaffie11d30102018-11-02 16:09:09 +01005607 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005608 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005609 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005610 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005611 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005612 }
5613
Eric Laurent0dd51852019-04-19 18:18:58 -07005614 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005615 addInput(input, desc);
5616 }
5617 } // endif input != 0
5618
Eric Laurentcf2c0212014-07-25 16:20:43 -07005619 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005620 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005621 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005622 profiles.removeAt(profile_index);
5623 profile_index--;
5624 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005625 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005626 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005627 }
Eric Laurentd4692962014-05-05 18:13:44 -07005628 ALOGV("checkInputsForDevice(): adding input %d", input);
5629 }
5630 } // end scan profiles
5631
5632 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005633 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005634 return BAD_VALUE;
5635 }
5636 } else {
5637 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005638 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005639 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005640 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005641 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005642 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005643 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005644 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005645 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5646 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005647 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005648 }
5649 }
5650 }
5651 } // end disconnect
5652
5653 return NO_ERROR;
5654}
5655
5656
Eric Laurente0720872014-03-11 09:30:41 -07005657void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005658{
5659 ALOGV("closeOutput(%d)", output);
5660
François Gaffie1c878552018-11-22 16:53:21 +01005661 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5662 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005663 ALOGW("closeOutput() unknown output %d", output);
5664 return;
5665 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005666 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005667 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005668
Eric Laurente552edb2014-03-10 17:42:56 -07005669 // look for duplicated outputs connected to the output being removed.
5670 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005671 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5672 if (dupOutput->isDuplicated() &&
5673 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5674 sp<SwAudioOutputDescriptor> remainingOutput =
5675 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005676 // As all active tracks on duplicated output will be deleted,
5677 // and as they were also referenced on the other output, the reference
5678 // count for their stream type must be adjusted accordingly on
5679 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005680 const bool wasActive = remainingOutput->isActive();
5681 // Note: no-op on the closing output where all clients has already been set inactive
5682 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005683 // stop() will be a no op if the output is still active but is needed in case all
5684 // active streams refcounts where cleared above
5685 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005686 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005687 }
Eric Laurente552edb2014-03-10 17:42:56 -07005688 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5689 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5690
5691 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005692 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005693 }
5694 }
5695
Eric Laurent05b90f82014-08-27 15:32:29 -07005696 nextAudioPortGeneration();
5697
François Gaffie1c878552018-11-22 16:53:21 +01005698 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005699 if (index >= 0) {
5700 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005701 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5702 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005703 mAudioPatches.removeItemsAt(index);
5704 mpClientInterface->onAudioPatchListUpdate();
5705 }
5706
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005707 if (closingOutputWasActive) {
5708 closingOutput->stop();
5709 }
François Gaffie1c878552018-11-22 16:53:21 +01005710 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005711
François Gaffie53615e22015-03-19 09:24:12 +01005712 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005713 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005714
5715 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5716 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005717 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005718 bool directOutputOpen = false;
5719 for (size_t i = 0; i < mOutputs.size(); i++) {
5720 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5721 directOutputOpen = true;
5722 break;
5723 }
5724 }
5725 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005726 ALOGV("no direct outputs open, reset MSD patches");
5727 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5728 // how output devices for patching are resolved. Avoid by caching and reusing the
5729 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5730 // devices to patch to. This may be complicated by the fact that devices may become
5731 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005732 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005733 }
5734 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005735}
5736
5737void AudioPolicyManager::closeInput(audio_io_handle_t input)
5738{
5739 ALOGV("closeInput(%d)", input);
5740
5741 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5742 if (inputDesc == NULL) {
5743 ALOGW("closeInput() unknown input %d", input);
5744 return;
5745 }
5746
Eric Laurent6a94d692014-05-20 11:18:06 -07005747 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005748
François Gaffie11d30102018-11-02 16:09:09 +01005749 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005750 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005751 if (index >= 0) {
5752 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005753 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5754 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005755 mAudioPatches.removeItemsAt(index);
5756 mpClientInterface->onAudioPatchListUpdate();
5757 }
5758
Eric Laurentfe231122017-11-17 17:48:06 -08005759 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005760 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005761
François Gaffie11d30102018-11-02 16:09:09 +01005762 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5763 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005764 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005765 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005766 }
Eric Laurente552edb2014-03-10 17:42:56 -07005767}
5768
François Gaffie11d30102018-11-02 16:09:09 +01005769SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5770 const DeviceVector &devices,
5771 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005772{
5773 SortedVector<audio_io_handle_t> outputs;
5774
François Gaffie11d30102018-11-02 16:09:09 +01005775 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005776 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005777 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005778 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005779 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005780 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005781 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005782 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005783 outputs.add(openOutputs.keyAt(i));
5784 }
5785 }
5786 return outputs;
5787}
5788
Mikhail Naganov37977152018-07-11 15:54:44 -07005789void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5790{
5791 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5792 // output is suspended before any tracks are moved to it
5793 checkA2dpSuspend();
5794 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005795 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005796 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005797 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005798 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005799 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5800 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5801 // configuration changes will ultimately be rerouted correctly. We can still avoid
5802 // unnecessary rerouting by caching and reusing the arguments to
5803 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5804 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005805 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005806 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005807 // an event that changed routing likely occurred, inform upper layers
5808 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005809}
5810
François Gaffiec005e562018-11-06 15:04:49 +01005811bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5812 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005813{
François Gaffiec005e562018-11-06 15:04:49 +01005814 return mEngine->getProductStrategyForAttributes(lAttr) ==
5815 mEngine->getProductStrategyForAttributes(rAttr);
5816}
5817
Francois Gaffieff1eb522020-05-06 18:37:04 +02005818void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5819{
5820 for (size_t i = 0; i < mAudioSources.size(); i++) {
5821 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5822 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005823 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5824 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005825 connectAudioSource(sourceDesc);
5826 }
5827 }
5828}
5829
5830void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5831{
5832 for (size_t i = 0; i < mAudioSources.size(); i++) {
5833 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5834 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5835 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5836 disconnectAudioSource(sourceDesc);
5837 }
5838 }
5839}
5840
François Gaffiec005e562018-11-06 15:04:49 +01005841void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5842{
5843 auto psId = mEngine->getProductStrategyForAttributes(attr);
5844
5845 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5846 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005847
François Gaffie11d30102018-11-02 16:09:09 +01005848 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5849 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005850
Eric Laurentc209fe42020-06-05 18:11:23 -07005851 uint32_t maxLatency = 0;
5852 bool invalidate = false;
5853 // take into account dynamic audio policies related changes: if a client is now associated
5854 // to a different policy mix than at creation time, invalidate corresponding stream
5855 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5856 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5857 if (desc->isDuplicated()) {
5858 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005859 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005860 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5861 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5862 continue;
5863 }
5864 sp<AudioPolicyMix> primaryMix;
5865 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5866 client->flags(), primaryMix, nullptr);
5867 if (status != OK) {
5868 continue;
5869 }
yucliuf4de36d2020-09-14 14:57:56 -07005870 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005871 invalidate = true;
5872 if (desc->isStrategyActive(psId)) {
5873 maxLatency = desc->latency();
5874 }
5875 break;
5876 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005877 }
5878 }
5879
Eric Laurentc209fe42020-06-05 18:11:23 -07005880 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005881 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5882 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005883 for (audio_io_handle_t srcOut : srcOutputs) {
5884 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005885 if (desc == nullptr) continue;
5886
5887 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005888 maxLatency = desc->latency();
5889 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005890
5891 if (invalidate) continue;
5892
5893 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005894 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005895 // a client on a non direct outputs has necessarily a linear PCM format
5896 // so we can call selectOutput() safely
5897 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5898 client->flags(),
5899 client->config().format,
5900 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005901 client->config().sample_rate,
5902 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005903 if (newOutput != srcOut) {
5904 invalidate = true;
5905 break;
5906 }
5907 } else {
5908 sp<IOProfile> profile = getProfileForOutput(newDevices,
5909 client->config().sample_rate,
5910 client->config().format,
5911 client->config().channel_mask,
5912 client->flags(),
5913 true /* directOnly */);
5914 if (profile != desc->mProfile) {
5915 invalidate = true;
5916 break;
5917 }
5918 }
5919 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005920 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005921
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005922 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005923 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005924 std::to_string(srcOutputs[0]).c_str(),
5925 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005926 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005927 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005928 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005929 if (desc == nullptr) continue;
5930
5931 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005932 setStrategyMute(psId, true, desc);
5933 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005934 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005935 }
François Gaffiec005e562018-11-06 15:04:49 +01005936 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005937 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005938 connectAudioSource(source);
5939 }
Eric Laurente552edb2014-03-10 17:42:56 -07005940 }
5941
François Gaffiec005e562018-11-06 15:04:49 +01005942 // Move effects associated to this stream from previous output to new output
5943 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005944 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005945 }
François Gaffiec005e562018-11-06 15:04:49 +01005946 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005947 if (invalidate) {
5948 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5949 mpClientInterface->invalidateStream(stream);
5950 }
Eric Laurente552edb2014-03-10 17:42:56 -07005951 }
5952 }
5953}
5954
Eric Laurente0720872014-03-11 09:30:41 -07005955void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005956{
François Gaffiec005e562018-11-06 15:04:49 +01005957 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5958 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5959 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005960 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005961 }
Eric Laurente552edb2014-03-10 17:42:56 -07005962}
5963
Kevin Rocard153f92d2018-12-18 18:33:28 -08005964void AudioPolicyManager::checkSecondaryOutputs() {
5965 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005966 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005967 for (size_t i = 0; i < mOutputs.size(); i++) {
5968 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5969 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005970 sp<AudioPolicyMix> primaryMix;
5971 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005972 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005973 client->flags(), primaryMix, &secondaryMixes);
5974 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5975 for (auto &secondaryMix : secondaryMixes) {
5976 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5977 if (outputDesc != nullptr &&
5978 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5979 secondaryDescs.push_back(outputDesc);
5980 }
5981 }
5982
jiabinf042b9b2021-05-07 23:46:28 +00005983 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005984 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005985 } else if (!std::equal(
5986 client->getSecondaryOutputs().begin(),
5987 client->getSecondaryOutputs().end(),
5988 secondaryDescs.begin(), secondaryDescs.end())) {
jiabin64794372021-11-23 00:10:23 +00005989 if (!audio_is_linear_pcm(client->config().format)) {
5990 // If the format is not PCM, the tracks should be invalidated to get correct
5991 // behavior when the secondary output is changed.
5992 streamsToInvalidate.insert(client->stream());
5993 } else {
5994 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5995 std::vector<audio_io_handle_t> secondaryOutputIds;
5996 for (const auto &secondaryDesc: secondaryDescs) {
5997 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5998 weakSecondaryDescs.push_back(secondaryDesc);
5999 }
6000 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6001 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabinf042b9b2021-05-07 23:46:28 +00006002 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006003 }
6004 }
6005 }
jiabinf042b9b2021-05-07 23:46:28 +00006006 if (!trackSecondaryOutputs.empty()) {
6007 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6008 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006009 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00006010 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006011 mpClientInterface->invalidateStream(stream);
6012 }
6013}
6014
Eric Laurent2517af32020-11-25 15:31:27 +01006015bool AudioPolicyManager::isScoRequestedForComm() const {
6016 AudioDeviceTypeAddrVector devices;
6017 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6018 for (const auto &device : devices) {
6019 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6020 return true;
6021 }
6022 }
6023 return false;
6024}
6025
Eric Laurente0720872014-03-11 09:30:41 -07006026void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006027{
François Gaffie53615e22015-03-19 09:24:12 +01006028 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006029 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006030 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006031 return;
6032 }
6033
Eric Laurent3a4311c2014-03-17 12:00:47 -07006034 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006035 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6036 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006037 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006038
6039 // if suspended, restore A2DP output if:
6040 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006041 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006042 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006043 //
Eric Laurentf732e072016-08-03 19:30:28 -07006044 // if not suspended, suspend A2DP output if:
6045 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006046 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006047 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006048 //
6049 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006050 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006051 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006052 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006053 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006054
6055 mpClientInterface->restoreOutput(a2dpOutput);
6056 mA2dpSuspended = false;
6057 }
6058 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006059 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006060 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006061 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006062 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006063
6064 mpClientInterface->suspendOutput(a2dpOutput);
6065 mA2dpSuspended = true;
6066 }
6067 }
6068}
6069
François Gaffie11d30102018-11-02 16:09:09 +01006070DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6071 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006072{
François Gaffie11d30102018-11-02 16:09:09 +01006073 DeviceVector devices;
6074
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006075 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006076 if (index >= 0) {
6077 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006078 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006079 ALOGV("%s device %s forced by patch %d", __func__,
6080 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6081 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006082 }
6083 }
6084
Dean Wheatley514b4312020-06-17 21:45:00 +10006085 // Do not retrieve engine device for outputs through MSD
6086 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6087 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6088 return outputDesc->devices();
6089 }
6090
Eric Laurent97ac8712018-07-27 18:59:02 -07006091 // Honor explicit routing requests only if no client using default routing is active on this
6092 // input: a specific app can not force routing for other apps by setting a preferred device.
6093 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006094 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006095 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006096 if (device != nullptr) {
6097 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006098 }
6099
François Gaffiea807ef92018-11-05 10:44:33 +01006100 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6101 // of setForceUse / Default Bus device here
6102 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6103 if (device != nullptr) {
6104 return DeviceVector(device);
6105 }
6106
François Gaffiec005e562018-11-06 15:04:49 +01006107 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6108 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6109 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306110 auto hasStreamActive = [&](auto stream) {
6111 return hasStream(streams, stream) && isStreamActive(stream, 0);
6112 };
Eric Laurent484e9272018-06-07 17:29:23 -07006113
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306114 auto doGetOutputDevicesForVoice = [&]() {
6115 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006116 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306117 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006118 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6119 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306120 };
6121
6122 // With low-latency playing on speaker, music on WFD, when the first low-latency
6123 // output is stopped, getNewOutputDevices checks for a product strategy
6124 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006125 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306126 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6127 // stream is associated to the output descriptor.
6128 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6129 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6130 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6131 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006132 // Retrieval of devices for voice DL is done on primary output profile, cannot
6133 // check the route (would force modifying configuration file for this profile)
6134 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6135 break;
6136 }
Eric Laurente552edb2014-03-10 17:42:56 -07006137 }
François Gaffiec005e562018-11-06 15:04:49 +01006138 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006139 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006140}
6141
François Gaffie11d30102018-11-02 16:09:09 +01006142sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6143 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006144{
François Gaffie11d30102018-11-02 16:09:09 +01006145 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006146
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006147 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006148 if (index >= 0) {
6149 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006150 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006151 ALOGV("getNewInputDevice() device %s forced by patch %d",
6152 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6153 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006154 }
6155 }
6156
Eric Laurent97ac8712018-07-27 18:59:02 -07006157 // Honor explicit routing requests only if no client using default routing is active on this
6158 // input: a specific app can not force routing for other apps by setting a preferred device.
6159 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006160 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6161 if (device != nullptr) {
6162 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006163 }
6164
Eric Laurentdc95a252018-04-12 12:46:56 -07006165 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006166 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006167 audio_attributes_t attributes;
6168 uid_t uid;
6169 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6170 if (topClient != nullptr) {
6171 attributes = topClient->attributes();
6172 uid = topClient->uid();
6173 } else {
6174 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6175 uid = 0;
6176 }
6177
Francois Gaffie716e1432019-01-14 16:58:59 +01006178 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6179 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006180 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006181 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006182 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006183 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006184
Eric Laurente552edb2014-03-10 17:42:56 -07006185 return device;
6186}
6187
Eric Laurent794fde22016-03-11 09:50:45 -08006188bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6189 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006190 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006191}
6192
Eric Laurente0720872014-03-11 09:30:41 -07006193audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006194 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006195 // getOutputDevicesForStream's behavior for invalid streams.
6196 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6197 // device for music stream), but we want to return the empty set.
6198 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07006199 return AUDIO_DEVICE_NONE;
6200 }
François Gaffie11d30102018-11-02 16:09:09 +01006201 DeviceVector activeDevices;
6202 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006203 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6204 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006205 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006206 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006207 }
François Gaffiec005e562018-11-06 15:04:49 +01006208 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006209 devices.merge(curDevices);
6210 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006211 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006212 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01006213 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006214 }
6215 }
Eric Laurente552edb2014-03-10 17:42:56 -07006216 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006217
Eric Laurentb0688d62018-08-14 15:49:18 -07006218 // Favor devices selected on active streams if any to report correct device in case of
6219 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006220 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006221 devices = activeDevices;
6222 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006223 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6224 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006225 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006226 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006227 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006228 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006229 }
jiabin9a3361e2019-10-01 09:38:30 -07006230 // FIXME: use DeviceTypeSet when Java layer is ready for it.
6231 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006232}
6233
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006234status_t AudioPolicyManager::getDevicesForAttributes(
6235 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6236 if (devices == nullptr) {
6237 return BAD_VALUE;
6238 }
6239 // check dynamic policies but only for primary descriptors (secondary not used for audible
6240 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006241 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006242 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006243 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006244 if (status != OK) {
6245 return status;
6246 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006247 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6248 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6249 devices->push_back(device);
6250 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006251 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006252 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6253 for (const auto& device : curDevices) {
6254 devices->push_back(device->getDeviceTypeAddr());
6255 }
6256 return NO_ERROR;
6257}
6258
Eric Laurente0720872014-03-11 09:30:41 -07006259void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006260 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006261 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006262 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006263 updateDevicesAndOutputs();
6264 break;
6265 default:
6266 break;
6267 }
6268}
6269
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006270uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006271
6272 // skip beacon mute management if a dedicated TTS output is available
6273 if (mTtsOutputAvailable) {
6274 return 0;
6275 }
6276
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006277 switch(event) {
6278 case STARTING_OUTPUT:
6279 mBeaconMuteRefCount++;
6280 break;
6281 case STOPPING_OUTPUT:
6282 if (mBeaconMuteRefCount > 0) {
6283 mBeaconMuteRefCount--;
6284 }
6285 break;
6286 case STARTING_BEACON:
6287 mBeaconPlayingRefCount++;
6288 break;
6289 case STOPPING_BEACON:
6290 if (mBeaconPlayingRefCount > 0) {
6291 mBeaconPlayingRefCount--;
6292 }
6293 break;
6294 }
6295
6296 if (mBeaconMuteRefCount > 0) {
6297 // any playback causes beacon to be muted
6298 return setBeaconMute(true);
6299 } else {
6300 // no other playback: unmute when beacon starts playing, mute when it stops
6301 return setBeaconMute(mBeaconPlayingRefCount == 0);
6302 }
6303}
6304
6305uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6306 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6307 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6308 // keep track of muted state to avoid repeating mute/unmute operations
6309 if (mBeaconMuted != mute) {
6310 // mute/unmute AUDIO_STREAM_TTS on all outputs
6311 ALOGV("\t muting %d", mute);
6312 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006313 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6314 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6315 ALOGV("\t no tts volume source available");
6316 return 0;
6317 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006318 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006319 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006320 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006321 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006322 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006323 maxLatency = latency;
6324 }
6325 }
6326 mBeaconMuted = mute;
6327 return maxLatency;
6328 }
6329 return 0;
6330}
6331
Eric Laurente0720872014-03-11 09:30:41 -07006332void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006333{
François Gaffiec005e562018-11-06 15:04:49 +01006334 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006335 mPreviousOutputs = mOutputs;
6336}
6337
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006338uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006339 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006340 uint32_t delayMs)
6341{
6342 // mute/unmute strategies using an incompatible device combination
6343 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6344 // if unmuting, unmute only after the specified delay
6345 if (outputDesc->isDuplicated()) {
6346 return 0;
6347 }
6348
6349 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006350 DeviceVector devices = outputDesc->devices();
6351 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006352
François Gaffiec005e562018-11-06 15:04:49 +01006353 auto productStrategies = mEngine->getOrderedProductStrategies();
6354 for (const auto &productStrategy : productStrategies) {
6355 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6356 DeviceVector curDevices =
6357 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6358 curDevices = curDevices.filter(outputDesc->supportedDevices());
6359 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006360 bool doMute = false;
6361
François Gaffiec005e562018-11-06 15:04:49 +01006362 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006363 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006364 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6365 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006366 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006367 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006368 }
Eric Laurent99401132014-05-07 19:48:15 -07006369 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006370 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006371 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006372 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006373 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006374 continue;
6375 }
François Gaffiec005e562018-11-06 15:04:49 +01006376 ALOGVV("%s() %s (curDevice %s)", __func__,
6377 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6378 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6379 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006380 if (mute) {
6381 // FIXME: should not need to double latency if volume could be applied
6382 // immediately by the audioflinger mixer. We must account for the delay
6383 // between now and the next time the audioflinger thread for this output
6384 // will process a buffer (which corresponds to one buffer size,
6385 // usually 1/2 or 1/4 of the latency).
6386 if (muteWaitMs < desc->latency() * 2) {
6387 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006388 }
6389 }
6390 }
6391 }
6392 }
6393 }
6394
Eric Laurent99401132014-05-07 19:48:15 -07006395 // temporary mute output if device selection changes to avoid volume bursts due to
6396 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006397 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006398 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6399 // temporary mute duration is conservatively set to 4 times the reported latency
6400 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6401 if (muteWaitMs < tempMuteWaitMs) {
6402 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006403 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006404 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6405 // make sure that we do not start the temporary mute period too early in case of
6406 // delayed device change
6407 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6408 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006409 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006410 }
6411 }
6412
Eric Laurente552edb2014-03-10 17:42:56 -07006413 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6414 if (muteWaitMs > delayMs) {
6415 muteWaitMs -= delayMs;
6416 usleep(muteWaitMs * 1000);
6417 return muteWaitMs;
6418 }
6419 return 0;
6420}
6421
François Gaffie11d30102018-11-02 16:09:09 +01006422uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6423 const DeviceVector &devices,
6424 bool force,
6425 int delayMs,
6426 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006427 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006428{
François Gaffie11d30102018-11-02 16:09:09 +01006429 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006430 uint32_t muteWaitMs;
6431
6432 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006433 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6434 nullptr /* patchHandle */, requiresMuteCheck);
6435 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6436 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006437 return muteWaitMs;
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439
6440 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006441 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006442 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006443 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006444
François Gaffie11d30102018-11-02 16:09:09 +01006445 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6446
6447 if (!filteredDevices.isEmpty()) {
6448 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006449 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006450
6451 // if the outputs are not materially active, there is no need to mute.
6452 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006453 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006454 } else {
6455 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6456 muteWaitMs = 0;
6457 }
Eric Laurente552edb2014-03-10 17:42:56 -07006458
Eric Laurent79ea9582020-06-11 18:49:24 -07006459 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6460 // output profile or if new device is not supported AND previous device(s) is(are) still
6461 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006462 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006463 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6464 // restore previous device after evaluating strategy mute state
6465 outputDesc->setDevices(prevDevices);
6466 return muteWaitMs;
6467 }
6468
Eric Laurente552edb2014-03-10 17:42:56 -07006469 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006470 // the requested device is AUDIO_DEVICE_NONE
6471 // OR the requested device is the same as current device
6472 // AND force is not specified
6473 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006474 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006475 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
Francois Gaffie3523ab32021-06-22 13:24:34 +02006476 !force && outputDesc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006477 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6478 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006479 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6480 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6481 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6482 }
Eric Laurente552edb2014-03-10 17:42:56 -07006483 return muteWaitMs;
6484 }
6485
François Gaffie11d30102018-11-02 16:09:09 +01006486 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006487
Eric Laurente552edb2014-03-10 17:42:56 -07006488 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006489 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006490 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006491 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006492 PatchBuilder patchBuilder;
6493 patchBuilder.addSource(outputDesc);
6494 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6495 for (const auto &filteredDevice : filteredDevices) {
6496 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006497 }
6498
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006499 // Add half reported latency to delayMs when muteWaitMs is null in order
6500 // to avoid disordered sequence of muting volume and changing devices.
6501 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6502 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006503 }
Eric Laurente552edb2014-03-10 17:42:56 -07006504
6505 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006506 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006507
6508 return muteWaitMs;
6509}
6510
Eric Laurentc75307b2015-03-17 15:29:32 -07006511status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006512 int delayMs,
6513 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006514{
Eric Laurent6a94d692014-05-20 11:18:06 -07006515 ssize_t index;
6516 if (patchHandle) {
6517 index = mAudioPatches.indexOfKey(*patchHandle);
6518 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006519 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006520 }
6521 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006522 return INVALID_OPERATION;
6523 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006524 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006525 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006526 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006527 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006528 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006529 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006530 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006531 return status;
6532}
6533
6534status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006535 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006536 bool force,
6537 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006538{
6539 status_t status = NO_ERROR;
6540
Eric Laurent1f2f2232014-06-02 12:01:23 -07006541 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006542 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6543 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006544
François Gaffie11d30102018-11-02 16:09:09 +01006545 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006546 PatchBuilder patchBuilder;
6547 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006548 // AUDIO_SOURCE_HOTWORD is for internal use only:
6549 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006550 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6551 auto result = usecase;
6552 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6553 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6554 }
6555 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006556 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006557 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006558 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006559 }
6560 }
6561 return status;
6562}
6563
Eric Laurent6a94d692014-05-20 11:18:06 -07006564status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6565 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006566{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006567 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006568 ssize_t index;
6569 if (patchHandle) {
6570 index = mAudioPatches.indexOfKey(*patchHandle);
6571 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006572 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006573 }
6574 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006575 return INVALID_OPERATION;
6576 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006577 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006578 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006579 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006580 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006581 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006582 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006583 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006584 return status;
6585}
6586
François Gaffie11d30102018-11-02 16:09:09 +01006587sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006588 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006589 audio_format_t& format,
6590 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006591 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006592{
6593 // Choose an input profile based on the requested capture parameters: select the first available
6594 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006595 //
6596 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6597 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006598
Glenn Kasten730b9262018-03-29 15:01:26 -07006599 sp<IOProfile> firstInexact;
6600 uint32_t updatedSamplingRate = 0;
6601 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6602 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006603 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006604 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006605 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006606 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006607 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006608 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006609 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006610 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006611 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006612 &channelMask /*updatedChannelMask*/,
6613 // FIXME ugly cast
6614 (audio_output_flags_t) flags,
6615 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006616 return profile;
6617 }
François Gaffie11d30102018-11-02 16:09:09 +01006618 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006619 samplingRate,
6620 &updatedSamplingRate,
6621 format,
6622 &updatedFormat,
6623 channelMask,
6624 &updatedChannelMask,
6625 // FIXME ugly cast
6626 (audio_output_flags_t) flags,
6627 false /*exactMatchRequiredForInputFlags*/)) {
6628 firstInexact = profile;
6629 }
6630
Eric Laurente552edb2014-03-10 17:42:56 -07006631 }
6632 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006633 if (firstInexact != nullptr) {
6634 samplingRate = updatedSamplingRate;
6635 format = updatedFormat;
6636 channelMask = updatedChannelMask;
6637 return firstInexact;
6638 }
Eric Laurente552edb2014-03-10 17:42:56 -07006639 return NULL;
6640}
6641
François Gaffieaaac0fd2018-11-22 17:56:39 +01006642float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6643 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006644 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006645 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006646{
jiabin9a3361e2019-10-01 09:38:30 -07006647 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006648
6649 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6650 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6651 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6652 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006653 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6654 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
6655 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
6656 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
6657 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006658
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006659 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006660 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6661 mOutputs.isActive(ringVolumeSrc, 0)) {
6662 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006663 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006664 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006665 }
6666
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006667 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006668 if ((volumeSource != callVolumeSrc && (isInCall() ||
6669 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006670 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006671 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6672 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006673 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
6674 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
6675 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006676 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006677 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006678 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006679 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006680 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006681 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006682 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6683 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6684 // programmatically muted.
6685 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6686 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6687 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006688 bool exemptFromCapping =
6689 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6690 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006691 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6692 volumeSource, volumeDb);
6693 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006694 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6695 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6696 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006697 }
6698 }
Eric Laurente552edb2014-03-10 17:42:56 -07006699 // if a headset is connected, apply the following rules to ring tones and notifications
6700 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006701 // - always attenuate notifications volume by 6dB
6702 // - attenuate ring tones volume by 6dB unless music is not playing and
6703 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006704 // - if music is playing, always limit the volume to current music volume,
6705 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006706 if (!Intersection(deviceTypes,
6707 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6708 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006709 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6710 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006711 ((volumeSource == alarmVolumeSrc ||
6712 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006713 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
6714 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
6715 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006716 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6717 curves.canBeMuted()) {
6718
Eric Laurente552edb2014-03-10 17:42:56 -07006719 // when the phone is ringing we must consider that music could have been paused just before
6720 // by the music application and behave as if music was active if the last music track was
6721 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006722 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006723 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006724 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006725 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006726 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6727 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006728 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006729 float musicVolDb = computeVolume(musicCurves,
6730 musicVolumeSrc,
6731 musicCurves.getVolumeIndex(musicDevice),
6732 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006733 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6734 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6735 if (volumeDb > minVolDb) {
6736 volumeDb = minVolDb;
6737 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006738 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006739 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6740 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6741 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006742 // on A2DP, also ensure notification volume is not too low compared to media when
6743 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006744 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006745 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006746 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6747 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006748 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6749 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006750 }
6751 }
jiabin9a3361e2019-10-01 09:38:30 -07006752 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006753 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006754 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006755 }
6756 }
6757
François Gaffie43c73442018-11-08 08:21:55 +01006758 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006759}
6760
Eric Laurent3839bc02018-07-10 18:33:34 -07006761int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006762 VolumeSource fromVolumeSource,
6763 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006764{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006765 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006766 return srcIndex;
6767 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006768 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6769 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006770 float minSrc = (float)srcCurves.getVolumeIndexMin();
6771 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6772 float minDst = (float)dstCurves.getVolumeIndexMin();
6773 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006774
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006775 // preserve mute request or correct range
6776 if (srcIndex < minSrc) {
6777 if (srcIndex == 0) {
6778 return 0;
6779 }
6780 srcIndex = minSrc;
6781 } else if (srcIndex > maxSrc) {
6782 srcIndex = maxSrc;
6783 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006784 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6785}
6786
François Gaffieaaac0fd2018-11-22 17:56:39 +01006787status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6788 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006789 int index,
6790 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006791 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006792 int delayMs,
6793 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006794{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006795 // do not change actual attributes volume if the attributes is muted
6796 if (outputDesc->isMuted(volumeSource)) {
6797 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6798 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006799 return NO_ERROR;
6800 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006801 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6802 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
6803 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
6804 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006805
Eric Laurent2517af32020-11-25 15:31:27 +01006806 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006807 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006808 // if sco and call follow same curves, bypass forceUseForComm
6809 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006810 ((isVoiceVolSrc && isScoRequested) ||
6811 (isBtScoVolSrc && !isScoRequested))) {
6812 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6813 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006814 // Do not return an error here as AudioService will always set both voice call
6815 // and bluetooth SCO volumes due to stream aliasing.
6816 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006817 }
jiabin9a3361e2019-10-01 09:38:30 -07006818 if (deviceTypes.empty()) {
6819 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006820 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006821
jiabin9a3361e2019-10-01 09:38:30 -07006822 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6823 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006824 // Force VoIP volume to max for bluetooth SCO device except if muted
6825 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006826 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006827 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006828 }
Francois Gaffie593634d2021-06-22 13:31:31 +02006829 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07006830 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02006831 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006832
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006833 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006834 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006835 // 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 +01006836 if (isVoiceVolSrc) {
6837 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006838 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006839 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006840 }
Eric Laurent18fba842016-03-31 14:41:26 -07006841 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006842 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6843 mLastVoiceVolume = voiceVolume;
6844 }
6845 }
Eric Laurente552edb2014-03-10 17:42:56 -07006846 return NO_ERROR;
6847}
6848
Eric Laurentc75307b2015-03-17 15:29:32 -07006849void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006850 const DeviceTypeSet& deviceTypes,
6851 int delayMs,
6852 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006853{
jiabincd510522020-01-22 09:40:55 -08006854 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006855 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6856 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6857 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006858 curves.getVolumeIndex(deviceTypes),
6859 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006860 }
6861}
6862
François Gaffiec005e562018-11-06 15:04:49 +01006863void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6864 bool on,
6865 const sp<AudioOutputDescriptor>& outputDesc,
6866 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006867 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006868{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006869 std::vector<VolumeSource> sourcesToMute;
6870 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6871 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6872 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006873 VolumeSource source = toVolumeSource(attributes, false);
6874 if ((source != VOLUME_SOURCE_NONE) &&
6875 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
6876 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006877 sourcesToMute.push_back(source);
6878 }
Eric Laurente552edb2014-03-10 17:42:56 -07006879 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006880 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006881 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006882 }
6883
Eric Laurente552edb2014-03-10 17:42:56 -07006884}
6885
François Gaffieaaac0fd2018-11-22 17:56:39 +01006886void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6887 bool on,
6888 const sp<AudioOutputDescriptor>& outputDesc,
6889 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006890 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006891{
jiabin9a3361e2019-10-01 09:38:30 -07006892 if (deviceTypes.empty()) {
6893 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006894 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006895 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006896 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006897 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006898 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006899 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006900 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6901 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006902 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006903 }
6904 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006905 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6906 // ignored
6907 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006908 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006909 if (!outputDesc->isMuted(volumeSource)) {
6910 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006911 return;
6912 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006913 if (outputDesc->decMuteCount(volumeSource) == 0) {
6914 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006915 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006916 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006917 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006918 delayMs);
6919 }
6920 }
6921}
6922
François Gaffie53615e22015-03-19 09:24:12 +01006923bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6924{
François Gaffiec005e562018-11-06 15:04:49 +01006925 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006926 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6927 return true;
6928 }
6929
6930 // has known usage?
6931 switch (paa->usage) {
6932 case AUDIO_USAGE_UNKNOWN:
6933 case AUDIO_USAGE_MEDIA:
6934 case AUDIO_USAGE_VOICE_COMMUNICATION:
6935 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6936 case AUDIO_USAGE_ALARM:
6937 case AUDIO_USAGE_NOTIFICATION:
6938 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6939 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6940 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6941 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6942 case AUDIO_USAGE_NOTIFICATION_EVENT:
6943 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6944 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6945 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6946 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006947 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006948 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006949 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006950 case AUDIO_USAGE_EMERGENCY:
6951 case AUDIO_USAGE_SAFETY:
6952 case AUDIO_USAGE_VEHICLE_STATUS:
6953 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006954 break;
6955 default:
6956 return false;
6957 }
6958 return true;
6959}
6960
François Gaffie2110e042015-03-24 08:41:51 +01006961audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6962{
6963 return mEngine->getForceUse(usage);
6964}
6965
6966bool AudioPolicyManager::isInCall()
6967{
6968 return isStateInCall(mEngine->getPhoneState());
6969}
6970
6971bool AudioPolicyManager::isStateInCall(int state)
6972{
6973 return is_state_in_call(state);
6974}
6975
Eric Laurent74b71512019-11-06 17:21:57 -08006976bool AudioPolicyManager::isCallAudioAccessible()
6977{
6978 audio_mode_t mode = mEngine->getPhoneState();
6979 return (mode == AUDIO_MODE_IN_CALL)
6980 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6981 || (mode == AUDIO_MODE_CALL_SCREEN);
6982}
6983
Eric Laurentd60560a2015-04-10 11:31:20 -07006984void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6985{
6986 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006987 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006988 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006989 sourceDesc->sinkDevice()->equals(deviceDesc))
6990 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006991 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006992 }
6993 }
6994
6995 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6996 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6997 bool release = false;
6998 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6999 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7000 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7001 source->ext.device.type == deviceDesc->type()) {
7002 release = true;
7003 }
7004 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007005 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007006 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7007 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7008 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007009 sink->ext.device.type == deviceDesc->type() &&
7010 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7011 || strncmp(sink->ext.device.address, address,
7012 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007013 release = true;
7014 }
7015 }
7016 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007017 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7018 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007019 }
7020 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007021
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007022 mInputs.clearSessionRoutesForDevice(deviceDesc);
7023
Francois Gaffie716e1432019-01-14 16:58:59 +01007024 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007025}
7026
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007027void AudioPolicyManager::modifySurroundFormats(
7028 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007029 std::unordered_set<audio_format_t> enforcedSurround(
7030 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007031 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7032 for (const auto& pair : mConfig.getSurroundFormats()) {
7033 allSurround.insert(pair.first);
7034 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7035 }
Phil Burk09bc4612016-02-24 15:58:15 -08007036
7037 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7038 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007039 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007040 // This is the resulting set of formats depending on the surround mode:
7041 // 'all surround' = allSurround
7042 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7043 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7044 // 'manual surround' = mManualSurroundFormats
7045 // AUTO: formats v 'enforced surround'
7046 // ALWAYS: formats v 'all surround' v 'enforced surround'
7047 // NEVER: formats ^ 'non-surround'
7048 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007049
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007050 std::unordered_set<audio_format_t> formatSet;
7051 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7052 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007053 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007054 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007055 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007056 formatSet.insert(*formatIter);
7057 }
7058 }
7059 } else {
7060 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7061 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007062 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007063
jiabin81772902018-04-02 17:52:27 -07007064 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007065 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007066 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7067 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7068 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007069 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007070 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7071 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7072 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007073 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007074 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007075 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007076 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007077 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007078 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007079}
7080
jiabin06e4bab2019-07-29 10:13:34 -07007081void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7082 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007083 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7084 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7085
7086 // If NEVER, then remove support for channelMasks > stereo.
7087 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007088 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7089 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007090 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007091 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007092 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007093 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007094 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007095 }
7096 }
jiabin81772902018-04-02 17:52:27 -07007097 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7098 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7099 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007100 bool supports5dot1 = false;
7101 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007102 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007103 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7104 supports5dot1 = true;
7105 break;
7106 }
7107 }
7108 // If not then add 5.1 support.
7109 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007110 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007111 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007112 }
Phil Burk09bc4612016-02-24 15:58:15 -08007113 }
7114}
7115
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007116void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007117 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007118 AudioProfileVector &profiles)
7119{
7120 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007121 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007122
François Gaffie112b0af2015-11-19 16:13:25 +01007123 // Format MUST be checked first to update the list of AudioProfile
7124 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007125 reply = mpClientInterface->getParameters(
7126 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007127 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007128 AudioParameter repliedParameters(reply);
7129 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007130 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007131 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7132 return;
7133 }
Phil Burk09bc4612016-02-24 15:58:15 -08007134 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007135 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007136 if (device == AUDIO_DEVICE_OUT_HDMI
7137 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007138 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007139 }
jiabin3e277cc2019-09-10 14:27:34 -07007140 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007141 }
François Gaffie112b0af2015-11-19 16:13:25 +01007142
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007143 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007144 ChannelMaskSet channelMasks;
7145 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007146 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007147 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007148
7149 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007150 reply = mpClientInterface->getParameters(
7151 ioHandle,
7152 requestedParameters.toString() + ";" +
7153 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007154 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007155 AudioParameter repliedParameters(reply);
7156 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007157 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007158 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007159 }
7160 }
7161 if (profiles.hasDynamicChannelsFor(format)) {
7162 reply = mpClientInterface->getParameters(ioHandle,
7163 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007164 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007165 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007166 AudioParameter repliedParameters(reply);
7167 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007168 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007169 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007170 if (device == AUDIO_DEVICE_OUT_HDMI
7171 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007172 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007173 }
François Gaffie112b0af2015-11-19 16:13:25 +01007174 }
7175 }
jiabin3e277cc2019-09-10 14:27:34 -07007176 addDynamicAudioProfileAndSort(
7177 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007178 }
7179}
Eric Laurentd60560a2015-04-10 11:31:20 -07007180
Mikhail Naganovdc769682018-05-04 15:34:08 -07007181status_t AudioPolicyManager::installPatch(const char *caller,
7182 audio_patch_handle_t *patchHandle,
7183 AudioIODescriptorInterface *ioDescriptor,
7184 const struct audio_patch *patch,
7185 int delayMs)
7186{
7187 ssize_t index = mAudioPatches.indexOfKey(
7188 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7189 *patchHandle : ioDescriptor->getPatchHandle());
7190 sp<AudioPatch> patchDesc;
7191 status_t status = installPatch(
7192 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7193 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007194 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007195 }
7196 return status;
7197}
7198
7199status_t AudioPolicyManager::installPatch(const char *caller,
7200 ssize_t index,
7201 audio_patch_handle_t *patchHandle,
7202 const struct audio_patch *patch,
7203 int delayMs,
7204 uid_t uid,
7205 sp<AudioPatch> *patchDescPtr)
7206{
7207 sp<AudioPatch> patchDesc;
7208 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7209 if (index >= 0) {
7210 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007211 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007212 }
7213
7214 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7215 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7216 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7217 if (status == NO_ERROR) {
7218 if (index < 0) {
7219 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007220 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007221 } else {
7222 patchDesc->mPatch = *patch;
7223 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007224 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007225 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007226 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007227 }
7228 nextAudioPortGeneration();
7229 mpClientInterface->onAudioPatchListUpdate();
7230 }
7231 if (patchDescPtr) *patchDescPtr = patchDesc;
7232 return status;
7233}
7234
jiabinbce0c1d2020-10-05 11:20:18 -07007235bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7236{
7237 const TrackClientVector activeClients = output->getActiveClients();
7238 if (activeClients.empty()) {
7239 return true;
7240 }
7241 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7242 if (index < 0) {
7243 ALOGE("%s, no audio patch found while there are active clients on output %d",
7244 __func__, output->getId());
7245 return false;
7246 }
7247 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7248 DeviceVector routedDevices;
7249 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7250 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7251 patchDesc->mPatch.sinks[i].id);
7252 if (device == nullptr) {
7253 ALOGE("%s, no audio device found with id(%d)",
7254 __func__, patchDesc->mPatch.sinks[i].id);
7255 return false;
7256 }
7257 routedDevices.add(device);
7258 }
7259 for (const auto& client : activeClients) {
7260 // TODO: b/175343099 only travel the valid client
7261 sp<DeviceDescriptor> preferredDevice =
7262 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7263 if (mEngine->getOutputDevicesForAttributes(
7264 client->attributes(), preferredDevice, false) == routedDevices) {
7265 return false;
7266 }
7267 }
7268 return true;
7269}
7270
7271sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7272 const sp<IOProfile>& profile, const DeviceVector& devices)
7273{
7274 for (const auto& device : devices) {
7275 // TODO: This should be checking if the profile supports the device combo.
7276 if (!profile->supportsDevice(device)) {
7277 return nullptr;
7278 }
7279 }
7280 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7281 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02007282 status_t status = desc->open(nullptr /* halConfig */, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007283 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7284 if (status != NO_ERROR) {
7285 return nullptr;
7286 }
7287
7288 // Here is where the out_set_parameters() for card & device gets called
7289 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7290 const audio_devices_t deviceType = device->type();
7291 const String8 &address = String8(device->address().c_str());
7292 if (!address.isEmpty()) {
7293 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7294 mpClientInterface->setParameters(output, String8(param));
7295 free(param);
7296 }
7297 updateAudioProfiles(device, output, profile->getAudioProfiles());
7298 if (!profile->hasValidAudioProfile()) {
7299 ALOGW("%s() missing param", __func__);
7300 desc->close();
7301 return nullptr;
7302 } else if (profile->hasDynamicAudioProfile()) {
7303 desc->close();
7304 output = AUDIO_IO_HANDLE_NONE;
7305 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7306 profile->pickAudioProfile(
7307 config.sample_rate, config.channel_mask, config.format);
7308 config.offload_info.sample_rate = config.sample_rate;
7309 config.offload_info.channel_mask = config.channel_mask;
7310 config.offload_info.format = config.format;
7311
Eric Laurentf1f22e72021-07-13 14:04:14 +02007312 status = desc->open(&config, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007313 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7314 if (status != NO_ERROR) {
7315 return nullptr;
7316 }
7317 }
7318
7319 addOutput(output, desc);
7320 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7321 sp<AudioPolicyMix> policyMix;
7322 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7323 policyMix->setOutput(desc);
7324 desc->mPolicyMix = policyMix;
7325 } else {
7326 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7327 address.string());
7328 }
7329
7330 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7331 // no duplicated output for direct outputs and
7332 // outputs used by dynamic policy mixes
7333 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7334
7335 //TODO: configure audio effect output stage here
7336
7337 // open a duplicating output thread for the new output and the primary output
7338 sp<SwAudioOutputDescriptor> dupOutputDesc =
7339 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7340 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7341 if (status == NO_ERROR) {
7342 // add duplicated output descriptor
7343 addOutput(duplicatedOutput, dupOutputDesc);
7344 } else {
7345 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7346 mPrimaryOutput->mIoHandle, output);
7347 desc->close();
7348 removeOutput(output);
7349 nextAudioPortGeneration();
7350 return nullptr;
7351 }
7352 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007353 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7354 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7355 mPrimaryOutput = desc;
7356 }
jiabinbce0c1d2020-10-05 11:20:18 -07007357 return desc;
7358}
7359
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007360} // namespace android