blob: 3b0a63398cd72c2e002d5630338ba1535c5f8fec [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;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11001058 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1059 .channel_mask = config->channel_mask,
1060 .format = config->format,
1061 };
1062 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1063 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001064 if (status != OK) {
1065 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001066 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001067
Kevin Rocard153f92d2018-12-18 18:33:28 -08001068 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001069 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001070
1071 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11001072 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1073 && !audio_is_linear_pcm(config->format)) {
1074 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001075 return BAD_VALUE;
1076 }
1077 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001078 sp<DeviceDescriptor> deviceDesc =
1079 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1080 primaryMix->mDeviceAddress,
1081 AUDIO_FORMAT_DEFAULT);
1082 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001083 bool tryDirectForFlags = policyDesc == nullptr ||
1084 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1085 // if a direct output can be opened to deliver the track's multi-channel content to the
1086 // output rather than being downmixed by the primary output, then use this direct
1087 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1088 // mix.
1089 bool tryDirectForChannelMask = policyDesc != nullptr
1090 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1091 audio_channel_count_from_out_mask(config->channel_mask));
1092 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001093 audio_io_handle_t newOutput;
1094 status = openDirectOutput(
1095 *stream, session, config,
1096 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1097 DeviceVector(deviceDesc), &newOutput);
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001098 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001099 policyDesc = mOutputs.valueFor(newOutput);
1100 primaryMix->setOutput(policyDesc);
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001101 } else if (tryDirectForFlags) {
1102 policyDesc = nullptr;
1103 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001104 }
1105 if (policyDesc != nullptr) {
1106 policyDesc->mPolicyMix = primaryMix;
1107 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001108 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001109
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001110 ALOGV("getOutputForAttr() returns output %d", *output);
1111 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1112 *outputType = API_OUT_MIX_PLAYBACK;
1113 } else {
1114 *outputType = API_OUTPUT_LEGACY;
1115 }
1116 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001117 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001118 }
François Gaffiec005e562018-11-06 15:04:49 +01001119 // Virtual sources must always be dynamicaly or explicitly routed
1120 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1121 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1122 return BAD_VALUE;
1123 }
1124 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1125 // in order to let the choice of the order to future vendor engine
1126 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001127
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001128 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001129 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001130 }
1131
Nadav Barb2f18162018-07-18 13:01:53 +03001132 // Set incall music only if device was explicitly set, and fallback to the device which is
1133 // chosen by the engine if not.
1134 // FIXME: provide a more generic approach which is not device specific and move this back
1135 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001136 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001137 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001138 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001139 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001140 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001141 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001142 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001143 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001144 }
1145 }
1146
François Gaffiec005e562018-11-06 15:04:49 +01001147 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1148 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1149 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001150
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001151 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001152 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001153 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001154 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001155 ALOGV("%s() Using MSD devices %s instead of devices %s",
1156 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001157 } else {
1158 *output = AUDIO_IO_HANDLE_NONE;
1159 }
1160 }
1161 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001162 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001163 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001164 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001165 if (*output == AUDIO_IO_HANDLE_NONE) {
1166 return INVALID_OPERATION;
1167 }
Paul McLeanaa981192015-03-21 09:55:15 -07001168
François Gaffiec005e562018-11-06 15:04:49 +01001169 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001170 for (auto &outputDevice : outputDevices) {
1171 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1172 *selectedDeviceId = outputDevice->getId();
1173 break;
1174 }
1175 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001176
Eric Laurent8a1095a2019-11-08 14:44:16 -08001177 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1178 *outputType = API_OUTPUT_TELEPHONY_TX;
1179 } else {
1180 *outputType = API_OUTPUT_LEGACY;
1181 }
1182
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1184
1185 return NO_ERROR;
1186}
1187
1188status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1189 audio_io_handle_t *output,
1190 audio_session_t session,
1191 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001192 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001193 const audio_config_t *config,
1194 audio_output_flags_t *flags,
1195 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001196 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001197 std::vector<audio_io_handle_t> *secondaryOutputs,
1198 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001199{
1200 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1201 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1202 return INVALID_OPERATION;
1203 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001204 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001205 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001206 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001208 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001210 const sp<DeviceDescriptor> requestedDevice =
1211 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1212
1213 // Prevent from storing invalid requested device id in clients
1214 const audio_port_handle_t sanitizedRequestedPortId =
1215 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1216 *selectedDeviceId = sanitizedRequestedPortId;
1217
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001218 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001221 if (status != NO_ERROR) {
1222 return status;
1223 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001224 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001225 if (secondaryOutputs != nullptr) {
1226 for (auto &secondaryMix : secondaryMixes) {
1227 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1228 if (outputDesc != nullptr &&
1229 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1230 secondaryOutputs->push_back(outputDesc->mIoHandle);
1231 weakSecondaryOutputDescs.push_back(outputDesc);
1232 }
1233 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001234 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001235
Eric Laurent8fc147b2018-07-22 19:13:55 -07001236 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001237 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001238 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001239 };
jiabin4ef93452019-09-10 14:29:54 -07001240 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001241
Eric Laurentc209fe42020-06-05 18:11:23 -07001242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001243 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001245 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001246 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001247 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001248 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001249 std::move(weakSecondaryOutputDescs),
1250 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001251 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001253 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1254 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001255
Eric Laurente83b55d2014-11-14 10:06:21 -08001256 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001257}
1258
Eric Laurentc529cf62020-04-17 18:19:10 -07001259status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1260 audio_session_t session,
1261 const audio_config_t *config,
1262 audio_output_flags_t flags,
1263 const DeviceVector &devices,
1264 audio_io_handle_t *output) {
1265
1266 *output = AUDIO_IO_HANDLE_NONE;
1267
1268 // skip direct output selection if the request can obviously be attached to a mixed output
1269 // and not explicitly requested
1270 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1271 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1272 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1273 return NAME_NOT_FOUND;
1274 }
1275
1276 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1277 // This prevents creating an offloaded track and tearing it down immediately after start
1278 // when audioflinger detects there is an active non offloadable effect.
1279 // FIXME: We should check the audio session here but we do not have it in this context.
1280 // This may prevent offloading in rare situations where effects are left active by apps
1281 // in the background.
1282 sp<IOProfile> profile;
1283 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1284 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1285 profile = getProfileForOutput(
1286 devices, config->sample_rate, config->format, config->channel_mask,
1287 flags, true /* directOnly */);
1288 }
1289
1290 if (profile == nullptr) {
1291 return NAME_NOT_FOUND;
1292 }
1293
1294 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1295 for (size_t i = 0; i < mOutputs.size(); i++) {
1296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1297 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1298 // reuse direct output if currently open by the same client
1299 // and configured with same parameters
1300 if ((config->sample_rate == desc->getSamplingRate()) &&
1301 (config->format == desc->getFormat()) &&
1302 (config->channel_mask == desc->getChannelMask()) &&
1303 (session == desc->mDirectClientSession)) {
1304 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001305 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001306 mOutputs.keyAt(i), session);
1307 *output = mOutputs.keyAt(i);
1308 return NO_ERROR;
1309 }
1310 }
1311 }
1312
1313 if (!profile->canOpenNewIo()) {
1314 return NAME_NOT_FOUND;
1315 }
1316
1317 sp<SwAudioOutputDescriptor> outputDesc =
1318 new SwAudioOutputDescriptor(profile, mpClientInterface);
1319
Michael Chan6fb34492020-12-08 15:44:49 +11001320 // An MSD patch may be using the only output stream that can service this request. Release
1321 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001322 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001323
Eric Laurentf1f22e72021-07-13 14:04:14 +02001324 status_t status =
1325 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001326
1327 // only accept an output with the requested parameters
1328 if (status != NO_ERROR ||
1329 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1330 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1331 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1332 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1333 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1334 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1335 config->channel_mask, outputDesc->getChannelMask());
1336 if (*output != AUDIO_IO_HANDLE_NONE) {
1337 outputDesc->close();
1338 }
1339 // fall back to mixer output if possible when the direct output could not be open
1340 if (audio_is_linear_pcm(config->format) &&
1341 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1342 return NAME_NOT_FOUND;
1343 }
1344 *output = AUDIO_IO_HANDLE_NONE;
1345 return BAD_VALUE;
1346 }
1347 outputDesc->mDirectOpenCount = 1;
1348 outputDesc->mDirectClientSession = session;
1349
1350 addOutput(*output, outputDesc);
1351 mPreviousOutputs = mOutputs;
1352 ALOGV("%s returns new direct output %d", __func__, *output);
1353 mpClientInterface->onAudioPortListUpdate();
1354 return NO_ERROR;
1355}
1356
François Gaffie11d30102018-11-02 16:09:09 +01001357audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1358 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001359 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001360 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001361 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001362 audio_output_flags_t *flags,
1363 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001364{
Andy Hungc88b0642018-04-27 15:42:35 -07001365 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001366
jiabine375d412019-02-26 12:54:53 -08001367 // Discard haptic channel mask when forcing muting haptic channels.
1368 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001369 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1370 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001371
Eric Laurente552edb2014-03-10 17:42:56 -07001372 // open a direct output if required by specified parameters
1373 //force direct flag if offload flag is set: offloading implies a direct output stream
1374 // and all common behaviors are driven by checking only the direct flag
1375 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001376 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1377 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001378 }
Nadav Bar766fb022018-01-07 12:18:03 +02001379 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1380 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001381 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001382
1383 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1384
Eric Laurente83b55d2014-11-14 10:06:21 -08001385 // only allow deep buffering for music stream type
1386 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001387 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001388 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001389 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001390 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1391 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001392 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001393 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001394 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001395 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001396 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001397 audio_is_linear_pcm(config->format) &&
1398 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001399 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001400 AUDIO_OUTPUT_FLAG_DIRECT);
1401 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001402 }
Eric Laurente552edb2014-03-10 17:42:56 -07001403
Eric Laurentfa0f6742021-08-17 18:39:44 +02001404 if (mSpatializerOutput != nullptr
Eric Laurentd23aa162022-01-17 17:37:31 +01001405 && canBeSpatializedInt(attr, config,
1406 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001407 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001408 }
1409
Eric Laurentc529cf62020-04-17 18:19:10 -07001410 audio_config_t directConfig = *config;
1411 directConfig.channel_mask = channelMask;
1412 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1413 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001414 return output;
1415 }
1416
Eric Laurent14cbfca2016-03-17 09:42:16 -07001417 // A request for HW A/V sync cannot fallback to a mixed output because time
1418 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001419 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001420 return AUDIO_IO_HANDLE_NONE;
1421 }
1422
Eric Laurente552edb2014-03-10 17:42:56 -07001423 // ignoring channel mask due to downmix capability in mixer
1424
1425 // open a non direct output
1426
1427 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001428 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001429 // get which output is suitable for the specified stream. The actual
1430 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001431 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001432
Eric Laurent8838a382014-09-08 16:44:28 -07001433 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001434 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001435 output = selectOutput(
1436 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001437 }
François Gaffie11d30102018-11-02 16:09:09 +01001438 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001439 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001440 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001441
Eric Laurente552edb2014-03-10 17:42:56 -07001442 return output;
1443}
1444
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001445sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001446 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1447 mAvailableInputDevices);
1448 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1449}
1450
1451DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1452 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1453 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001454}
1455
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001456const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001457 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001458 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1459 if (msdModule != 0) {
1460 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1461 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1462 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1463 const struct audio_port_config *source = &patch->mPatch.sources[j];
1464 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1465 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001466 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001467 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001468 }
1469 }
1470 }
1471 return msdPatches;
1472}
1473
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1475 const InputProfileCollection &inputProfiles,
1476 const OutputProfileCollection &outputProfiles,
1477 const sp<DeviceDescriptor> &sourceDevice,
1478 const sp<DeviceDescriptor> &sinkDevice,
1479 AudioProfileVector& sourceProfiles,
1480 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001481 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001482 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 return NO_INIT;
1484 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001486 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001487 return NO_INIT;
1488 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001489 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001490 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1491 inProfile->supportsDevice(sourceDevice)) {
1492 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493 }
1494 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001495 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001496 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001497 outProfile->supportsDevice(sinkDevice)) {
1498 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001499 }
1500 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001501 return NO_ERROR;
1502}
1503
1504status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1505 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1506 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1507{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001508 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001509 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1510 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1511 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001512 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001513 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1514 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001515 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001516 }
1517 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1518 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1519 sinkConfig->format = bestSinkConfig.format;
1520 // For encoded streams force direct flag to prevent downstream mixing.
1521 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1522 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001523 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1524 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001525 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001526 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1527 // raw and IEC61937 framed streams.
1528 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1529 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1530 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001531 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1532 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1533 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1534 sourceConfig->format = bestSinkConfig.format;
1535 // Copy input stream directly without any processing (e.g. resampling).
1536 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1537 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1538 if (hwAvSync) {
1539 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1540 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1541 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1542 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1543 }
1544 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1545 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1546 sinkConfig->config_mask |= config_mask;
1547 sourceConfig->config_mask |= config_mask;
1548 return NO_ERROR;
1549}
1550
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001551PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1552 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001553{
1554 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001555 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1556 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1557 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1558 if (deviceModule == nullptr) {
1559 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1560 return patchBuilder;
1561 }
1562 const InputProfileCollection inputProfiles = msdIsSource ?
1563 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1564 const OutputProfileCollection outputProfiles = msdIsSource ?
1565 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1566
1567 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1568 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1569 device : getMsdAudioOutDevices().itemAt(0);
1570 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1571
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1573 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001574 AudioProfileVector sourceProfiles;
1575 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001576 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1577 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001578 for (auto hwAvSync : { true, false }) {
1579 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1580 sourceProfiles, sinkProfiles) != NO_ERROR) {
1581 continue;
1582 }
1583 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1584 &sinkConfig) == NO_ERROR) {
1585 // Found a matching config. Re-create PatchBuilder with this config.
1586 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1587 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001588 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001589 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001590 " supporting PCM format conversion.", __func__);
1591 return patchBuilder;
1592}
1593
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001594status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001595 DeviceVector devices;
1596 if (outputDevices != nullptr && outputDevices->size() > 0) {
1597 devices.add(*outputDevices);
1598 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001599 // Use media strategy for unspecified output device. This should only
1600 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1601 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001602 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001603 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001604 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001605 }
Michael Chan6fb34492020-12-08 15:44:49 +11001606 std::vector<PatchBuilder> patchesToCreate;
1607 for (auto i = 0u; i < devices.size(); ++i) {
1608 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001609 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001610 }
1611 // Retain only the MSD patches associated with outputDevices request.
1612 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001614 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1615 auto retainedPatch = false;
1616 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1617 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1618 patchesToRemove.removeItemsAt(i);
1619 retainedPatch = true;
1620 break;
1621 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 }
Michael Chan6fb34492020-12-08 15:44:49 +11001623 if (retainedPatch) {
1624 it = patchesToCreate.erase(it);
1625 continue;
1626 }
1627 ++it;
1628 }
1629 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1630 return NO_ERROR;
1631 }
1632 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1633 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001634 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001635 }
Michael Chan6fb34492020-12-08 15:44:49 +11001636 status_t status = NO_ERROR;
1637 for (const auto &p : patchesToCreate) {
1638 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1639 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1640 char message[256];
1641 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1642 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1643 currStatus == NO_ERROR ? "Success" : "Error",
1644 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1645 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1646 if (currStatus == NO_ERROR) {
1647 ALOGD("%s", message);
1648 } else {
1649 ALOGE("%s", message);
1650 if (status == NO_ERROR) {
1651 status = currStatus;
1652 }
1653 }
1654 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001655 return status;
1656}
1657
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001658void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1659 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001660 for (size_t i = 0; i < msdPatches.size(); i++) {
1661 const auto& patch = msdPatches[i];
1662 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1663 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1664 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1665 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1666 releaseAudioPatch(patch->getHandle(), mUidCached);
1667 break;
1668 }
1669 }
1670 }
1671}
1672
Eric Laurente0720872014-03-11 09:30:41 -07001673audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001674 audio_output_flags_t flags,
1675 audio_format_t format,
1676 audio_channel_mask_t channelMask,
1677 uint32_t samplingRate,
1678 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001679{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001680 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1681 "%s called with format %#x", __func__, format);
1682
jiabinebb6af42020-06-09 17:31:17 -07001683 // Return the output that haptic-generating attached to when 1) session id is specified,
1684 // 2) haptic-generating effect exists for given session id and 3) the output that
1685 // haptic-generating effect attached to is in given outputs.
1686 if (sessionId != AUDIO_SESSION_NONE) {
1687 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1688 sessionId, FX_IID_HAPTICGENERATOR);
1689 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1690 return hapticGeneratingOutput;
1691 }
1692 }
1693
Eric Laurent16c66dd2019-05-01 17:54:10 -07001694 // Flags disqualifying an output: the match must happen before calling selectOutput()
1695 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1696 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1697
1698 // Flags expressing a functional request: must be honored in priority over
1699 // other criteria
1700 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1701 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1702 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1703 // Flags expressing a performance request: have lower priority than serving
1704 // requested sampling rate or channel mask
1705 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1706 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1707 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1708
1709 const audio_output_flags_t functionalFlags =
1710 (audio_output_flags_t)(flags & kFunctionalFlags);
1711 const audio_output_flags_t performanceFlags =
1712 (audio_output_flags_t)(flags & kPerformanceFlags);
1713
1714 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1715
Eric Laurente552edb2014-03-10 17:42:56 -07001716 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001717 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001719 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001720 // 2: the output with the highest number of requested functional flags
1721 // 3: the output supporting the exact channel mask
1722 // 4: the output with a higher channel count than requested
1723 // 5: the output with a higher sampling rate than requested
1724 // 6: the output with the highest number of requested performance flags
1725 // 7: the output with the bit depth the closest to the requested one
1726 // 8: the primary output
1727 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001728
Eric Laurent16c66dd2019-05-01 17:54:10 -07001729 // matching criteria values in priority order for best matching output so far
1730 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001731
Eric Laurent16c66dd2019-05-01 17:54:10 -07001732 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1733 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1734 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001735
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001736 for (audio_io_handle_t output : outputs) {
1737 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001738 // matching criteria values in priority order for current output
1739 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001740
Eric Laurent16c66dd2019-05-01 17:54:10 -07001741 if (outputDesc->isDuplicated()) {
1742 continue;
1743 }
1744 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1745 continue;
1746 }
Eric Laurent8838a382014-09-08 16:44:28 -07001747
Eric Laurent16c66dd2019-05-01 17:54:10 -07001748 // If haptic channel is specified, use the haptic output if present.
1749 // When using haptic output, same audio format and sample rate are required.
1750 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001751 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001752 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1753 continue;
1754 }
1755 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001756 && format == outputDesc->getFormat()
1757 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001758 currentMatchCriteria[0] = outputHapticChannelCount;
1759 }
1760
1761 // functional flags match
1762 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1763
1764 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001765 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1766 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001767 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1768 channelCount <= outputChannelCount) {
1769 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001770 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1771 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001772 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001773 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001774 currentMatchCriteria[3] = outputChannelCount;
1775 }
1776
1777 // sampling rate match
1778 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001779 samplingRate <= outputDesc->getSamplingRate()) {
1780 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001781 }
1782
1783 // performance flags match
1784 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1785
1786 // format match
1787 if (format != AUDIO_FORMAT_INVALID) {
1788 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001789 PolicyAudioPort::kFormatDistanceMax -
1790 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001791 }
1792
1793 // primary output match
1794 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1795
1796 // compare match criteria by priority then value
1797 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1798 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1799 bestMatchCriteria = currentMatchCriteria;
1800 bestOutput = output;
1801
1802 std::stringstream result;
1803 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1804 std::ostream_iterator<int>(result, " "));
1805 ALOGV("%s new bestOutput %d criteria %s",
1806 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001807 }
1808 }
1809
Eric Laurent16c66dd2019-05-01 17:54:10 -07001810 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001811}
1812
Eric Laurent8fc147b2018-07-22 19:13:55 -07001813status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001814{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001815 ALOGV("%s portId %d", __FUNCTION__, portId);
1816
1817 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1818 if (outputDesc == 0) {
1819 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001820 return BAD_VALUE;
1821 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001822 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001823
Eric Laurent8fc147b2018-07-22 19:13:55 -07001824 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001825 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001826
Eric Laurent733ce942017-12-07 12:18:25 -08001827 status_t status = outputDesc->start();
1828 if (status != NO_ERROR) {
1829 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001830 }
1831
Eric Laurent97ac8712018-07-27 18:59:02 -07001832 uint32_t delayMs;
1833 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001834
1835 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001836 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001837 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001838 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001839 if (delayMs != 0) {
1840 usleep(delayMs * 1000);
1841 }
1842
1843 return status;
1844}
1845
Eric Laurent97ac8712018-07-27 18:59:02 -07001846status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1847 const sp<TrackClientDescriptor>& client,
1848 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001849{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001850 // cannot start playback of STREAM_TTS if any other output is being used
1851 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001852
1853 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001854 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001855 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001856 auto clientStrategy = client->strategy();
1857 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001858 if (stream == AUDIO_STREAM_TTS) {
1859 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001860 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001861 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001862 return INVALID_OPERATION;
1863 } else {
1864 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1865 }
1866 } else {
1867 // some playback other than beacon starts
1868 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1869 }
1870
Eric Laurent77305a62016-07-25 16:39:22 -07001871 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001872 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001873 bool force = !outputDesc->isActive() &&
1874 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001875
François Gaffie11d30102018-11-02 16:09:09 +01001876 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001877 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001878 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001879 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001880 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001881 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001882 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001883 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001884 } else {
1885 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001886 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001887 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1888 AUDIO_FORMAT_DEFAULT);
1889 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1890 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001891 }
1892
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001893 // requiresMuteCheck is false when we can bypass mute strategy.
1894 // It covers a common case when there is no materially active audio
1895 // and muting would result in unnecessary delay and dropped audio.
1896 const uint32_t outputLatencyMs = outputDesc->latency();
1897 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1898
Eric Laurente552edb2014-03-10 17:42:56 -07001899 // increment usage count for this stream on the requested output:
1900 // NOTE that the usage count is the same for duplicated output and hardware output which is
1901 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001902 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001903
1904 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001905 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1906 client->isPreferredDeviceForExclusiveUse()) {
1907 // Preferred device may be exclusive, use only if no other active clients on this output
1908 devices = DeviceVector(
1909 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1910 } else {
1911 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1912 }
François Gaffie11d30102018-11-02 16:09:09 +01001913 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001914 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001915 }
1916 }
Eric Laurente552edb2014-03-10 17:42:56 -07001917
François Gaffiec005e562018-11-06 15:04:49 +01001918 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001919 selectOutputForMusicEffects();
1920 }
1921
François Gaffie1c878552018-11-22 16:53:21 +01001922 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001923 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001924 if (devices.isEmpty()) {
1925 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001926 }
François Gaffiec005e562018-11-06 15:04:49 +01001927 bool shouldWait =
1928 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1929 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1930 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001931 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001932 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001933 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001934 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001935 // An output has a shared device if
1936 // - managed by the same hw module
1937 // - supports the currently selected device
1938 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001939 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001940
Eric Laurent77305a62016-07-25 16:39:22 -07001941 // force a device change if any other output is:
1942 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001943 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001944 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001945 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001946 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001947 // change the device currently selected by the other output.
1948 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001949 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001950 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001951 force = true;
1952 }
1953 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001954 // a notification so that audio focus effect can propagate, or that a mute/unmute
1955 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001956 const uint32_t latencyMs = desc->latency();
1957 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1958
1959 if (shouldWait && isActive && (waitMs < latencyMs)) {
1960 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001961 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001962
1963 // Require mute check if another output is on a shared device
1964 // and currently active to have proper drain and avoid pops.
1965 // Note restoring AudioTracks onto this output needs to invoke
1966 // a volume ramp if there is no mute.
1967 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001968 }
1969 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001970
1971 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001972 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001973
Eric Laurente552edb2014-03-10 17:42:56 -07001974 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001975 auto &curves = getVolumeCurves(client->attributes());
1976 checkAndSetVolume(curves, client->volumeSource(),
1977 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001978 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001979 outputDesc->devices().types(), 0 /*delay*/,
1980 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001981
1982 // update the outputs if starting an output with a stream that can affect notification
1983 // routing
1984 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001985
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001986 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001987 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001988 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1989 }
Eric Laurentdc462862016-07-19 12:29:53 -07001990
1991 if (waitMs > muteWaitMs) {
1992 *delayMs = waitMs - muteWaitMs;
1993 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001994
1995 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1996 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1997 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1998 // change occurs after the MixerThread starts and causes a stream volume
1999 // glitch.
2000 //
2001 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002002 }
Eric Laurentdc462862016-07-19 12:29:53 -07002003
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002004 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002005 mEngine->getForceUse(
2006 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002007 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002008 }
2009
Eric Laurent97ac8712018-07-27 18:59:02 -07002010 // Automatically enable the remote submix input when output is started on a re routing mix
2011 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002012 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2013 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002014 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2015 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2016 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002017 "remote-submix",
2018 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002019 }
2020
Eric Laurente552edb2014-03-10 17:42:56 -07002021 return NO_ERROR;
2022}
2023
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002025{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002026 ALOGV("%s portId %d", __FUNCTION__, portId);
2027
2028 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2029 if (outputDesc == 0) {
2030 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002031 return BAD_VALUE;
2032 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002033 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002034
Eric Laurent97ac8712018-07-27 18:59:02 -07002035 ALOGV("stopOutput() output %d, stream %d, session %d",
2036 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002037
Eric Laurent97ac8712018-07-27 18:59:02 -07002038 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002039
Eric Laurent733ce942017-12-07 12:18:25 -08002040 if (status == NO_ERROR ) {
2041 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002042 }
2043 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002044}
2045
Eric Laurent97ac8712018-07-27 18:59:02 -07002046status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2047 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002048{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002049 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002051 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002052
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002053 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2054
François Gaffie1c878552018-11-22 16:53:21 +01002055 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2056 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002057 // Automatically disable the remote submix input when output is stopped on a
2058 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002059 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002060 if (isSingleDeviceType(
2061 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002062 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002063 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002064 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2065 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002066 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002067 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002068 }
2069 }
2070 bool forceDeviceUpdate = false;
2071 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002072 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002073 forceDeviceUpdate = true;
2074 }
2075
Eric Laurente552edb2014-03-10 17:42:56 -07002076 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002077 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002078
Eric Laurente552edb2014-03-10 17:42:56 -07002079 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002080 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002081 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002082 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002083
2084 // If the routing does not change, if an output is routed on a device using HwGain
2085 // (aka setAudioPortConfig) and there are still active clients following different
2086 // volume group(s), force reapply volume
2087 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2088 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2089
Eric Laurente552edb2014-03-10 17:42:56 -07002090 // delay the device switch by twice the latency because stopOutput() is executed when
2091 // the track stop() command is received and at that time the audio track buffer can
2092 // still contain data that needs to be drained. The latency only covers the audio HAL
2093 // and kernel buffers. Also the latency does not always include additional delay in the
2094 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002095 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2096 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002097
2098 // force restoring the device selection on other active outputs if it differs from the
2099 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002100 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002101 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002102 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002103 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002104 desc->isActive() &&
2105 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002106 (newDevices != desc->devices())) {
2107 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2108 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002109
François Gaffie11d30102018-11-02 16:09:09 +01002110 setOutputDevices(desc, newDevices2, force, delayMs);
2111
Eric Laurent57de36c2016-09-28 16:59:11 -07002112 // re-apply device specific volume if not done by setOutputDevice()
2113 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002114 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002115 }
Eric Laurente552edb2014-03-10 17:42:56 -07002116 }
2117 }
2118 // update the outputs if stopping one with a stream that can affect notification routing
2119 handleNotificationRoutingForStream(stream);
2120 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002121
2122 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2123 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002124 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002125 }
2126
François Gaffiec005e562018-11-06 15:04:49 +01002127 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002128 selectOutputForMusicEffects();
2129 }
Eric Laurente552edb2014-03-10 17:42:56 -07002130 return NO_ERROR;
2131 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002132 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002133 return INVALID_OPERATION;
2134 }
2135}
2136
jiabinbce0c1d2020-10-05 11:20:18 -07002137bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002138{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139 ALOGV("%s portId %d", __FUNCTION__, portId);
2140
2141 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2142 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002143 // If an output descriptor is closed due to a device routing change,
2144 // then there are race conditions with releaseOutput from tracks
2145 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2146 // destroyed shortly thereafter.
2147 //
2148 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002149 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002150 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002151 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002152
2153 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302155 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2156 if (outputDesc->isClientActive(client)) {
2157 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2158 stopOutput(portId);
2159 }
2160
Eric Laurent8fc147b2018-07-22 19:13:55 -07002161 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2162 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002163 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002164 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002165 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002166 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002167 if (--outputDesc->mDirectOpenCount == 0) {
2168 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002169 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002170 }
2171 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302172
Andy Hung39efb7a2018-09-26 15:39:28 -07002173 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002174 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2175 // The output is pending reopened to query dynamic profiles and
2176 // there is no active clients
2177 closeOutput(outputDesc->mIoHandle);
2178 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2179 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2180 if (newOutputDesc == nullptr) {
2181 ALOGE("%s failed to open output", __func__);
2182 }
2183 return true;
2184 }
2185 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002186}
2187
Eric Laurentcaf7f482014-11-25 17:50:47 -08002188status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2189 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002190 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002191 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002192 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002193 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002194 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002195 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002196 input_type_t *inputType,
2197 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002198{
François Gaffiec005e562018-11-06 15:04:49 +01002199 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2200 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2201 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002202
Eric Laurentad2e7b92017-09-14 20:06:42 -07002203 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002204 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002205 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002206 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002207 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002208 sp<AudioInputDescriptor> inputDesc;
2209 sp<RecordClientDescriptor> clientDesc;
2210 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002211 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002212 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002213
2214 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2215 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2216 return INVALID_OPERATION;
2217 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002218
Francois Gaffie716e1432019-01-14 16:58:59 +01002219 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2220 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002221 }
2222
Paul McLean466dc8e2015-04-17 13:15:36 -06002223 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002224 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002225 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002226
Eric Laurentad2e7b92017-09-14 20:06:42 -07002227 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2228 // possible
2229 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2230 *input != AUDIO_IO_HANDLE_NONE) {
2231 ssize_t index = mInputs.indexOfKey(*input);
2232 if (index < 0) {
2233 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2234 status = BAD_VALUE;
2235 goto error;
2236 }
2237 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002238 RecordClientVector clients = inputDesc->getClientsForSession(session);
2239 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002240 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2241 status = BAD_VALUE;
2242 goto error;
2243 }
2244 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2245 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002246 // corresponds to a new client and is only permitted from the same UID.
2247 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002248 if (clients.size() > 1) {
2249 for (const auto& client : clients) {
2250 // The client map is ordered by key values (portId) and portIds are allocated
2251 // incrementaly. So the first client in this list is the one opened by audio flinger
2252 // when the mmap stream is created and should be ignored as it does not correspond
2253 // to an actual client
2254 if (client == *clients.cbegin()) {
2255 continue;
2256 }
2257 if (uid != client->uid() && !client->isSilenced()) {
2258 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2259 uid, client->portId(), client->uid());
2260 status = INVALID_OPERATION;
2261 goto error;
2262 }
Eric Laurent331679c2018-04-16 17:03:16 -07002263 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002264 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002265 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002266 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002267
Eric Laurentfecbceb2021-02-09 14:46:43 +01002268 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002269 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002270 }
2271
2272 *input = AUDIO_IO_HANDLE_NONE;
2273 *inputType = API_INPUT_INVALID;
2274
Francois Gaffie716e1432019-01-14 16:58:59 +01002275 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002276
Francois Gaffie716e1432019-01-14 16:58:59 +01002277 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2278 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2279 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002280 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002281 ALOGW("%s could not find input mix for attr %s",
2282 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002283 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002284 }
jiabinc1de2df2019-05-07 14:26:40 -07002285 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2286 String8(attr->tags + strlen("addr=")),
2287 AUDIO_FORMAT_DEFAULT);
2288 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002289 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002290 __func__, attributes.source, attributes.tags);
2291 status = BAD_VALUE;
2292 goto error;
2293 }
2294
Kevin Rocard25f9b052019-02-27 15:08:54 -08002295 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2296 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2297 } else {
2298 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2299 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002300 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002301 if (explicitRoutingDevice != nullptr) {
2302 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002304 // Prevent from storing invalid requested device id in clients
2305 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002306 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002307 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2308 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 }
François Gaffie11d30102018-11-02 16:09:09 +01002310 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002311 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002312 status = BAD_VALUE;
2313 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002314 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002315 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2316 *inputType = API_INPUT_MIX_CAPTURE;
2317 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002318 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2319 // there is an external policy, but this input is attached to a mix of recorders,
2320 // meaning it receives audio injected into the framework, so the recorder doesn't
2321 // know about it and is therefore considered "legacy"
2322 *inputType = API_INPUT_LEGACY;
2323 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002324 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002325 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002326 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002327 } else {
2328 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002329 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002330
Eric Laurent599c7582015-12-07 18:05:55 -08002331 }
2332
François Gaffiec005e562018-11-06 15:04:49 +01002333 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002334 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002335 status = INVALID_OPERATION;
2336 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002337 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002338
Eric Laurent8f42ea12018-08-08 09:08:25 -07002339exit:
2340
François Gaffiec005e562018-11-06 15:04:49 +01002341 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2342 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002343
Francois Gaffie716e1432019-01-14 16:58:59 +01002344 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002345 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002346 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002347
Mikhail Naganov2996f672019-04-18 12:29:59 -07002348 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002349 requestedDeviceId, attributes.source, flags,
2350 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002351 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002352 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002353
2354 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2355 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002356
Eric Laurent599c7582015-12-07 18:05:55 -08002357 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002358
2359error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002360 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002361}
2362
2363
François Gaffie11d30102018-11-02 16:09:09 +01002364audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002365 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002366 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002367 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002368 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002369 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002370{
2371 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002372 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002373 bool isSoundTrigger = false;
2374
François Gaffiec005e562018-11-06 15:04:49 +01002375 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002376 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2377 if (index >= 0) {
2378 input = mSoundTriggerSessions.valueFor(session);
2379 isSoundTrigger = true;
2380 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2381 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2382 } else {
2383 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002384 }
François Gaffiec005e562018-11-06 15:04:49 +01002385 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002386 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002387 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002388 }
2389
Andy Hungf129b032015-04-07 13:45:50 -07002390 // find a compatible input profile (not necessarily identical in parameters)
2391 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002392 // sampling rate and flags may be updated by getInputProfile
2393 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2394 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002395 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002396 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002397 audio_input_flags_t profileFlags = flags;
2398 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002399 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002400 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002401 profileFlags);
2402 if (profile != 0) {
2403 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002404 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2405 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002406 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2407 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2408 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002409 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002410 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002411 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002412 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002413 }
Eric Laurente552edb2014-03-10 17:42:56 -07002414 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002415 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002416 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002417 if (samplingRate == 0) {
2418 samplingRate = profileSamplingRate;
2419 }
Eric Laurente552edb2014-03-10 17:42:56 -07002420
Eric Laurent322b4d22015-04-03 15:57:54 -07002421 if (profile->getModuleHandle() == 0) {
2422 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002423 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002424 }
2425
Eric Laurentec376dc2021-04-08 20:41:22 +02002426 // Reuse an already opened input if a client with the same session ID already exists
2427 // on that input
2428 for (size_t i = 0; i < mInputs.size(); i++) {
2429 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2430 if (desc->mProfile != profile) {
2431 continue;
2432 }
2433 RecordClientVector clients = desc->clientsList();
2434 for (const auto &client : clients) {
2435 if (session == client->session()) {
2436 return desc->mIoHandle;
2437 }
2438 }
2439 }
2440
Eric Laurent3974e3b2017-12-07 17:58:43 -08002441 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002442 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002443 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002444 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002445 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002446 continue;
2447 }
2448 // if sound trigger, reuse input if used by other sound trigger on same session
2449 // else
2450 // reuse input if active client app is not in IDLE state
2451 //
2452 RecordClientVector clients = desc->clientsList();
2453 bool doClose = false;
2454 for (const auto& client : clients) {
2455 if (isSoundTrigger != client->isSoundTrigger()) {
2456 continue;
2457 }
2458 if (client->isSoundTrigger()) {
2459 if (session == client->session()) {
2460 return desc->mIoHandle;
2461 }
2462 continue;
2463 }
2464 if (client->active() && client->appState() != APP_STATE_IDLE) {
2465 return desc->mIoHandle;
2466 }
2467 doClose = true;
2468 }
2469 if (doClose) {
2470 closeInput(desc->mIoHandle);
2471 } else {
2472 i++;
2473 }
2474 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002475 }
2476
Eric Laurentfe231122017-11-17 17:48:06 -08002477 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002478
Eric Laurentfe231122017-11-17 17:48:06 -08002479 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2480 lConfig.sample_rate = profileSamplingRate;
2481 lConfig.channel_mask = profileChannelMask;
2482 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002483
François Gaffie11d30102018-11-02 16:09:09 +01002484 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002485
2486 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002487 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002488 (profileSamplingRate != lConfig.sample_rate) ||
2489 !audio_formats_match(profileFormat, lConfig.format) ||
2490 (profileChannelMask != lConfig.channel_mask)) {
2491 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002492 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002493 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002494 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002495 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002496 }
Eric Laurent599c7582015-12-07 18:05:55 -08002497 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002498 }
2499
Eric Laurentc722f302014-12-10 11:21:49 -08002500 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002501
Eric Laurent599c7582015-12-07 18:05:55 -08002502 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002503 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002504
Eric Laurent599c7582015-12-07 18:05:55 -08002505 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002506}
2507
Eric Laurent4eb58f12018-12-07 16:41:02 -08002508status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002509{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002510 ALOGV("%s portId %d", __FUNCTION__, portId);
2511
2512 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2513 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002515 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002516 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002517 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002518 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 if (client->active()) {
2520 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2521 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002522 }
2523
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 audio_session_t session = client->session();
2525
Eric Laurent4eb58f12018-12-07 16:41:02 -08002526 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002527
Eric Laurent4eb58f12018-12-07 16:41:02 -08002528 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002529
Eric Laurent4eb58f12018-12-07 16:41:02 -08002530 status_t status = inputDesc->start();
2531 if (status != NO_ERROR) {
2532 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002533 }
Eric Laurente552edb2014-03-10 17:42:56 -07002534
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002535 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002536 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002537 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002538
Eric Laurent8f42ea12018-08-08 09:08:25 -07002539 // indicate active capture to sound trigger service if starting capture from a mic on
2540 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002541 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002542 if (device != nullptr) {
2543 status = setInputDevice(input, device, true /* force */);
2544 } else {
2545 ALOGW("%s no new input device can be found for descriptor %d",
2546 __FUNCTION__, inputDesc->getId());
2547 status = BAD_VALUE;
2548 }
Eric Laurente552edb2014-03-10 17:42:56 -07002549
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002550 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002551 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002553 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002554 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2555 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002557 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002558
François Gaffie11d30102018-11-02 16:09:09 +01002559 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2560 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002562 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002564
Eric Laurent8f42ea12018-08-08 09:08:25 -07002565 // automatically enable the remote submix output when input is started if not
2566 // used by a policy mix of type MIX_TYPE_RECORDERS
2567 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002568 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002569 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002570 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002572 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2573 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002574 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002575 if (address != "") {
2576 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002578 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002579 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002580 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002581 } else if (status != NO_ERROR) {
2582 // Restore client activity state.
2583 inputDesc->setClientActive(client, false);
2584 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002585 }
2586
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002587 ALOGV("%s input %d source = %d status = %d exit",
2588 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002589
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002590 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002591}
2592
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002594{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002595 ALOGV("%s portId %d", __FUNCTION__, portId);
2596
2597 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2598 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002600 return BAD_VALUE;
2601 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002603 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002604 if (!client->active()) {
2605 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002606 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002607 }
Carter Hsue6139d52021-07-08 10:30:20 +08002608 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002609 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002610
Eric Laurent8f42ea12018-08-08 09:08:25 -07002611 inputDesc->stop();
2612 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002613 auto current_source = inputDesc->source();
2614 setInputDevice(input, getNewInputDevice(inputDesc),
2615 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002616 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002617 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002619 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002620 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2621 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002622 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002623 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002624
2625 // automatically disable the remote submix output when input is stopped if not
2626 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002627 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002628 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002629 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002631 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2632 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 }
2634 if (address != "") {
2635 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2636 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002637 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002638 }
2639 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002640 resetInputDevice(input);
2641
2642 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2643 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002644 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2645 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002646 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002647 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002648 }
2649 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002650 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002651 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002652}
2653
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002655{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656 ALOGV("%s portId %d", __FUNCTION__, portId);
2657
2658 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2659 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002660 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002661 return;
2662 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002663 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 audio_io_handle_t input = inputDesc->mIoHandle;
2665
Eric Laurent8f42ea12018-08-08 09:08:25 -07002666 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002667
Andy Hung39efb7a2018-09-26 15:39:28 -07002668 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002669
Andy Hung39efb7a2018-09-26 15:39:28 -07002670 if (inputDesc->getClientCount() > 0) {
2671 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002672 return;
2673 }
2674
Eric Laurent05b90f82014-08-27 15:32:29 -07002675 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002676 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002678}
2679
Eric Laurent8f42ea12018-08-08 09:08:25 -07002680void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002682 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002683
2684 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002685 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002686 }
2687}
2688
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2690{
2691 stopInput(portId);
2692 releaseInput(portId);
2693}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002694
Eric Laurent0dd51852019-04-19 18:18:58 -07002695void AudioPolicyManager::checkCloseInputs() {
2696 // After connecting or disconnecting an input device, close input if:
2697 // - it has no client (was just opened to check profile) OR
2698 // - none of its supported devices are connected anymore OR
2699 // - one of its clients cannot be routed to one of its supported
2700 // devices anymore. Otherwise update device selection
2701 std::vector<audio_io_handle_t> inputsToClose;
2702 for (size_t i = 0; i < mInputs.size(); i++) {
2703 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2704 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002705 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002706 inputsToClose.push_back(mInputs.keyAt(i));
2707 } else {
2708 bool close = false;
2709 for (const auto& client : input->clientsList()) {
2710 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002711 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002712 if (!input->supportedDevices().contains(device)) {
2713 close = true;
2714 break;
2715 }
2716 }
2717 if (close) {
2718 inputsToClose.push_back(mInputs.keyAt(i));
2719 } else {
2720 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2721 }
2722 }
2723 }
2724
2725 for (const audio_io_handle_t handle : inputsToClose) {
2726 ALOGV("%s closing input %d", __func__, handle);
2727 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002728 }
Eric Laurentd4692962014-05-05 18:13:44 -07002729}
2730
François Gaffie251c7f02018-11-07 10:41:08 +01002731void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002732{
2733 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002734 if (indexMin < 0 || indexMax < 0) {
2735 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2736 return;
2737 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002738 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002739
2740 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002741 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2742 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002743 continue;
2744 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002745 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002746 }
Eric Laurente552edb2014-03-10 17:42:56 -07002747}
2748
Eric Laurente0720872014-03-11 09:30:41 -07002749status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002750 int index,
2751 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002752{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002753 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002754 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2755 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2756 return NO_ERROR;
2757 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002758 ALOGV("%s: stream %s attributes=%s", __func__,
2759 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002760 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002761}
2762
Eric Laurente0720872014-03-11 09:30:41 -07002763status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002764 int *index,
2765 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002766{
François Gaffiec005e562018-11-06 15:04:49 +01002767 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2768 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002769 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002770 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002771 deviceTypes = mEngine->getOutputDevicesForStream(
2772 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002773 }
jiabin9a3361e2019-10-01 09:38:30 -07002774 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002775}
2776
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002777status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002778 int index,
2779 audio_devices_t device)
2780{
2781 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002782 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2783 if (group == VOLUME_GROUP_NONE) {
2784 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002785 return BAD_VALUE;
2786 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002787 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002788 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002789 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002790 VolumeSource vs = toVolumeSource(group);
2791 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2792
2793 status = setVolumeCurveIndex(index, device, curves);
2794 if (status != NO_ERROR) {
2795 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2796 return status;
2797 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002798
jiabin9a3361e2019-10-01 09:38:30 -07002799 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002800 auto curCurvAttrs = curves.getAttributes();
2801 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2802 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002803 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002804 } else if (!curves.getStreamTypes().empty()) {
2805 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002806 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002807 } else {
2808 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2809 return BAD_VALUE;
2810 }
jiabin9a3361e2019-10-01 09:38:30 -07002811 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2812 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002813
François Gaffiecfe17322018-11-07 13:41:29 +01002814 // update volume on all outputs and streams matching the following:
2815 // - The requested stream (or a stream matching for volume control) is active on the output
2816 // - The device (or devices) selected by the engine for this stream includes
2817 // the requested device
2818 // - For non default requested device, currently selected device on the output is either the
2819 // requested device or one of the devices selected by the engine for this stream
2820 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2821 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002822 for (size_t i = 0; i < mOutputs.size(); i++) {
2823 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002824 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002825
jiabin9a3361e2019-10-01 09:38:30 -07002826 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2827 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002828 }
François Gaffieed91f582020-01-31 10:35:37 +01002829 if (!(desc->isActive(vs) || isInCall())) {
2830 continue;
2831 }
2832 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2833 curDevices.find(device) == curDevices.end()) {
2834 continue;
2835 }
2836 bool applyVolume = false;
2837 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2838 curSrcDevices.insert(device);
2839 applyVolume = (curSrcDevices.find(
2840 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2841 } else {
2842 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2843 }
2844 if (!applyVolume) {
2845 continue; // next output
2846 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002847 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2848 // If a higher priority strategy is active, and the output is routed to a device with a
2849 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002850 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002851 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002852 // If the volume source is active with higher priority source, ensure at least Sw Muted
2853 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002854 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2855 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2856 false /*preferredDevice*/);
2857 if (activeClients.empty()) {
2858 continue;
2859 }
2860 bool isPreempted = false;
2861 bool isHigherPriority = productStrategy < strategy;
2862 for (const auto &client : activeClients) {
2863 if (isHigherPriority && (client->volumeSource() != vs)) {
2864 ALOGV("%s: Strategy=%d (\nrequester:\n"
2865 " group %d, volumeGroup=%d attributes=%s)\n"
2866 " higher priority source active:\n"
2867 " volumeGroup=%d attributes=%s) \n"
2868 " on output %zu, bailing out", __func__, productStrategy,
2869 group, group, toString(attributes).c_str(),
2870 client->volumeSource(), toString(client->attributes()).c_str(), i);
2871 applyVolume = false;
2872 isPreempted = true;
2873 break;
2874 }
2875 // However, continue for loop to ensure no higher prio clients running on output
2876 if (client->volumeSource() == vs) {
2877 applyVolume = true;
2878 }
2879 }
2880 if (isPreempted || applyVolume) {
2881 break;
2882 }
2883 }
2884 if (!applyVolume) {
2885 continue; // next output
2886 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002887 }
François Gaffieed91f582020-01-31 10:35:37 +01002888 //FIXME: workaround for truncated touch sounds
2889 // delayed volume change for system stream to be removed when the problem is
2890 // handled by system UI
2891 status_t volStatus = checkAndSetVolume(
2892 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002893 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002894 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2895 if (volStatus != NO_ERROR) {
2896 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002897 }
2898 }
François Gaffiecfe17322018-11-07 13:41:29 +01002899 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2900 return status;
2901}
2902
François Gaffieaaac0fd2018-11-22 17:56:39 +01002903status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002904 audio_devices_t device,
2905 IVolumeCurves &volumeCurves)
2906{
2907 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2908 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002909 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2910 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002911 (index > volumeCurves.getVolumeIndexMax())) {
2912 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2913 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2914 return BAD_VALUE;
2915 }
2916 if (!audio_is_output_device(device)) {
2917 return BAD_VALUE;
2918 }
2919
2920 // Force max volume if stream cannot be muted
2921 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2922
François Gaffieaaac0fd2018-11-22 17:56:39 +01002923 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002924 volumeCurves.addCurrentVolumeIndex(device, index);
2925 return NO_ERROR;
2926}
2927
2928status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2929 int &index,
2930 audio_devices_t device)
2931{
2932 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2933 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002934 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002935 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00002936 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07002937 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002938 }
jiabin9a3361e2019-10-01 09:38:30 -07002939 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002940}
2941
2942status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2943 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002944 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002945{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00002946 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002947 return BAD_VALUE;
2948 }
jiabin9a3361e2019-10-01 09:38:30 -07002949 index = curves.getVolumeIndex(deviceTypes);
2950 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002951 return NO_ERROR;
2952}
2953
2954status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2955 int &index)
2956{
2957 index = getVolumeCurves(attr).getVolumeIndexMin();
2958 return NO_ERROR;
2959}
2960
2961status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2962 int &index)
2963{
2964 index = getVolumeCurves(attr).getVolumeIndexMax();
2965 return NO_ERROR;
2966}
2967
Eric Laurent36829f92017-04-07 19:04:42 -07002968audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002969{
2970 // select one output among several suitable for global effects.
2971 // The priority is as follows:
2972 // 1: An offloaded output. If the effect ends up not being offloadable,
2973 // AudioFlinger will invalidate the track and the offloaded output
2974 // will be closed causing the effect to be moved to a PCM output.
2975 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002976 // 3: The primary output
2977 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002978
François Gaffiec005e562018-11-06 15:04:49 +01002979 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2980 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002981 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002982
Eric Laurent36829f92017-04-07 19:04:42 -07002983 if (outputs.size() == 0) {
2984 return AUDIO_IO_HANDLE_NONE;
2985 }
Eric Laurente552edb2014-03-10 17:42:56 -07002986
Eric Laurent36829f92017-04-07 19:04:42 -07002987 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2988 bool activeOnly = true;
2989
2990 while (output == AUDIO_IO_HANDLE_NONE) {
2991 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2992 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2993 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2994
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002995 for (audio_io_handle_t output : outputs) {
2996 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002997 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002998 continue;
2999 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003000 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3001 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003002 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003003 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003004 }
3005 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003006 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003007 }
3008 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003009 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003010 }
3011 }
3012 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3013 output = outputOffloaded;
3014 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3015 output = outputDeepBuffer;
3016 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3017 output = outputPrimary;
3018 } else {
3019 output = outputs[0];
3020 }
3021 activeOnly = false;
3022 }
3023
3024 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003025 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003026 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3027 mMusicEffectOutput = output;
3028 }
3029
3030 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003031 return output;
3032}
3033
Eric Laurent36829f92017-04-07 19:04:42 -07003034audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3035{
3036 return selectOutputForMusicEffects();
3037}
3038
Eric Laurente0720872014-03-11 09:30:41 -07003039status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003040 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003041 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003042 int session,
3043 int id)
3044{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003045 if (session != AUDIO_SESSION_DEVICE) {
3046 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003047 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003048 index = mInputs.indexOfKey(io);
3049 if (index < 0) {
3050 ALOGW("registerEffect() unknown io %d", io);
3051 return INVALID_OPERATION;
3052 }
Eric Laurente552edb2014-03-10 17:42:56 -07003053 }
3054 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003055 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3056 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3057 || strategy == PRODUCT_STRATEGY_NONE));
3058 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003059}
3060
Eric Laurentc241b0d2018-11-28 09:08:49 -08003061status_t AudioPolicyManager::unregisterEffect(int id)
3062{
3063 if (mEffects.getEffect(id) == nullptr) {
3064 return INVALID_OPERATION;
3065 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003066 if (mEffects.isEffectEnabled(id)) {
3067 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3068 setEffectEnabled(id, false);
3069 }
3070 return mEffects.unregisterEffect(id);
3071}
3072
3073status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3074{
3075 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3076 if (effect == nullptr) {
3077 return INVALID_OPERATION;
3078 }
3079
3080 status_t status = mEffects.setEffectEnabled(id, enabled);
3081 if (status == NO_ERROR) {
3082 mInputs.trackEffectEnabled(effect, enabled);
3083 }
3084 return status;
3085}
3086
Eric Laurent6c796322019-04-09 14:13:17 -07003087
3088status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3089{
3090 mEffects.moveEffects(ids, io);
3091 return NO_ERROR;
3092}
3093
Eric Laurentc75307b2015-03-17 15:29:32 -07003094bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3095{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003096 auto vs = toVolumeSource(stream, false);
3097 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003098}
3099
3100bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3101{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003102 auto vs = toVolumeSource(stream, false);
3103 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003104}
3105
Eric Laurente0720872014-03-11 09:30:41 -07003106bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003107{
3108 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003109 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003110 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003111 return true;
3112 }
3113 }
3114 return false;
3115}
3116
Eric Laurent275e8e92014-11-30 15:14:47 -08003117// Register a list of custom mixes with their attributes and format.
3118// When a mix is registered, corresponding input and output profiles are
3119// added to the remote submix hw module. The profile contains only the
3120// parameters (sampling rate, format...) specified by the mix.
3121// The corresponding input remote submix device is also connected.
3122//
3123// When a remote submix device is connected, the address is checked to select the
3124// appropriate profile and the corresponding input or output stream is opened.
3125//
3126// When capture starts, getInputForAttr() will:
3127// - 1 look for a mix matching the address passed in attribtutes tags if any
3128// - 2 if none found, getDeviceForInputSource() will:
3129// - 2.1 look for a mix matching the attributes source
3130// - 2.2 if none found, default to device selection by policy rules
3131// At this time, the corresponding output remote submix device is also connected
3132// and active playback use cases can be transferred to this mix if needed when reconnecting
3133// after AudioTracks are invalidated
3134//
3135// When playback starts, getOutputForAttr() will:
3136// - 1 look for a mix matching the address passed in attribtutes tags if any
3137// - 2 if none found, look for a mix matching the attributes usage
3138// - 3 if none found, default to device and output selection by policy rules.
3139
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003140status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003141{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003142 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3143 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003144 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003145 sp<HwModule> rSubmixModule;
3146 // examine each mix's route type
3147 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003148 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003149 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3150 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3151 ALOGE("Unsupported Policy Mix %zu of %zu: "
3152 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3153 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003154 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003155 break;
3156 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003157 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3158 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003159 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003160 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3161 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003162 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003163 rSubmixModule = mHwModules.getModuleFromName(
3164 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3165 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003166 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003167 i);
3168 res = INVALID_OPERATION;
3169 break;
3170 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003171 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003172
Eric Laurent97ac8712018-07-27 18:59:02 -07003173 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003174 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003175 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003176 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003177 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3178 } else {
3179 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3180 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003181 }
François Gaffie036e1e92015-03-19 10:16:24 +01003182
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003183 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003184 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003185 res = INVALID_OPERATION;
3186 break;
3187 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003188 audio_config_t outputConfig = mix.mFormat;
3189 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003190 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3191 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003192 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3193 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003194 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003196 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003197 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003198
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003199 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003200 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3201 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3202 ALOGE("Failed to set remote submix device available, type %u, address %s",
3203 mix.mDeviceType, address.string());
3204 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003205 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003206 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3207 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003208 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003209 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003210 i, mixes.size(), type, address.string());
3211
3212 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3213 mix.mDeviceType, mix.mDeviceAddress,
3214 String8(), AUDIO_FORMAT_DEFAULT);
3215 if (device == nullptr) {
3216 res = INVALID_OPERATION;
3217 break;
3218 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003219
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003220 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003221 // First try to find an already opened output supporting the device
3222 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003223 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003224
Eric Laurentc529cf62020-04-17 18:19:10 -07003225 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003226 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003227 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3228 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003229 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003230 } else {
3231 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003232 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003233 }
3234 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003235 // If no output found, try to find a direct output profile supporting the device
3236 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3237 sp<HwModule> module = mHwModules[i];
3238 for (size_t j = 0;
3239 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3240 j++) {
3241 sp<IOProfile> profile = module->getOutputProfiles()[j];
3242 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3243 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3244 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3245 address.string());
3246 res = INVALID_OPERATION;
3247 } else {
3248 foundOutput = true;
3249 }
3250 }
3251 }
3252 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003253 if (res != NO_ERROR) {
3254 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003255 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003256 res = INVALID_OPERATION;
3257 break;
3258 } else if (!foundOutput) {
3259 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003260 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003261 res = INVALID_OPERATION;
3262 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003263 } else {
3264 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265 }
Eric Laurentc722f302014-12-10 11:21:49 -08003266 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003267 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268 if (res != NO_ERROR) {
3269 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003270 } else if (checkOutputs) {
3271 checkForDeviceAndOutputChanges();
3272 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003273 }
3274 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003275}
3276
3277status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3278{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003279 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003280 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003281 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003282 sp<HwModule> rSubmixModule;
3283 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003284 for (const auto& mix : mixes) {
3285 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003286
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003287 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003288 rSubmixModule = mHwModules.getModuleFromName(
3289 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3290 if (rSubmixModule == 0) {
3291 res = INVALID_OPERATION;
3292 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003293 }
3294 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003295
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003296 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003297
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003298 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003299 res = INVALID_OPERATION;
3300 continue;
3301 }
3302
Kevin Rocard04ed0462019-05-02 17:53:24 -07003303 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3304 if (getDeviceConnectionState(device, address.string()) ==
3305 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3306 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3307 address.string(), "remote-submix",
3308 AUDIO_FORMAT_DEFAULT);
3309 if (res != OK) {
3310 ALOGE("Error making RemoteSubmix device unavailable for mix "
3311 "with type %d, address %s", device, address.string());
3312 }
3313 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003314 }
jiabin5740f082019-08-19 15:08:30 -07003315 rSubmixModule->removeOutputProfile(address.c_str());
3316 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003317
Kevin Rocard153f92d2018-12-18 18:33:28 -08003318 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003319 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003320 res = INVALID_OPERATION;
3321 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003322 } else {
3323 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003324 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003325 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003326 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003327 if (res == NO_ERROR && checkOutputs) {
3328 checkForDeviceAndOutputChanges();
3329 updateCallAndOutputRouting();
3330 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003331 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003332}
3333
Mikhail Naganov100f0122018-11-29 11:22:16 -08003334void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3335{
3336 size_t i = 0;
3337 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3338 for (const auto& fmt : mManualSurroundFormats) {
3339 if (i++ != 0) dst->append(", ");
3340 std::string sfmt;
3341 FormatConverter::toString(fmt, sfmt);
3342 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3343 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3344 }
3345}
3346
Eric Laurentc529cf62020-04-17 18:19:10 -07003347// Returns true if all devices types match the predicate and are supported by one HW module
3348bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003349 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003350 std::function<bool(audio_devices_t)> predicate,
3351 const char *context) {
3352 for (size_t i = 0; i < devices.size(); i++) {
3353 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003354 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003355 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003356 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003357 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003358 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003359 return false;
3360 }
3361 }
3362 return true;
3363}
3364
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003365status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003366 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003367 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003368 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3369 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003370 }
3371 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003372 if (res != NO_ERROR) {
3373 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3374 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003375 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003376
3377 checkForDeviceAndOutputChanges();
3378 updateCallAndOutputRouting();
3379
3380 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003381}
3382
3383status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3384 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003385 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3386 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003387 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003388 __FUNCTION__, uid);
3389 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003390 }
3391
Eric Laurentc529cf62020-04-17 18:19:10 -07003392 checkForDeviceAndOutputChanges();
3393 updateCallAndOutputRouting();
3394
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003395 return res;
3396}
3397
Eric Laurent2517af32020-11-25 15:31:27 +01003398
jiabin0a488932020-08-07 17:32:40 -07003399status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3400 device_role_t role,
3401 const AudioDeviceTypeAddrVector &devices) {
3402 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3403 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003404
Eric Laurentc529cf62020-04-17 18:19:10 -07003405 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003406 return BAD_VALUE;
3407 }
jiabin0a488932020-08-07 17:32:40 -07003408 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003409 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003410 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3411 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003412 return status;
3413 }
3414
3415 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003416
3417 bool forceVolumeReeval = false;
3418 // FIXME: workaround for truncated touch sounds
3419 // to be removed when the problem is handled by system UI
3420 uint32_t delayMs = 0;
3421 if (strategy == mCommunnicationStrategy) {
3422 forceVolumeReeval = true;
3423 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3424 updateInputRouting();
3425 }
3426 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003427
3428 return NO_ERROR;
3429}
3430
3431void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3432{
3433 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003434 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003435 // Only apply special touch sound delay once
3436 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003437 }
3438 for (size_t i = 0; i < mOutputs.size(); i++) {
3439 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3440 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3441 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3442 // As done in setDeviceConnectionState, we could also fix default device issue by
3443 // preventing the force re-routing in case of default dev that distinguishes on address.
3444 // Let's give back to engine full device choice decision however.
3445 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003446 // Only apply special touch sound delay once
3447 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003448 }
3449 if (forceVolumeReeval && !newDevices.isEmpty()) {
3450 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3451 }
3452 }
3453}
3454
Eric Laurent2517af32020-11-25 15:31:27 +01003455void AudioPolicyManager::updateInputRouting() {
3456 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303457 // Skip for hotword recording as the input device switch
3458 // is handled within sound trigger HAL
3459 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3460 continue;
3461 }
Eric Laurent2517af32020-11-25 15:31:27 +01003462 auto newDevice = getNewInputDevice(activeDesc);
3463 // Force new input selection if the new device can not be reached via current input
3464 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3465 setInputDevice(activeDesc->mIoHandle, newDevice);
3466 } else {
3467 closeInput(activeDesc->mIoHandle);
3468 }
3469 }
3470}
3471
jiabin0a488932020-08-07 17:32:40 -07003472status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3473 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003474{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003475 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003476
jiabin0a488932020-08-07 17:32:40 -07003477 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003478 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003479 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3480 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003481 return status;
3482 }
3483
3484 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003485
3486 bool forceVolumeReeval = false;
3487 // FIXME: workaround for truncated touch sounds
3488 // to be removed when the problem is handled by system UI
3489 uint32_t delayMs = 0;
3490 if (strategy == mCommunnicationStrategy) {
3491 forceVolumeReeval = true;
3492 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3493 updateInputRouting();
3494 }
3495 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003496
3497 return NO_ERROR;
3498}
3499
jiabin0a488932020-08-07 17:32:40 -07003500status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3501 device_role_t role,
3502 AudioDeviceTypeAddrVector &devices) {
3503 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003504}
3505
Jiabin Huang3b98d322020-09-03 17:54:16 +00003506status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3507 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3508 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3509 dumpAudioDeviceTypeAddrVector(devices).c_str());
3510
Mikhail Naganov55773032020-10-01 15:08:13 -07003511 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003512 return BAD_VALUE;
3513 }
3514 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3515 ALOGW_IF(status != NO_ERROR,
3516 "Engine could not set preferred devices %s for audio source %d role %d",
3517 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3518
3519 return status;
3520}
3521
3522status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3523 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3524 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3525 dumpAudioDeviceTypeAddrVector(devices).c_str());
3526
Mikhail Naganov55773032020-10-01 15:08:13 -07003527 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003528 return BAD_VALUE;
3529 }
3530 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3531 ALOGW_IF(status != NO_ERROR,
3532 "Engine could not add preferred devices %s for audio source %d role %d",
3533 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3534
Eric Laurent2517af32020-11-25 15:31:27 +01003535 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003536 return status;
3537}
3538
3539status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3540 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3541{
3542 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3543 dumpAudioDeviceTypeAddrVector(devices).c_str());
3544
Mikhail Naganov55773032020-10-01 15:08:13 -07003545 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003546 return BAD_VALUE;
3547 }
3548
3549 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3550 audioSource, role, devices);
3551 ALOGW_IF(status != NO_ERROR,
3552 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3553
Eric Laurent2517af32020-11-25 15:31:27 +01003554 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003555 return status;
3556}
3557
3558status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3559 device_role_t role) {
3560 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3561
3562 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3563 ALOGW_IF(status != NO_ERROR,
3564 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3565
Eric Laurent2517af32020-11-25 15:31:27 +01003566 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003567 return status;
3568}
3569
3570status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3571 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3572 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3573}
3574
Oscar Azucena90e77632019-11-27 17:12:28 -08003575status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003576 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003577 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003578 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3579 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003580 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003581 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3582 if (status != NO_ERROR) {
3583 ALOGE("%s() could not set device affinity for userId %d",
3584 __FUNCTION__, userId);
3585 return status;
3586 }
3587
3588 // reevaluate outputs for all devices
3589 checkForDeviceAndOutputChanges();
3590 updateCallAndOutputRouting();
3591
3592 return NO_ERROR;
3593}
3594
3595status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003596 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003597 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3598 if (status != NO_ERROR) {
3599 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3600 __FUNCTION__, userId);
3601 return status;
3602 }
3603
3604 // reevaluate outputs for all devices
3605 checkForDeviceAndOutputChanges();
3606 updateCallAndOutputRouting();
3607
3608 return NO_ERROR;
3609}
3610
Andy Hungc29d82b2018-10-05 12:23:17 -07003611void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003612{
Andy Hungc29d82b2018-10-05 12:23:17 -07003613 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3614 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003615 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003616 std::string stateLiteral;
3617 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003618 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003619 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3620 "communications", "media", "record", "dock", "system",
3621 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3622 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3623 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003624 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3625 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3626 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3627 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3628 dst->append(" (MANUAL: ");
3629 dumpManualSurroundFormats(dst);
3630 dst->append(")");
3631 }
3632 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003633 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003634 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3635 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003636 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003637 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003638
Andy Hungc29d82b2018-10-05 12:23:17 -07003639 mAvailableOutputDevices.dump(dst, String8("Available output"));
3640 mAvailableInputDevices.dump(dst, String8("Available input"));
3641 mHwModulesAll.dump(dst);
3642 mOutputs.dump(dst);
3643 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003644 mEffects.dump(dst);
3645 mAudioPatches.dump(dst);
3646 mPolicyMixes.dump(dst);
3647 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003648
Kevin Rocardb99cc752019-03-21 20:52:24 -07003649 dst->appendFormat(" AllowedCapturePolicies:\n");
3650 for (auto& policy : mAllowedCapturePolicies) {
3651 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3652 }
3653
François Gaffiec005e562018-11-06 15:04:49 +01003654 dst->appendFormat("\nPolicy Engine dump:\n");
3655 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003656}
3657
3658status_t AudioPolicyManager::dump(int fd)
3659{
3660 String8 result;
3661 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003662 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003663 return NO_ERROR;
3664}
3665
Kevin Rocardb99cc752019-03-21 20:52:24 -07003666status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3667{
3668 mAllowedCapturePolicies[uid] = capturePolicy;
3669 return NO_ERROR;
3670}
3671
Eric Laurente552edb2014-03-10 17:42:56 -07003672// This function checks for the parameters which can be offloaded.
3673// This can be enhanced depending on the capability of the DSP and policy
3674// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003675audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003676{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003677 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003678 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003679 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003680 offloadInfo.format,
3681 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3682 offloadInfo.has_video);
3683
Andy Hung2ddee192015-12-18 17:34:44 -08003684 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003685 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003686 }
3687
Eric Laurente552edb2014-03-10 17:42:56 -07003688 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003689 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003690 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3691 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003692 }
3693
3694 // Check if stream type is music, then only allow offload as of now.
3695 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3696 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003697 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3698 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003699 }
3700
3701 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003702 const bool allowOffloadWithVideo =
3703 property_get_bool("audio.offload.video", false /* default_value */);
3704 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003705 ALOGV("%s: has_video == true, returning false", __func__);
3706 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003707 }
3708
3709 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003710 const int min_duration_secs = property_get_int32(
3711 "audio.offload.min.duration.secs", -1 /* default_value */);
3712 if (min_duration_secs >= 0) {
3713 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003714 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3715 __func__, min_duration_secs);
3716 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003717 }
3718 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003719 ALOGV("%s: Offload denied by duration < default min(=%u)",
3720 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3721 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
3723
3724 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3725 // creating an offloaded track and tearing it down immediately after start when audioflinger
3726 // detects there is an active non offloadable effect.
3727 // FIXME: We should check the audio session here but we do not have it in this context.
3728 // This may prevent offloading in rare situations where effects are left active by apps
3729 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003730 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003731 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003732 }
3733
3734 // See if there is a profile to support this.
3735 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003736 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003737 offloadInfo.sample_rate,
3738 offloadInfo.format,
3739 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003740 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3741 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003742 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3743 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3744 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003745 if (profile == nullptr) {
3746 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3747 }
3748 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3749 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3750 }
3751 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003752}
3753
Michael Chana94fbb22018-04-24 14:31:19 +10003754bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3755 const audio_attributes_t& attributes) {
3756 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003757 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003758 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003759 config.sample_rate,
3760 config.format,
3761 config.channel_mask,
3762 output_flags,
3763 true /* directOnly */);
3764 ALOGV("%s() profile %sfound with name: %s, "
3765 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3766 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003767 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003768 config.sample_rate, config.format, config.channel_mask, output_flags);
3769 return (profile != 0);
3770}
3771
Eric Laurent6a94d692014-05-20 11:18:06 -07003772status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3773 audio_port_type_t type,
3774 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003775 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003776 unsigned int *generation)
3777{
jiabin19cdba52020-11-24 11:28:58 -08003778 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3779 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003780 return BAD_VALUE;
3781 }
3782 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003783 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003784 *num_ports = 0;
3785 }
3786
3787 size_t portsWritten = 0;
3788 size_t portsMax = *num_ports;
3789 *num_ports = 0;
3790 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003791 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3792 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003793 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003794 for (const auto& dev : mAvailableOutputDevices) {
3795 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003796 continue;
3797 }
3798 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003799 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003800 }
3801 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003802 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003803 }
3804 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003805 for (const auto& dev : mAvailableInputDevices) {
3806 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003807 continue;
3808 }
3809 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003810 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003811 }
3812 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003813 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003814 }
3815 }
3816 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3817 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3818 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3819 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3820 }
3821 *num_ports += mInputs.size();
3822 }
3823 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003824 size_t numOutputs = 0;
3825 for (size_t i = 0; i < mOutputs.size(); i++) {
3826 if (!mOutputs[i]->isDuplicated()) {
3827 numOutputs++;
3828 if (portsWritten < portsMax) {
3829 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3830 }
3831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 }
Eric Laurent84c70242014-06-23 08:46:27 -07003833 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003834 }
3835 }
3836 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003837 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 return NO_ERROR;
3839}
3840
jiabin19cdba52020-11-24 11:28:58 -08003841status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003842{
Eric Laurent99fcae42018-05-17 16:59:18 -07003843 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3844 return BAD_VALUE;
3845 }
3846 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3847 if (dev != 0) {
3848 dev->toAudioPort(port);
3849 return NO_ERROR;
3850 }
3851 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3852 if (dev != 0) {
3853 dev->toAudioPort(port);
3854 return NO_ERROR;
3855 }
3856 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3857 if (out != 0) {
3858 out->toAudioPort(port);
3859 return NO_ERROR;
3860 }
3861 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3862 if (in != 0) {
3863 in->toAudioPort(port);
3864 return NO_ERROR;
3865 }
3866 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003867}
3868
François Gaffieafd4cea2019-11-18 15:50:22 +01003869status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3870 audio_patch_handle_t *handle,
3871 uid_t uid, uint32_t delayMs,
3872 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003873{
François Gaffieafd4cea2019-11-18 15:50:22 +01003874 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003875 if (handle == NULL || patch == NULL) {
3876 return BAD_VALUE;
3877 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003878 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003879
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003880 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003881 return BAD_VALUE;
3882 }
3883 // only one source per audio patch supported for now
3884 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003885 return INVALID_OPERATION;
3886 }
Eric Laurent874c42872014-08-08 15:13:39 -07003887
3888 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 return INVALID_OPERATION;
3890 }
Eric Laurent874c42872014-08-08 15:13:39 -07003891 for (size_t i = 0; i < patch->num_sinks; i++) {
3892 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3893 return INVALID_OPERATION;
3894 }
3895 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003896
3897 sp<AudioPatch> patchDesc;
3898 ssize_t index = mAudioPatches.indexOfKey(*handle);
3899
François Gaffieafd4cea2019-11-18 15:50:22 +01003900 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3901 patch->sources[0].role,
3902 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003903#if LOG_NDEBUG == 0
3904 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003905 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3906 patch->sinks[i].role,
3907 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003908 }
3909#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003910
3911 if (index >= 0) {
3912 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003913 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3914 __func__, mUidCached, patchDesc->getUid(), uid);
3915 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003916 return INVALID_OPERATION;
3917 }
3918 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003919 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 }
3921
3922 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003923 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003925 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 return BAD_VALUE;
3927 }
Eric Laurent84c70242014-06-23 08:46:27 -07003928 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3929 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003930 if (patchDesc != 0) {
3931 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003932 ALOGV("%s source id differs for patch current id %d new id %d",
3933 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003934 return BAD_VALUE;
3935 }
3936 }
Eric Laurent874c42872014-08-08 15:13:39 -07003937 DeviceVector devices;
3938 for (size_t i = 0; i < patch->num_sinks; i++) {
3939 // Only support mix to devices connection
3940 // TODO add support for mix to mix connection
3941 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003942 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003943 return INVALID_OPERATION;
3944 }
3945 sp<DeviceDescriptor> devDesc =
3946 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3947 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003948 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003949 return BAD_VALUE;
3950 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003951
François Gaffie11d30102018-11-02 16:09:09 +01003952 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003953 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003954 NULL, // updatedSamplingRate
3955 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003956 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003957 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003958 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003959 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003960 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003961 return INVALID_OPERATION;
3962 }
3963 devices.add(devDesc);
3964 }
3965 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 return INVALID_OPERATION;
3967 }
Eric Laurent874c42872014-08-08 15:13:39 -07003968
Eric Laurent6a94d692014-05-20 11:18:06 -07003969 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003970 ALOGV("%s setting device %s on output %d",
3971 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003972 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003973 index = mAudioPatches.indexOfKey(*handle);
3974 if (index >= 0) {
3975 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003976 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003977 }
3978 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003979 patchDesc->setUid(uid);
3980 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003981 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003982 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003983 return INVALID_OPERATION;
3984 }
3985 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3986 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3987 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003988 // only one sink supported when connecting an input device to a mix
3989 if (patch->num_sinks > 1) {
3990 return INVALID_OPERATION;
3991 }
François Gaffie53615e22015-03-19 09:24:12 +01003992 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003993 if (inputDesc == NULL) {
3994 return BAD_VALUE;
3995 }
3996 if (patchDesc != 0) {
3997 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3998 return BAD_VALUE;
3999 }
4000 }
François Gaffie11d30102018-11-02 16:09:09 +01004001 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004002 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004003 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004004 return BAD_VALUE;
4005 }
4006
François Gaffie11d30102018-11-02 16:09:09 +01004007 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004008 patch->sinks[0].sample_rate,
4009 NULL, /*updatedSampleRate*/
4010 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004011 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004012 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004013 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004014 // FIXME for the parameter type,
4015 // and the NONE
4016 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004017 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004018 return INVALID_OPERATION;
4019 }
4020 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004021 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004022 device->toString().c_str(), inputDesc->mIoHandle);
4023 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004024 index = mAudioPatches.indexOfKey(*handle);
4025 if (index >= 0) {
4026 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004027 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004028 }
4029 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004030 patchDesc->setUid(uid);
4031 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004032 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004033 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004034 return INVALID_OPERATION;
4035 }
4036 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4037 // device to device connection
4038 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004039 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004040 return BAD_VALUE;
4041 }
4042 }
François Gaffie11d30102018-11-02 16:09:09 +01004043 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004044 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004045 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004046 return BAD_VALUE;
4047 }
Eric Laurent874c42872014-08-08 15:13:39 -07004048
Eric Laurent6a94d692014-05-20 11:18:06 -07004049 //update source and sink with our own data as the data passed in the patch may
4050 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004051 PatchBuilder patchBuilder;
4052 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004053
4054 // if first sink is to MSD, establish single MSD patch
4055 if (getMsdAudioOutDevices().contains(
4056 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4057 ALOGV("%s patching to MSD", __FUNCTION__);
4058 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4059 goto installPatch;
4060 }
4061
François Gaffieafd4cea2019-11-18 15:50:22 +01004062 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4063 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004064
Eric Laurent874c42872014-08-08 15:13:39 -07004065 for (size_t i = 0; i < patch->num_sinks; i++) {
4066 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004067 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004068 return INVALID_OPERATION;
4069 }
François Gaffie11d30102018-11-02 16:09:09 +01004070 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004071 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004072 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004073 return BAD_VALUE;
4074 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004075 audio_port_config sinkPortConfig = {};
4076 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4077 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004078
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004079 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4080 // volume management purpose (tracking activity)
4081 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4082 // in config XML to reach the sink so that is can be declared as available.
4083 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4084 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4085 if (sourceDesc != nullptr) {
4086 // take care of dynamic routing for SwOutput selection,
4087 audio_attributes_t attributes = sourceDesc->attributes();
4088 audio_stream_type_t stream = sourceDesc->stream();
4089 audio_attributes_t resultAttr;
4090 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4091 config.sample_rate = sourceDesc->config().sample_rate;
4092 config.channel_mask = sourceDesc->config().channel_mask;
4093 config.format = sourceDesc->config().format;
4094 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4095 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4096 bool isRequestedDeviceForExclusiveUse = false;
4097 output_type_t outputType;
4098 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4099 &stream, sourceDesc->uid(), &config, &flags,
4100 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4101 nullptr, &outputType);
4102 if (output == AUDIO_IO_HANDLE_NONE) {
4103 ALOGV("%s no output for device %s",
4104 __FUNCTION__, sinkDevice->toString().c_str());
4105 return INVALID_OPERATION;
4106 }
4107 outputDesc = mOutputs.valueFor(output);
4108 if (outputDesc->isDuplicated()) {
4109 ALOGE("%s output is duplicated", __func__);
4110 return INVALID_OPERATION;
4111 }
4112 sourceDesc->setSwOutput(outputDesc);
4113 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004114 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004115 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004116 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004117 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004118 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4119 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004120 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4121 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004122 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4123 (sourceDesc != nullptr &&
4124 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004125 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004126 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004127 return INVALID_OPERATION;
4128 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004129 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004130 SortedVector<audio_io_handle_t> outputs =
4131 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4132 // if the sink device is reachable via an opened output stream, request to
4133 // go via this output stream by adding a second source to the patch
4134 // description
4135 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004136 if (output != AUDIO_IO_HANDLE_NONE) {
4137 outputDesc = mOutputs.valueFor(output);
4138 if (outputDesc->isDuplicated()) {
4139 ALOGV("%s output for device %s is duplicated",
4140 __FUNCTION__, sinkDevice->toString().c_str());
4141 return INVALID_OPERATION;
4142 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004143 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004144 }
4145 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 audio_port_config srcMixPortConfig = {};
4147 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004148 // for volume control, we may need a valid stream
4149 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4150 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4151 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004152 }
Eric Laurent83b88082014-06-20 18:31:16 -07004153 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 }
4155 // TODO: check from routing capabilities in config file and other conflicting patches
4156
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004157installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004158 status_t status = installPatch(
4159 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004160 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004161 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004162 return INVALID_OPERATION;
4163 }
4164 } else {
4165 return BAD_VALUE;
4166 }
4167 } else {
4168 return BAD_VALUE;
4169 }
4170 return NO_ERROR;
4171}
4172
4173status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4174 uid_t uid)
4175{
4176 ALOGV("releaseAudioPatch() patch %d", handle);
4177
4178 ssize_t index = mAudioPatches.indexOfKey(handle);
4179
4180 if (index < 0) {
4181 return BAD_VALUE;
4182 }
4183 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004184 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4185 __func__, mUidCached, patchDesc->getUid(), uid);
4186 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 return INVALID_OPERATION;
4188 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004189 return releaseAudioPatchInternal(handle);
4190}
Eric Laurent6a94d692014-05-20 11:18:06 -07004191
François Gaffieafd4cea2019-11-18 15:50:22 +01004192status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4193 uint32_t delayMs)
4194{
4195 ALOGV("%s patch %d", __func__, handle);
4196 if (mAudioPatches.indexOfKey(handle) < 0) {
4197 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4198 return BAD_VALUE;
4199 }
4200 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004201 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004202 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004204 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004205 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004206 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 return BAD_VALUE;
4208 }
4209
François Gaffie11d30102018-11-02 16:09:09 +01004210 setOutputDevices(outputDesc,
4211 getNewOutputDevices(outputDesc, true /*fromCache*/),
4212 true,
4213 0,
4214 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4216 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004217 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004219 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 return BAD_VALUE;
4221 }
4222 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004223 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004224 true,
4225 NULL);
4226 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004227 status_t status =
4228 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4229 ALOGV("%s patch panel returned %d patchHandle %d",
4230 __func__, status, patchDesc->getAfHandle());
4231 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004233 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004234 // SW Bridge
4235 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4236 sp<SwAudioOutputDescriptor> outputDesc =
4237 mOutputs.getOutputFromId(patch->sources[1].id);
4238 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004239 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4240 // releaseOutput has already called closeOuput in case of direct output
4241 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004242 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004243 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4244 // force SwOutput patch removal as AF counter part patch has already gone.
4245 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4246 removeAudioPatch(outputDesc->getPatchHandle());
4247 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004248 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4249 setOutputDevices(outputDesc,
4250 getNewOutputDevices(outputDesc, true /*fromCache*/),
4251 true, /*force*/
4252 0,
4253 NULL);
4254 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004255 } else {
4256 return BAD_VALUE;
4257 }
4258 } else {
4259 return BAD_VALUE;
4260 }
4261 return NO_ERROR;
4262}
4263
4264status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4265 struct audio_patch *patches,
4266 unsigned int *generation)
4267{
François Gaffie53615e22015-03-19 09:24:12 +01004268 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004269 return BAD_VALUE;
4270 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004271 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004272 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004273}
4274
Eric Laurente1715a42014-05-20 11:30:42 -07004275status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004276{
Eric Laurente1715a42014-05-20 11:30:42 -07004277 ALOGV("setAudioPortConfig()");
4278
4279 if (config == NULL) {
4280 return BAD_VALUE;
4281 }
4282 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4283 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004284 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4285 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004286 }
4287
Eric Laurenta121f902014-06-03 13:32:54 -07004288 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004289 if (config->type == AUDIO_PORT_TYPE_MIX) {
4290 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004291 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004292 if (outputDesc == NULL) {
4293 return BAD_VALUE;
4294 }
Eric Laurent84c70242014-06-23 08:46:27 -07004295 ALOG_ASSERT(!outputDesc->isDuplicated(),
4296 "setAudioPortConfig() called on duplicated output %d",
4297 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004298 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004299 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004300 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004301 if (inputDesc == NULL) {
4302 return BAD_VALUE;
4303 }
Eric Laurenta121f902014-06-03 13:32:54 -07004304 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004305 } else {
4306 return BAD_VALUE;
4307 }
4308 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4309 sp<DeviceDescriptor> deviceDesc;
4310 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4311 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4312 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4313 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4314 } else {
4315 return BAD_VALUE;
4316 }
4317 if (deviceDesc == NULL) {
4318 return BAD_VALUE;
4319 }
Eric Laurenta121f902014-06-03 13:32:54 -07004320 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004321 } else {
4322 return BAD_VALUE;
4323 }
4324
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004325 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004326 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4327 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004328 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004329 audioPortConfig->toAudioPortConfig(&newConfig, config);
4330 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004331 }
Eric Laurenta121f902014-06-03 13:32:54 -07004332 if (status != NO_ERROR) {
4333 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004334 }
Eric Laurente1715a42014-05-20 11:30:42 -07004335
4336 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004337}
4338
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004339void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4340{
Eric Laurentd60560a2015-04-10 11:31:20 -07004341 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004342 clearAudioPatches(uid);
4343 clearSessionRoutes(uid);
4344}
4345
Eric Laurent6a94d692014-05-20 11:18:06 -07004346void AudioPolicyManager::clearAudioPatches(uid_t uid)
4347{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004348 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004349 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004350 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004351 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004352 }
4353 }
4354}
4355
François Gaffiec005e562018-11-06 15:04:49 +01004356void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004357{
François Gaffiec005e562018-11-06 15:04:49 +01004358 // Take the first attributes following the product strategy as it is used to retrieve the routed
4359 // device. All attributes wihin a strategy follows the same "routing strategy"
4360 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4361 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004362 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004363 for (size_t j = 0; j < mOutputs.size(); j++) {
4364 if (mOutputs.keyAt(j) == ouptutToSkip) {
4365 continue;
4366 }
4367 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004368 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004369 continue;
4370 }
4371 // If the default device for this strategy is on another output mix,
4372 // invalidate all tracks in this strategy to force re connection.
4373 // Otherwise select new device on the output mix.
4374 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004375 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4376 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004377 }
4378 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004379 setOutputDevices(
4380 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004381 }
4382 }
4383}
4384
4385void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4386{
4387 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004388 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004389 for (size_t i = 0; i < mOutputs.size(); i++) {
4390 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004391 for (const auto& client : outputDesc->getClientIterable()) {
4392 if (client->hasPreferredDevice() && client->uid() == uid) {
4393 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004394 auto clientStrategy = client->strategy();
4395 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4396 end(affectedStrategies)) {
4397 continue;
4398 }
4399 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004400 }
4401 }
4402 }
4403 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004404 for (const auto& strategy : affectedStrategies) {
4405 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004406 }
4407
4408 // remove input routes associated with this uid
4409 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004410 for (size_t i = 0; i < mInputs.size(); i++) {
4411 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004412 for (const auto& client : inputDesc->getClientIterable()) {
4413 if (client->hasPreferredDevice() && client->uid() == uid) {
4414 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4415 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004416 }
4417 }
4418 }
4419 // reroute inputs if necessary
4420 SortedVector<audio_io_handle_t> inputsToClose;
4421 for (size_t i = 0; i < mInputs.size(); i++) {
4422 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004423 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004424 inputsToClose.add(inputDesc->mIoHandle);
4425 }
4426 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004427 for (const auto& input : inputsToClose) {
4428 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004429 }
4430}
4431
Eric Laurentd60560a2015-04-10 11:31:20 -07004432void AudioPolicyManager::clearAudioSources(uid_t uid)
4433{
4434 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004435 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4436 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004437 stopAudioSource(mAudioSources.keyAt(i));
4438 }
4439 }
4440}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004441
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004442status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4443 audio_io_handle_t *ioHandle,
4444 audio_devices_t *device)
4445{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004446 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4447 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004448 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004449 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004450
François Gaffiedf372692015-03-19 10:43:27 +01004451 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004452}
4453
Eric Laurentd60560a2015-04-10 11:31:20 -07004454status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004455 const audio_attributes_t *attributes,
4456 audio_port_handle_t *portId,
4457 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004458{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004459 ALOGV("%s", __FUNCTION__);
4460 *portId = AUDIO_PORT_HANDLE_NONE;
4461
4462 if (source == NULL || attributes == NULL || portId == NULL) {
4463 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4464 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004465 return BAD_VALUE;
4466 }
4467
Eric Laurentd60560a2015-04-10 11:31:20 -07004468 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4469 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004470 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4471 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004472 return INVALID_OPERATION;
4473 }
4474
François Gaffie11d30102018-11-02 16:09:09 +01004475 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004476 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004477 String8(source->ext.device.address),
4478 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004479 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004480 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004481 return BAD_VALUE;
4482 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004483
jiabin4ef93452019-09-10 14:29:54 -07004484 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004485
François Gaffieaaac0fd2018-11-22 17:56:39 +01004486 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004488 mEngine->getStreamTypeForAttributes(*attributes),
4489 mEngine->getProductStrategyForAttributes(*attributes),
4490 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004491
4492 status_t status = connectAudioSource(sourceDesc);
4493 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004494 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004495 }
4496 return status;
4497}
4498
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004499status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004500{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004501 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004502
4503 // make sure we only have one patch per source.
4504 disconnectAudioSource(sourceDesc);
4505
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004506 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004507 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4508 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4509 sourceDesc->srcDevice()->type(),
4510 String8(sourceDesc->srcDevice()->address().c_str()),
4511 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004512 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004513 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004514 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004515 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004516 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4517 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4518 return INVALID_OPERATION;
4519 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004520 PatchBuilder patchBuilder;
4521 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4522 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4523 status_t status =
4524 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4525 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4526 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4527 return INVALID_OPERATION;
4528 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004529 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004530 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4531 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4532 if (swOutput != 0) {
4533 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004534 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004535 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004536 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004537 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004538 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004539 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004540 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004541 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004542 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004543 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004544 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004545 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4546 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004547 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004548 if (delayMs != 0) {
4549 usleep(delayMs * 1000);
4550 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004551 } else {
4552 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4553 if (hwOutputDesc != 0) {
4554 // create Hwoutput and add to mHwOutputs
4555 } else {
4556 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4557 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004558 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004559 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004560
4561FailureSourceActive:
4562 swOutput->stop();
4563 releaseOutput(sourceDesc->portId());
4564FailureSourceAdded:
4565 sourceDesc->setSwOutput(nullptr);
4566FailureReleasePatch:
4567 releaseAudioPatchInternal(handle);
4568 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004569}
4570
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004571status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004572{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004573 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4574 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004575 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004576 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004577 return BAD_VALUE;
4578 }
4579 status_t status = disconnectAudioSource(sourceDesc);
4580
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004581 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004582 return status;
4583}
4584
Andy Hung2ddee192015-12-18 17:34:44 -08004585status_t AudioPolicyManager::setMasterMono(bool mono)
4586{
4587 if (mMasterMono == mono) {
4588 return NO_ERROR;
4589 }
4590 mMasterMono = mono;
4591 // if enabling mono we close all offloaded devices, which will invalidate the
4592 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4593 // for recreating the new AudioTrack as non-offloaded PCM.
4594 //
4595 // If disabling mono, we leave all tracks as is: we don't know which clients
4596 // and tracks are able to be recreated as offloaded. The next "song" should
4597 // play back offloaded.
4598 if (mMasterMono) {
4599 Vector<audio_io_handle_t> offloaded;
4600 for (size_t i = 0; i < mOutputs.size(); ++i) {
4601 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4602 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4603 offloaded.push(desc->mIoHandle);
4604 }
4605 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004606 for (const auto& handle : offloaded) {
4607 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004608 }
4609 }
4610 // update master mono for all remaining outputs
4611 for (size_t i = 0; i < mOutputs.size(); ++i) {
4612 updateMono(mOutputs.keyAt(i));
4613 }
4614 return NO_ERROR;
4615}
4616
4617status_t AudioPolicyManager::getMasterMono(bool *mono)
4618{
4619 *mono = mMasterMono;
4620 return NO_ERROR;
4621}
4622
Eric Laurentac9cef52017-06-09 15:46:26 -07004623float AudioPolicyManager::getStreamVolumeDB(
4624 audio_stream_type_t stream, int index, audio_devices_t device)
4625{
jiabin9a3361e2019-10-01 09:38:30 -07004626 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004627}
4628
jiabin81772902018-04-02 17:52:27 -07004629status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4630 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004631 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004632{
Kriti Dang6537def2021-03-02 13:46:59 +01004633 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4634 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004635 return BAD_VALUE;
4636 }
Kriti Dang6537def2021-03-02 13:46:59 +01004637 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4638 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004639
4640 size_t formatsWritten = 0;
4641 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004642
Kriti Dang6537def2021-03-02 13:46:59 +01004643 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004644 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4645 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004646 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004647 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004648 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004649 bool formatEnabled = true;
4650 switch (forceUse) {
4651 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004652 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004653 break;
4654 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4655 formatEnabled = false;
4656 break;
4657 default: // AUTO or ALWAYS => true
4658 break;
jiabin81772902018-04-02 17:52:27 -07004659 }
4660 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4661 }
jiabin81772902018-04-02 17:52:27 -07004662 }
4663 return NO_ERROR;
4664}
4665
Kriti Dang6537def2021-03-02 13:46:59 +01004666status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4667 audio_format_t *surroundFormats) {
4668 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4669 return BAD_VALUE;
4670 }
4671 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4672 __func__, *numSurroundFormats, surroundFormats);
4673
4674 size_t formatsWritten = 0;
4675 size_t formatsMax = *numSurroundFormats;
4676 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4677
4678 // Return formats from all device profiles that have already been resolved by
4679 // checkOutputsForDevice().
4680 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4681 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4682 audio_devices_t deviceType = device->type();
4683 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4684 // returns formats reported by HDMI devices.
4685 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4686 continue;
4687 }
4688 // Formats reported by sink devices
4689 std::unordered_set<audio_format_t> formatset;
4690 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4691 formatset.insert(it->second.begin(), it->second.end());
4692 }
4693
4694 // Formats hard-coded in the in policy configuration file (if any).
4695 FormatVector encodedFormats = device->encodedFormats();
4696 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4697 // Filter the formats which are supported by the vendor hardware.
4698 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4699 if (mConfig.getSurroundFormats().count(*it) != 0) {
4700 formats.insert(*it);
4701 } else {
4702 for (const auto& pair : mConfig.getSurroundFormats()) {
4703 if (pair.second.count(*it) != 0) {
4704 formats.insert(pair.first);
4705 break;
4706 }
4707 }
4708 }
4709 }
4710 }
4711 *numSurroundFormats = formats.size();
4712 for (const auto& format: formats) {
4713 if (formatsWritten < formatsMax) {
4714 surroundFormats[formatsWritten++] = format;
4715 }
4716 }
4717 return NO_ERROR;
4718}
4719
jiabin81772902018-04-02 17:52:27 -07004720status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4721{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004722 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004723 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4724 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004725 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004726 return BAD_VALUE;
4727 }
4728
Mikhail Naganov100f0122018-11-29 11:22:16 -08004729 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4730 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004731 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004732 return INVALID_OPERATION;
4733 }
4734
Mikhail Naganov100f0122018-11-29 11:22:16 -08004735 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004736 return NO_ERROR;
4737 }
4738
Mikhail Naganov100f0122018-11-29 11:22:16 -08004739 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004740 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004741 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004742 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004743 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004744 }
4745 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004746 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004747 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004748 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004749 }
4750 }
4751
4752 sp<SwAudioOutputDescriptor> outputDesc;
4753 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004754 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4755 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004756 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4757 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004758 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004759 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004760 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4761 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4762 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004763 name.c_str(),
4764 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004765 if (status != NO_ERROR) {
4766 continue;
4767 }
4768 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4769 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
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 profileUpdated |= (status == NO_ERROR);
4774 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004775 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004776 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004777 AUDIO_DEVICE_IN_HDMI);
4778 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4779 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004780 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004781 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004782 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4783 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4784 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004785 name.c_str(),
4786 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004787 if (status != NO_ERROR) {
4788 continue;
4789 }
4790 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4791 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4792 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004793 name.c_str(),
4794 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004795 profileUpdated |= (status == NO_ERROR);
4796 }
4797
jiabin81772902018-04-02 17:52:27 -07004798 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004799 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004800 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004801 }
4802
4803 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4804}
4805
Eric Laurent5ada82e2019-08-29 17:53:54 -07004806void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004807{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004808 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004809 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004810 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004811 }
4812}
4813
jiabin6012f912018-11-02 17:06:30 -07004814bool AudioPolicyManager::isHapticPlaybackSupported()
4815{
4816 for (const auto& hwModule : mHwModules) {
4817 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4818 for (const auto &outProfile : outputProfiles) {
4819 struct audio_port audioPort;
4820 outProfile->toAudioPort(&audioPort);
4821 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4822 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4823 return true;
4824 }
4825 }
4826 }
4827 }
4828 return false;
4829}
4830
Eric Laurent8340e672019-11-06 11:01:08 -08004831bool AudioPolicyManager::isCallScreenModeSupported()
4832{
4833 return getConfig().isCallScreenModeSupported();
4834}
4835
4836
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004837status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004838{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004839 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004840 if (!sourceDesc->isConnected()) {
4841 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4842 return NO_ERROR;
4843 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004844 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4845 if (swOutput != 0) {
4846 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004847 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004848 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004849 }
jiabinbce0c1d2020-10-05 11:20:18 -07004850 if (releaseOutput(sourceDesc->portId())) {
4851 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4852 // no need to release audio patch here but just return NO_ERROR.
4853 return NO_ERROR;
4854 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004855 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004856 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004857 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004858 // close Hwoutput and remove from mHwOutputs
4859 } else {
4860 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4861 }
4862 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004863 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4864 sourceDesc->disconnect();
4865 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004866}
4867
François Gaffiec005e562018-11-06 15:04:49 +01004868sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4869 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004870{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004871 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004872 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004873 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004874 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004875 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4876 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004877 source = sourceDesc;
4878 break;
4879 }
4880 }
4881 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004882}
4883
Eric Laurent39095982021-08-24 18:29:27 +02004884/* static */
4885bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
4886 switch (channels) {
4887 case AUDIO_CHANNEL_OUT_5POINT1:
4888 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
4889 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
4890 case AUDIO_CHANNEL_OUT_7POINT1:
4891 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
4892 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
4893 return true;
4894 default:
4895 return false;
4896 }
4897}
4898
Eric Laurentd23aa162022-01-17 17:37:31 +01004899bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004900 const audio_config_t *config,
Eric Laurentd23aa162022-01-17 17:37:31 +01004901 const AudioDeviceTypeAddrVector &devices,
4902 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004903{
4904 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4905 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004906 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004907 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02004908 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
4909 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4910 return false;
4911 }
4912 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
4913 return false;
4914 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004915 }
4916
4917 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004918 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4919 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004920 // to the specified devices must exist.
4921 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004922 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004923 if (profile == nullptr) {
4924 return false;
4925 }
4926
4927 // The caller can have the audio config criteria ignored by either passing a null ptr or
4928 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004929 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02004930 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004931 // If the spatializer output is already opened, only channel masks included in the
4932 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02004933
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004934 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02004935 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004936 return false;
4937 }
Eric Laurentd23aa162022-01-17 17:37:31 +01004938 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
4939 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004940 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004941 != config->channel_mask) {
4942 return false;
4943 }
4944 }
4945 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004946 return true;
4947}
4948
4949void AudioPolicyManager::checkVirtualizerClientRoutes() {
4950 std::set<audio_stream_type_t> streamsToInvalidate;
4951 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02004952 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
4953 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004954 audio_attributes_t attr = client->attributes();
4955 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4956 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4957 audio_config_base_t clientConfig = client->config();
4958 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02004959 if (desc != mSpatializerOutput
Eric Laurentd23aa162022-01-17 17:37:31 +01004960 && canBeSpatializedInt(&attr, &config,
4961 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004962 streamsToInvalidate.insert(client->stream());
4963 }
4964 }
4965 }
4966
4967 for (audio_stream_type_t stream : streamsToInvalidate) {
4968 mpClientInterface->invalidateStream(stream);
4969 }
4970}
4971
Eric Laurentfa0f6742021-08-17 18:39:44 +02004972status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004973 const audio_attributes_t *attr,
4974 audio_io_handle_t *output) {
4975 *output = AUDIO_IO_HANDLE_NONE;
4976
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004977 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4978 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4979 audio_config_t *configPtr = nullptr;
4980 audio_config_t config;
4981 if (mixerConfig != nullptr) {
4982 config = audio_config_initializer(mixerConfig);
4983 configPtr = &config;
4984 }
Eric Laurentd23aa162022-01-17 17:37:31 +01004985 if (!canBeSpatializedInt(
4986 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02004987 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004988 return BAD_VALUE;
4989 }
4990
4991 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004992 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004993 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02004994 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004995 return BAD_VALUE;
4996 }
4997
Eric Laurent39095982021-08-24 18:29:27 +02004998 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
4999 && configPtr != nullptr
5000 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5001 *output = mSpatializerOutput->mIoHandle;
5002 ALOGV("%s returns current spatializer output %d", __func__, *output);
5003 return NO_ERROR;
5004 }
5005 mSpatializerOutput.clear();
5006 for (size_t i = 0; i < mOutputs.size(); i++) {
5007 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5008 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentd23aa162022-01-17 17:37:31 +01005009 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005010 mSpatializerOutput = desc;
5011 break;
5012 }
5013 }
5014 if (mSpatializerOutput == nullptr) {
5015 ALOGW("%s no opened spatializer output for profile %s",
5016 __func__, profile->getName().c_str());
5017 return BAD_VALUE;
5018 }
5019
5020 if (configPtr != nullptr
5021 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5022 audio_config_base_t savedMixerConfig = {
5023 .sample_rate = mSpatializerOutput->getSamplingRate(),
5024 .format = mSpatializerOutput->getFormat(),
5025 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5026 };
5027 DeviceVector savedDevices = mSpatializerOutput->devices();
5028
Eric Laurentd23aa162022-01-17 17:37:31 +01005029 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5030 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005031
Eric Laurentd23aa162022-01-17 17:37:31 +01005032 closeOutput(mSpatializerOutput->mIoHandle);
5033 //from now on mSpatializerOutput is null
5034
5035 sp<SwAudioOutputDescriptor> desc =
5036 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5037 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005038 // re open the spatializer output with previous channel mask
Eric Laurentd23aa162022-01-17 17:37:31 +01005039 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5040 if (desc == nullptr) {
5041 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005042 } else {
5043 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005044 }
5045 mPreviousOutputs = mOutputs;
5046 mpClientInterface->onAudioPortListUpdate();
5047 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd23aa162022-01-17 17:37:31 +01005048 ALOGW("%s could not open spatializer output with requested config", __func__);
5049 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005050 }
Eric Laurent39095982021-08-24 18:29:27 +02005051 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005052 mPreviousOutputs = mOutputs;
5053 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005054 }
5055
5056 checkVirtualizerClientRoutes();
5057
Eric Laurent39095982021-08-24 18:29:27 +02005058 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005059 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005060 return NO_ERROR;
5061}
5062
Eric Laurentfa0f6742021-08-17 18:39:44 +02005063status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5064 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005065 return INVALID_OPERATION;
5066 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005067 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005068 return BAD_VALUE;
5069 }
Eric Laurent39095982021-08-24 18:29:27 +02005070
Eric Laurentfa0f6742021-08-17 18:39:44 +02005071 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005072
5073 checkVirtualizerClientRoutes();
5074
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005075 return NO_ERROR;
5076}
5077
Eric Laurente552edb2014-03-10 17:42:56 -07005078// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005079// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005080// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005081uint32_t AudioPolicyManager::nextAudioPortGeneration()
5082{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005083 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005084}
5085
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005086static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005087 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5088 !audioPolicyXmlConfigFile.empty()) {
5089 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5090 if (ret == NO_ERROR) {
5091 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005092 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005093 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005094 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005095 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005096}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005097
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005098AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5099 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005100 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005101 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005102 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005103 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005104 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005105 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005106 mAudioPortGeneration(1),
5107 mBeaconMuteRefCount(0),
5108 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005109 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005110 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005111 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005112 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005113{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005114}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005115
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005116AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5117 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5118{
5119 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005120}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005121
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005122void AudioPolicyManager::loadConfig() {
5123 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005124 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005125 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005126 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005127 //TODO: b/193496180 use spatializer flag at audio HAL when available
5128 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005129}
5130
5131status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005132 {
5133 auto engLib = EngineLibrary::load(
5134 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5135 if (!engLib) {
5136 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5137 return NO_INIT;
5138 }
5139 mEngine = engLib->createEngine();
5140 if (mEngine == nullptr) {
5141 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5142 return NO_INIT;
5143 }
François Gaffie2110e042015-03-24 08:41:51 +01005144 }
5145 mEngine->setObserver(this);
5146 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005147 if (status != NO_ERROR) {
5148 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5149 return status;
5150 }
François Gaffie2110e042015-03-24 08:41:51 +01005151
Eric Laurent1d69c872021-01-11 18:53:01 +01005152 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5153 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5154
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005155 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005156 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005157 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005158
Eric Laurent3a4311c2014-03-17 12:00:47 -07005159 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005160 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5161 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5162 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005163 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005164 }
jiabin9ff780e2018-03-19 18:19:52 -07005165 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005166 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005167 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005168 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005169 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005170 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005171 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005172 }
5173 }
5174 }
Eric Laurente552edb2014-03-10 17:42:56 -07005175
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005176 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005177
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005178 // Silence ALOGV statements
5179 property_set("log.tag." LOG_TAG, "D");
5180
Eric Laurente552edb2014-03-10 17:42:56 -07005181 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005182 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005183}
5184
Eric Laurente0720872014-03-11 09:30:41 -07005185AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005186{
Eric Laurente552edb2014-03-10 17:42:56 -07005187 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005188 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005189 }
5190 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005191 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005192 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005193 mAvailableOutputDevices.clear();
5194 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005195 mOutputs.clear();
5196 mInputs.clear();
5197 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005198 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005199 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005200}
5201
Eric Laurente0720872014-03-11 09:30:41 -07005202status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005203{
Eric Laurent87ffa392015-05-22 10:32:38 -07005204 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005205}
5206
Eric Laurente552edb2014-03-10 17:42:56 -07005207// ---
5208
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005209void AudioPolicyManager::onNewAudioModulesAvailable()
5210{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005211 DeviceVector newDevices;
5212 onNewAudioModulesAvailableInt(&newDevices);
5213 if (!newDevices.empty()) {
5214 nextAudioPortGeneration();
5215 mpClientInterface->onAudioPortListUpdate();
5216 }
5217}
5218
5219void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5220{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005221 for (const auto& hwModule : mHwModulesAll) {
5222 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5223 continue;
5224 }
5225 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5226 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5227 ALOGW("could not open HW module %s", hwModule->getName());
5228 continue;
5229 }
5230 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005231 // open all output streams needed to access attached devices.
5232 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005233 // This also validates mAvailableOutputDevices list
5234 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5235 if (!outProfile->canOpenNewIo()) {
5236 ALOGE("Invalid Output profile max open count %u for profile %s",
5237 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5238 continue;
5239 }
5240 if (!outProfile->hasSupportedDevices()) {
5241 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5242 continue;
5243 }
5244 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5245 mTtsOutputAvailable = true;
5246 }
5247
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005248 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5249 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5250 sp<DeviceDescriptor> supportedDevice = 0;
5251 if (supportedDevices.contains(mDefaultOutputDevice)) {
5252 supportedDevice = mDefaultOutputDevice;
5253 } else {
5254 // choose first device present in profile's SupportedDevices also part of
5255 // mAvailableOutputDevices.
5256 if (availProfileDevices.isEmpty()) {
5257 continue;
5258 }
5259 supportedDevice = availProfileDevices.itemAt(0);
5260 }
5261 if (!mOutputDevicesAll.contains(supportedDevice)) {
5262 continue;
5263 }
5264 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5265 mpClientInterface);
5266 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005267 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5268 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005269 AUDIO_STREAM_DEFAULT,
5270 AUDIO_OUTPUT_FLAG_NONE, &output);
5271 if (status != NO_ERROR) {
5272 ALOGW("Cannot open output stream for devices %s on hw module %s",
5273 supportedDevice->toString().c_str(), hwModule->getName());
5274 continue;
5275 }
5276 for (const auto &device : availProfileDevices) {
5277 // give a valid ID to an attached device once confirmed it is reachable
5278 if (!device->isAttached()) {
5279 device->attach(hwModule);
5280 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005281 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005282 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005283 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5284 }
5285 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005286 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005287 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5288 mPrimaryOutput = outputDesc;
5289 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005290 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5291 outputDesc->close();
5292 } else {
5293 addOutput(output, outputDesc);
5294 setOutputDevices(outputDesc,
5295 DeviceVector(supportedDevice),
5296 true,
5297 0,
5298 NULL);
5299 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005300 }
5301 // open input streams needed to access attached devices to validate
5302 // mAvailableInputDevices list
5303 for (const auto& inProfile : hwModule->getInputProfiles()) {
5304 if (!inProfile->canOpenNewIo()) {
5305 ALOGE("Invalid Input profile max open count %u for profile %s",
5306 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5307 continue;
5308 }
5309 if (!inProfile->hasSupportedDevices()) {
5310 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5311 continue;
5312 }
5313 // chose first device present in profile's SupportedDevices also part of
5314 // available input devices
5315 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5316 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5317 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005318 ALOGV("%s: Input device list is empty! for profile %s",
5319 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005320 continue;
5321 }
5322 sp<AudioInputDescriptor> inputDesc =
5323 new AudioInputDescriptor(inProfile, mpClientInterface);
5324
5325 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5326 status_t status = inputDesc->open(nullptr,
5327 availProfileDevices.itemAt(0),
5328 AUDIO_SOURCE_MIC,
5329 AUDIO_INPUT_FLAG_NONE,
5330 &input);
5331 if (status != NO_ERROR) {
5332 ALOGW("Cannot open input stream for device %s on hw module %s",
5333 availProfileDevices.toString().c_str(),
5334 hwModule->getName());
5335 continue;
5336 }
5337 for (const auto &device : availProfileDevices) {
5338 // give a valid ID to an attached device once confirmed it is reachable
5339 if (!device->isAttached()) {
5340 device->attach(hwModule);
5341 device->importAudioPortAndPickAudioProfile(inProfile, true);
5342 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005343 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005344 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5345 }
5346 }
5347 inputDesc->close();
5348 }
5349 }
5350}
5351
Eric Laurent98e38192018-02-15 18:31:53 -08005352void AudioPolicyManager::addOutput(audio_io_handle_t output,
5353 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005354{
Eric Laurent1c333e22014-05-20 10:48:17 -07005355 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005356 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005357 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005358 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005359 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005360}
5361
François Gaffie53615e22015-03-19 09:24:12 +01005362void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5363{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005364 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5365 ALOGV("%s: removing primary output", __func__);
5366 mPrimaryOutput = nullptr;
5367 }
François Gaffie53615e22015-03-19 09:24:12 +01005368 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005369 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005370}
5371
Eric Laurent98e38192018-02-15 18:31:53 -08005372void AudioPolicyManager::addInput(audio_io_handle_t input,
5373 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005374{
Eric Laurent1c333e22014-05-20 10:48:17 -07005375 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005377}
Eric Laurente552edb2014-03-10 17:42:56 -07005378
François Gaffie11d30102018-11-02 16:09:09 +01005379status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005380 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005381 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005382{
François Gaffie11d30102018-11-02 16:09:09 +01005383 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005384 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005385 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005386
François Gaffie11d30102018-11-02 16:09:09 +01005387 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005388 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005389 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005390 }
Eric Laurente552edb2014-03-10 17:42:56 -07005391
Eric Laurent3b73df72014-03-11 09:06:29 -07005392 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005393 // first call getAudioPort to get the supported attributes from the HAL
5394 struct audio_port_v7 port = {};
5395 device->toAudioPort(&port);
5396 status_t status = mpClientInterface->getAudioPort(&port);
5397 if (status == NO_ERROR) {
5398 device->importAudioPort(port);
5399 }
5400
5401 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005402 for (size_t i = 0; i < mOutputs.size(); i++) {
5403 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005404 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005405 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005406 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5407 mOutputs.keyAt(i), device->toString().c_str());
5408 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005409 }
5410 }
5411 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005412 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005413 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005414 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5415 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005416 if (profile->supportsDevice(device)) {
5417 profiles.add(profile);
5418 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5419 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005420 }
5421 }
5422 }
5423
Eric Laurent7b279bb2015-12-14 10:18:23 -08005424 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005425
Eric Laurente552edb2014-03-10 17:42:56 -07005426 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005427 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005428 return BAD_VALUE;
5429 }
5430
5431 // open outputs for matching profiles if needed. Direct outputs are also opened to
5432 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5433 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005434 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005435
5436 // nothing to do if one output is already opened for this profile
5437 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005438 for (j = 0; j < outputs.size(); j++) {
5439 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005440 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005441 // matching profile: save the sample rates, format and channel masks supported
5442 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005443 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005444 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005445 }
Eric Laurente552edb2014-03-10 17:42:56 -07005446 break;
5447 }
5448 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005449 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005450 continue;
5451 }
5452
Eric Laurent3974e3b2017-12-07 17:58:43 -08005453 if (!profile->canOpenNewIo()) {
5454 ALOGW("Max Output number %u already opened for this profile %s",
5455 profile->maxOpenCount, profile->getTagName().c_str());
5456 continue;
5457 }
5458
Eric Laurent83efe1c2017-07-09 16:51:08 -07005459 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005460 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005461 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5462 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005463 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005464 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 profiles.removeAt(profile_index);
5466 profile_index--;
5467 } else {
5468 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005469 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005470 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005471 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5472 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005473 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005474 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005475
François Gaffie11d30102018-11-02 16:09:09 +01005476 if (device_distinguishes_on_address(deviceType)) {
5477 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5478 device->toString().c_str());
5479 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5480 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005481 }
Eric Laurente552edb2014-03-10 17:42:56 -07005482 ALOGV("checkOutputsForDevice(): adding output %d", output);
5483 }
5484 }
5485
5486 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005487 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005488 return BAD_VALUE;
5489 }
Eric Laurentd4692962014-05-05 18:13:44 -07005490 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005491 // check if one opened output is not needed any more after disconnecting one device
5492 for (size_t i = 0; i < mOutputs.size(); i++) {
5493 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005494 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005495 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005496 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005497 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005498 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005499 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005500 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5501 mOutputs.keyAt(i));
5502 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005503 }
Eric Laurente552edb2014-03-10 17:42:56 -07005504 }
5505 }
Eric Laurentd4692962014-05-05 18:13:44 -07005506 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005507 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005508 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5509 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005510 if (!profile->supportsDevice(device)) {
5511 continue;
5512 }
5513 ALOGV("checkOutputsForDevice(): "
5514 "clearing direct output profile %zu on module %s",
5515 j, hwModule->getName());
5516 profile->clearAudioProfiles();
5517 if (!profile->hasDynamicAudioProfile()) {
5518 continue;
5519 }
5520 // When a device is disconnected, if there is an IOProfile that contains dynamic
5521 // profiles and supports the disconnected device, call getAudioPort to repopulate
5522 // the capabilities of the devices that is supported by the IOProfile.
5523 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5524 if (supportedDevice == device ||
5525 !mAvailableOutputDevices.contains(supportedDevice)) {
5526 continue;
5527 }
5528 struct audio_port_v7 port;
5529 supportedDevice->toAudioPort(&port);
5530 status_t status = mpClientInterface->getAudioPort(&port);
5531 if (status == NO_ERROR) {
5532 supportedDevice->importAudioPort(port);
5533 }
Eric Laurente552edb2014-03-10 17:42:56 -07005534 }
5535 }
5536 }
5537 }
5538 return NO_ERROR;
5539}
5540
François Gaffie11d30102018-11-02 16:09:09 +01005541status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005542 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005543{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005544 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005545
François Gaffie11d30102018-11-02 16:09:09 +01005546 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005547 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005548 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005549 }
5550
Eric Laurentd4692962014-05-05 18:13:44 -07005551 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005552 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005553 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005554 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005555 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005556 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005557 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005558 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005559
François Gaffie11d30102018-11-02 16:09:09 +01005560 if (profile->supportsDevice(device)) {
5561 profiles.add(profile);
5562 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5563 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005564 }
5565 }
5566 }
5567
Eric Laurent0dd51852019-04-19 18:18:58 -07005568 if (profiles.isEmpty()) {
5569 ALOGW("%s: No input profile available for device %s",
5570 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005571 return BAD_VALUE;
5572 }
5573
5574 // open inputs for matching profiles if needed. Direct inputs are also opened to
5575 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5576 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5577
Eric Laurent1c333e22014-05-20 10:48:17 -07005578 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005579
Eric Laurentd4692962014-05-05 18:13:44 -07005580 // nothing to do if one input is already opened for this profile
5581 size_t input_index;
5582 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5583 desc = mInputs.valueAt(input_index);
5584 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005585 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005586 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005587 }
Eric Laurentd4692962014-05-05 18:13:44 -07005588 break;
5589 }
5590 }
5591 if (input_index != mInputs.size()) {
5592 continue;
5593 }
5594
Eric Laurent3974e3b2017-12-07 17:58:43 -08005595 if (!profile->canOpenNewIo()) {
5596 ALOGW("Max Input number %u already opened for this profile %s",
5597 profile->maxOpenCount, profile->getTagName().c_str());
5598 continue;
5599 }
5600
Eric Laurentfe231122017-11-17 17:48:06 -08005601 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005602 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005603 status_t status = desc->open(nullptr,
5604 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005605 AUDIO_SOURCE_MIC,
5606 AUDIO_INPUT_FLAG_NONE,
5607 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005608
Eric Laurentcf2c0212014-07-25 16:20:43 -07005609 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005610 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005611 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005612 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005613 mpClientInterface->setParameters(input, String8(param));
5614 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005615 }
François Gaffie11d30102018-11-02 16:09:09 +01005616 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005617 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005618 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005619 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005620 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005621 }
5622
Eric Laurent0dd51852019-04-19 18:18:58 -07005623 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005624 addInput(input, desc);
5625 }
5626 } // endif input != 0
5627
Eric Laurentcf2c0212014-07-25 16:20:43 -07005628 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005629 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005630 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005631 profiles.removeAt(profile_index);
5632 profile_index--;
5633 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005634 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005635 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005636 }
Eric Laurentd4692962014-05-05 18:13:44 -07005637 ALOGV("checkInputsForDevice(): adding input %d", input);
5638 }
5639 } // end scan profiles
5640
5641 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005642 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005643 return BAD_VALUE;
5644 }
5645 } else {
5646 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005647 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005648 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005649 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005650 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005651 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005652 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005653 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005654 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5655 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005656 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005657 }
5658 }
5659 }
5660 } // end disconnect
5661
5662 return NO_ERROR;
5663}
5664
5665
Eric Laurente0720872014-03-11 09:30:41 -07005666void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005667{
5668 ALOGV("closeOutput(%d)", output);
5669
François Gaffie1c878552018-11-22 16:53:21 +01005670 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5671 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005672 ALOGW("closeOutput() unknown output %d", output);
5673 return;
5674 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005675 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005676 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005677
Eric Laurente552edb2014-03-10 17:42:56 -07005678 // look for duplicated outputs connected to the output being removed.
5679 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005680 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5681 if (dupOutput->isDuplicated() &&
5682 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5683 sp<SwAudioOutputDescriptor> remainingOutput =
5684 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005685 // As all active tracks on duplicated output will be deleted,
5686 // and as they were also referenced on the other output, the reference
5687 // count for their stream type must be adjusted accordingly on
5688 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005689 const bool wasActive = remainingOutput->isActive();
5690 // Note: no-op on the closing output where all clients has already been set inactive
5691 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005692 // stop() will be a no op if the output is still active but is needed in case all
5693 // active streams refcounts where cleared above
5694 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005695 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005696 }
Eric Laurente552edb2014-03-10 17:42:56 -07005697 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5698 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5699
5700 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005701 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005702 }
5703 }
5704
Eric Laurent05b90f82014-08-27 15:32:29 -07005705 nextAudioPortGeneration();
5706
François Gaffie1c878552018-11-22 16:53:21 +01005707 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005708 if (index >= 0) {
5709 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005710 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5711 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005712 mAudioPatches.removeItemsAt(index);
5713 mpClientInterface->onAudioPatchListUpdate();
5714 }
5715
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005716 if (closingOutputWasActive) {
5717 closingOutput->stop();
5718 }
François Gaffie1c878552018-11-22 16:53:21 +01005719 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005720
François Gaffie53615e22015-03-19 09:24:12 +01005721 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005722 mPreviousOutputs = mOutputs;
Eric Laurentd23aa162022-01-17 17:37:31 +01005723 if (closingOutput == mSpatializerOutput) {
5724 mSpatializerOutput.clear();
5725 }
Dean Wheatley3023b382018-08-09 07:42:40 +10005726
5727 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5728 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005729 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005730 bool directOutputOpen = false;
5731 for (size_t i = 0; i < mOutputs.size(); i++) {
5732 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5733 directOutputOpen = true;
5734 break;
5735 }
5736 }
5737 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005738 ALOGV("no direct outputs open, reset MSD patches");
5739 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5740 // how output devices for patching are resolved. Avoid by caching and reusing the
5741 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5742 // devices to patch to. This may be complicated by the fact that devices may become
5743 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005744 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005745 }
5746 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005747}
5748
5749void AudioPolicyManager::closeInput(audio_io_handle_t input)
5750{
5751 ALOGV("closeInput(%d)", input);
5752
5753 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5754 if (inputDesc == NULL) {
5755 ALOGW("closeInput() unknown input %d", input);
5756 return;
5757 }
5758
Eric Laurent6a94d692014-05-20 11:18:06 -07005759 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005760
François Gaffie11d30102018-11-02 16:09:09 +01005761 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005762 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005763 if (index >= 0) {
5764 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005765 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5766 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005767 mAudioPatches.removeItemsAt(index);
5768 mpClientInterface->onAudioPatchListUpdate();
5769 }
5770
Eric Laurentfe231122017-11-17 17:48:06 -08005771 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005772 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005773
François Gaffie11d30102018-11-02 16:09:09 +01005774 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5775 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005776 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005777 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005778 }
Eric Laurente552edb2014-03-10 17:42:56 -07005779}
5780
François Gaffie11d30102018-11-02 16:09:09 +01005781SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5782 const DeviceVector &devices,
5783 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005784{
5785 SortedVector<audio_io_handle_t> outputs;
5786
François Gaffie11d30102018-11-02 16:09:09 +01005787 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005788 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005789 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005790 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005791 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005792 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005793 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005794 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005795 outputs.add(openOutputs.keyAt(i));
5796 }
5797 }
5798 return outputs;
5799}
5800
Mikhail Naganov37977152018-07-11 15:54:44 -07005801void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5802{
5803 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5804 // output is suspended before any tracks are moved to it
5805 checkA2dpSuspend();
5806 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005807 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005808 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005809 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005810 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005811 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5812 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5813 // configuration changes will ultimately be rerouted correctly. We can still avoid
5814 // unnecessary rerouting by caching and reusing the arguments to
5815 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5816 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005817 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005818 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005819 // an event that changed routing likely occurred, inform upper layers
5820 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005821}
5822
François Gaffiec005e562018-11-06 15:04:49 +01005823bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5824 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005825{
François Gaffiec005e562018-11-06 15:04:49 +01005826 return mEngine->getProductStrategyForAttributes(lAttr) ==
5827 mEngine->getProductStrategyForAttributes(rAttr);
5828}
5829
Francois Gaffieff1eb522020-05-06 18:37:04 +02005830void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5831{
5832 for (size_t i = 0; i < mAudioSources.size(); i++) {
5833 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5834 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005835 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5836 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005837 connectAudioSource(sourceDesc);
5838 }
5839 }
5840}
5841
5842void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5843{
5844 for (size_t i = 0; i < mAudioSources.size(); i++) {
5845 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5846 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5847 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5848 disconnectAudioSource(sourceDesc);
5849 }
5850 }
5851}
5852
François Gaffiec005e562018-11-06 15:04:49 +01005853void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5854{
5855 auto psId = mEngine->getProductStrategyForAttributes(attr);
5856
5857 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5858 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005859
François Gaffie11d30102018-11-02 16:09:09 +01005860 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5861 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005862
Eric Laurentc209fe42020-06-05 18:11:23 -07005863 uint32_t maxLatency = 0;
5864 bool invalidate = false;
5865 // take into account dynamic audio policies related changes: if a client is now associated
5866 // to a different policy mix than at creation time, invalidate corresponding stream
5867 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5868 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5869 if (desc->isDuplicated()) {
5870 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005871 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005872 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5873 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5874 continue;
5875 }
5876 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005877 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5878 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07005879 if (status != OK) {
5880 continue;
5881 }
yucliuf4de36d2020-09-14 14:57:56 -07005882 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005883 invalidate = true;
5884 if (desc->isStrategyActive(psId)) {
5885 maxLatency = desc->latency();
5886 }
5887 break;
5888 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005889 }
5890 }
5891
Eric Laurentc209fe42020-06-05 18:11:23 -07005892 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005893 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5894 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005895 for (audio_io_handle_t srcOut : srcOutputs) {
5896 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005897 if (desc == nullptr) continue;
5898
5899 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005900 maxLatency = desc->latency();
5901 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005902
5903 if (invalidate) continue;
5904
5905 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005906 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005907 // a client on a non direct outputs has necessarily a linear PCM format
5908 // so we can call selectOutput() safely
5909 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5910 client->flags(),
5911 client->config().format,
5912 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005913 client->config().sample_rate,
5914 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005915 if (newOutput != srcOut) {
5916 invalidate = true;
5917 break;
5918 }
5919 } else {
5920 sp<IOProfile> profile = getProfileForOutput(newDevices,
5921 client->config().sample_rate,
5922 client->config().format,
5923 client->config().channel_mask,
5924 client->flags(),
5925 true /* directOnly */);
5926 if (profile != desc->mProfile) {
5927 invalidate = true;
5928 break;
5929 }
5930 }
5931 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005932 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005933
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005934 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005935 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005936 std::to_string(srcOutputs[0]).c_str(),
5937 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005938 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005939 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005940 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005941 if (desc == nullptr) continue;
5942
5943 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005944 setStrategyMute(psId, true, desc);
5945 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005946 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005947 }
François Gaffiec005e562018-11-06 15:04:49 +01005948 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005949 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005950 connectAudioSource(source);
5951 }
Eric Laurente552edb2014-03-10 17:42:56 -07005952 }
5953
François Gaffiec005e562018-11-06 15:04:49 +01005954 // Move effects associated to this stream from previous output to new output
5955 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005956 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005957 }
François Gaffiec005e562018-11-06 15:04:49 +01005958 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005959 if (invalidate) {
5960 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5961 mpClientInterface->invalidateStream(stream);
5962 }
Eric Laurente552edb2014-03-10 17:42:56 -07005963 }
5964 }
5965}
5966
Eric Laurente0720872014-03-11 09:30:41 -07005967void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005968{
François Gaffiec005e562018-11-06 15:04:49 +01005969 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5970 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5971 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005972 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005973 }
Eric Laurente552edb2014-03-10 17:42:56 -07005974}
5975
Kevin Rocard153f92d2018-12-18 18:33:28 -08005976void AudioPolicyManager::checkSecondaryOutputs() {
5977 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005978 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005979 for (size_t i = 0; i < mOutputs.size(); i++) {
5980 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5981 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005982 sp<AudioPolicyMix> primaryMix;
5983 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005984 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5985 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07005986 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5987 for (auto &secondaryMix : secondaryMixes) {
5988 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5989 if (outputDesc != nullptr &&
5990 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5991 secondaryDescs.push_back(outputDesc);
5992 }
5993 }
5994
jiabinf042b9b2021-05-07 23:46:28 +00005995 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005996 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005997 } else if (!std::equal(
5998 client->getSecondaryOutputs().begin(),
5999 client->getSecondaryOutputs().end(),
6000 secondaryDescs.begin(), secondaryDescs.end())) {
jiabin64794372021-11-23 00:10:23 +00006001 if (!audio_is_linear_pcm(client->config().format)) {
6002 // If the format is not PCM, the tracks should be invalidated to get correct
6003 // behavior when the secondary output is changed.
6004 streamsToInvalidate.insert(client->stream());
6005 } else {
6006 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6007 std::vector<audio_io_handle_t> secondaryOutputIds;
6008 for (const auto &secondaryDesc: secondaryDescs) {
6009 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6010 weakSecondaryDescs.push_back(secondaryDesc);
6011 }
6012 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6013 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabinf042b9b2021-05-07 23:46:28 +00006014 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006015 }
6016 }
6017 }
jiabinf042b9b2021-05-07 23:46:28 +00006018 if (!trackSecondaryOutputs.empty()) {
6019 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6020 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006021 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00006022 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006023 mpClientInterface->invalidateStream(stream);
6024 }
6025}
6026
Eric Laurent2517af32020-11-25 15:31:27 +01006027bool AudioPolicyManager::isScoRequestedForComm() const {
6028 AudioDeviceTypeAddrVector devices;
6029 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6030 for (const auto &device : devices) {
6031 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6032 return true;
6033 }
6034 }
6035 return false;
6036}
6037
Eric Laurente0720872014-03-11 09:30:41 -07006038void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006039{
François Gaffie53615e22015-03-19 09:24:12 +01006040 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006041 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006042 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006043 return;
6044 }
6045
Eric Laurent3a4311c2014-03-17 12:00:47 -07006046 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006047 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6048 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006049 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006050
6051 // if suspended, restore A2DP output if:
6052 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006053 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006054 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006055 //
Eric Laurentf732e072016-08-03 19:30:28 -07006056 // if not suspended, suspend A2DP output if:
6057 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006058 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006059 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006060 //
6061 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006062 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006063 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006064 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006065 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006066
6067 mpClientInterface->restoreOutput(a2dpOutput);
6068 mA2dpSuspended = false;
6069 }
6070 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006071 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006072 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006073 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006074 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006075
6076 mpClientInterface->suspendOutput(a2dpOutput);
6077 mA2dpSuspended = true;
6078 }
6079 }
6080}
6081
François Gaffie11d30102018-11-02 16:09:09 +01006082DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6083 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006084{
François Gaffie11d30102018-11-02 16:09:09 +01006085 DeviceVector devices;
6086
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006087 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006088 if (index >= 0) {
6089 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006090 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006091 ALOGV("%s device %s forced by patch %d", __func__,
6092 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6093 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006094 }
6095 }
6096
Dean Wheatley514b4312020-06-17 21:45:00 +10006097 // Do not retrieve engine device for outputs through MSD
6098 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6099 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6100 return outputDesc->devices();
6101 }
6102
Eric Laurent97ac8712018-07-27 18:59:02 -07006103 // Honor explicit routing requests only if no client using default routing is active on this
6104 // input: a specific app can not force routing for other apps by setting a preferred device.
6105 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006106 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006107 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006108 if (device != nullptr) {
6109 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006110 }
6111
François Gaffiea807ef92018-11-05 10:44:33 +01006112 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6113 // of setForceUse / Default Bus device here
6114 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6115 if (device != nullptr) {
6116 return DeviceVector(device);
6117 }
6118
François Gaffiec005e562018-11-06 15:04:49 +01006119 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6120 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6121 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306122 auto hasStreamActive = [&](auto stream) {
6123 return hasStream(streams, stream) && isStreamActive(stream, 0);
6124 };
Eric Laurent484e9272018-06-07 17:29:23 -07006125
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306126 auto doGetOutputDevicesForVoice = [&]() {
6127 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006128 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306129 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006130 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6131 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306132 };
6133
6134 // With low-latency playing on speaker, music on WFD, when the first low-latency
6135 // output is stopped, getNewOutputDevices checks for a product strategy
6136 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006137 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306138 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6139 // stream is associated to the output descriptor.
6140 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6141 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6142 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6143 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006144 // Retrieval of devices for voice DL is done on primary output profile, cannot
6145 // check the route (would force modifying configuration file for this profile)
6146 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6147 break;
6148 }
Eric Laurente552edb2014-03-10 17:42:56 -07006149 }
François Gaffiec005e562018-11-06 15:04:49 +01006150 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006151 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006152}
6153
François Gaffie11d30102018-11-02 16:09:09 +01006154sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6155 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006156{
François Gaffie11d30102018-11-02 16:09:09 +01006157 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006158
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006159 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006160 if (index >= 0) {
6161 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006162 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006163 ALOGV("getNewInputDevice() device %s forced by patch %d",
6164 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6165 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006166 }
6167 }
6168
Eric Laurent97ac8712018-07-27 18:59:02 -07006169 // Honor explicit routing requests only if no client using default routing is active on this
6170 // input: a specific app can not force routing for other apps by setting a preferred device.
6171 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006172 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6173 if (device != nullptr) {
6174 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006175 }
6176
Eric Laurentdc95a252018-04-12 12:46:56 -07006177 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006178 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006179 audio_attributes_t attributes;
6180 uid_t uid;
6181 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6182 if (topClient != nullptr) {
6183 attributes = topClient->attributes();
6184 uid = topClient->uid();
6185 } else {
6186 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6187 uid = 0;
6188 }
6189
Francois Gaffie716e1432019-01-14 16:58:59 +01006190 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6191 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006192 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006193 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006194 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006195 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006196
Eric Laurente552edb2014-03-10 17:42:56 -07006197 return device;
6198}
6199
Eric Laurent794fde22016-03-11 09:50:45 -08006200bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6201 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006202 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006203}
6204
Eric Laurente0720872014-03-11 09:30:41 -07006205audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006206 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006207 // getOutputDevicesForStream's behavior for invalid streams.
6208 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6209 // device for music stream), but we want to return the empty set.
6210 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07006211 return AUDIO_DEVICE_NONE;
6212 }
François Gaffie11d30102018-11-02 16:09:09 +01006213 DeviceVector activeDevices;
6214 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006215 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6216 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006217 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006218 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006219 }
François Gaffiec005e562018-11-06 15:04:49 +01006220 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006221 devices.merge(curDevices);
6222 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006223 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006224 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01006225 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006226 }
6227 }
Eric Laurente552edb2014-03-10 17:42:56 -07006228 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006229
Eric Laurentb0688d62018-08-14 15:49:18 -07006230 // Favor devices selected on active streams if any to report correct device in case of
6231 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006232 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006233 devices = activeDevices;
6234 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006235 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6236 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006237 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006238 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006239 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006240 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006241 }
jiabin9a3361e2019-10-01 09:38:30 -07006242 // FIXME: use DeviceTypeSet when Java layer is ready for it.
6243 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006244}
6245
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006246status_t AudioPolicyManager::getDevicesForAttributes(
6247 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6248 if (devices == nullptr) {
6249 return BAD_VALUE;
6250 }
6251 // check dynamic policies but only for primary descriptors (secondary not used for audible
6252 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006253 sp<AudioPolicyMix> policyMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11006254 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6255 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006256 if (status != OK) {
6257 return status;
6258 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006259 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6260 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6261 devices->push_back(device);
6262 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006263 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006264 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6265 for (const auto& device : curDevices) {
6266 devices->push_back(device->getDeviceTypeAddr());
6267 }
6268 return NO_ERROR;
6269}
6270
Eric Laurente0720872014-03-11 09:30:41 -07006271void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006272 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006273 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006274 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006275 updateDevicesAndOutputs();
6276 break;
6277 default:
6278 break;
6279 }
6280}
6281
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006282uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006283
6284 // skip beacon mute management if a dedicated TTS output is available
6285 if (mTtsOutputAvailable) {
6286 return 0;
6287 }
6288
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006289 switch(event) {
6290 case STARTING_OUTPUT:
6291 mBeaconMuteRefCount++;
6292 break;
6293 case STOPPING_OUTPUT:
6294 if (mBeaconMuteRefCount > 0) {
6295 mBeaconMuteRefCount--;
6296 }
6297 break;
6298 case STARTING_BEACON:
6299 mBeaconPlayingRefCount++;
6300 break;
6301 case STOPPING_BEACON:
6302 if (mBeaconPlayingRefCount > 0) {
6303 mBeaconPlayingRefCount--;
6304 }
6305 break;
6306 }
6307
6308 if (mBeaconMuteRefCount > 0) {
6309 // any playback causes beacon to be muted
6310 return setBeaconMute(true);
6311 } else {
6312 // no other playback: unmute when beacon starts playing, mute when it stops
6313 return setBeaconMute(mBeaconPlayingRefCount == 0);
6314 }
6315}
6316
6317uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6318 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6319 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6320 // keep track of muted state to avoid repeating mute/unmute operations
6321 if (mBeaconMuted != mute) {
6322 // mute/unmute AUDIO_STREAM_TTS on all outputs
6323 ALOGV("\t muting %d", mute);
6324 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006325 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6326 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6327 ALOGV("\t no tts volume source available");
6328 return 0;
6329 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006330 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006331 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006332 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006333 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006334 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006335 maxLatency = latency;
6336 }
6337 }
6338 mBeaconMuted = mute;
6339 return maxLatency;
6340 }
6341 return 0;
6342}
6343
Eric Laurente0720872014-03-11 09:30:41 -07006344void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006345{
François Gaffiec005e562018-11-06 15:04:49 +01006346 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006347 mPreviousOutputs = mOutputs;
6348}
6349
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006350uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006351 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006352 uint32_t delayMs)
6353{
6354 // mute/unmute strategies using an incompatible device combination
6355 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6356 // if unmuting, unmute only after the specified delay
6357 if (outputDesc->isDuplicated()) {
6358 return 0;
6359 }
6360
6361 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006362 DeviceVector devices = outputDesc->devices();
6363 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006364
François Gaffiec005e562018-11-06 15:04:49 +01006365 auto productStrategies = mEngine->getOrderedProductStrategies();
6366 for (const auto &productStrategy : productStrategies) {
6367 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6368 DeviceVector curDevices =
6369 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6370 curDevices = curDevices.filter(outputDesc->supportedDevices());
6371 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006372 bool doMute = false;
6373
François Gaffiec005e562018-11-06 15:04:49 +01006374 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006375 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006376 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6377 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006378 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006379 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006380 }
Eric Laurent99401132014-05-07 19:48:15 -07006381 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006382 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006383 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006384 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006385 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006386 continue;
6387 }
François Gaffiec005e562018-11-06 15:04:49 +01006388 ALOGVV("%s() %s (curDevice %s)", __func__,
6389 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6390 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6391 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006392 if (mute) {
6393 // FIXME: should not need to double latency if volume could be applied
6394 // immediately by the audioflinger mixer. We must account for the delay
6395 // between now and the next time the audioflinger thread for this output
6396 // will process a buffer (which corresponds to one buffer size,
6397 // usually 1/2 or 1/4 of the latency).
6398 if (muteWaitMs < desc->latency() * 2) {
6399 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006400 }
6401 }
6402 }
6403 }
6404 }
6405 }
6406
Eric Laurent99401132014-05-07 19:48:15 -07006407 // temporary mute output if device selection changes to avoid volume bursts due to
6408 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006409 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006410 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6411 // temporary mute duration is conservatively set to 4 times the reported latency
6412 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6413 if (muteWaitMs < tempMuteWaitMs) {
6414 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006415 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006416 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6417 // make sure that we do not start the temporary mute period too early in case of
6418 // delayed device change
6419 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6420 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006421 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006422 }
6423 }
6424
Eric Laurente552edb2014-03-10 17:42:56 -07006425 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6426 if (muteWaitMs > delayMs) {
6427 muteWaitMs -= delayMs;
6428 usleep(muteWaitMs * 1000);
6429 return muteWaitMs;
6430 }
6431 return 0;
6432}
6433
François Gaffie11d30102018-11-02 16:09:09 +01006434uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6435 const DeviceVector &devices,
6436 bool force,
6437 int delayMs,
6438 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006439 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006440{
François Gaffie11d30102018-11-02 16:09:09 +01006441 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006442 uint32_t muteWaitMs;
6443
6444 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006445 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6446 nullptr /* patchHandle */, requiresMuteCheck);
6447 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6448 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006449 return muteWaitMs;
6450 }
Eric Laurente552edb2014-03-10 17:42:56 -07006451
6452 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006453 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006454 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006455 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006456
François Gaffie11d30102018-11-02 16:09:09 +01006457 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6458
6459 if (!filteredDevices.isEmpty()) {
6460 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006461 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006462
6463 // if the outputs are not materially active, there is no need to mute.
6464 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006465 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006466 } else {
6467 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6468 muteWaitMs = 0;
6469 }
Eric Laurente552edb2014-03-10 17:42:56 -07006470
Eric Laurent79ea9582020-06-11 18:49:24 -07006471 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6472 // output profile or if new device is not supported AND previous device(s) is(are) still
6473 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006474 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006475 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6476 // restore previous device after evaluating strategy mute state
6477 outputDesc->setDevices(prevDevices);
6478 return muteWaitMs;
6479 }
6480
Eric Laurente552edb2014-03-10 17:42:56 -07006481 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006482 // the requested device is AUDIO_DEVICE_NONE
6483 // OR the requested device is the same as current device
6484 // AND force is not specified
6485 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006486 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006487 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
Francois Gaffie3523ab32021-06-22 13:24:34 +02006488 !force && outputDesc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006489 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6490 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006491 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6492 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6493 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6494 }
Eric Laurente552edb2014-03-10 17:42:56 -07006495 return muteWaitMs;
6496 }
6497
François Gaffie11d30102018-11-02 16:09:09 +01006498 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006499
Eric Laurente552edb2014-03-10 17:42:56 -07006500 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006501 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006502 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006503 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006504 PatchBuilder patchBuilder;
6505 patchBuilder.addSource(outputDesc);
6506 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6507 for (const auto &filteredDevice : filteredDevices) {
6508 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006509 }
6510
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006511 // Add half reported latency to delayMs when muteWaitMs is null in order
6512 // to avoid disordered sequence of muting volume and changing devices.
6513 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6514 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006515 }
Eric Laurente552edb2014-03-10 17:42:56 -07006516
6517 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006518 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006519
6520 return muteWaitMs;
6521}
6522
Eric Laurentc75307b2015-03-17 15:29:32 -07006523status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006524 int delayMs,
6525 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006526{
Eric Laurent6a94d692014-05-20 11:18:06 -07006527 ssize_t index;
6528 if (patchHandle) {
6529 index = mAudioPatches.indexOfKey(*patchHandle);
6530 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006531 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006532 }
6533 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006534 return INVALID_OPERATION;
6535 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006536 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006537 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006538 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006539 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006540 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006541 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006542 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006543 return status;
6544}
6545
6546status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006547 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006548 bool force,
6549 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006550{
6551 status_t status = NO_ERROR;
6552
Eric Laurent1f2f2232014-06-02 12:01:23 -07006553 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006554 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6555 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006556
François Gaffie11d30102018-11-02 16:09:09 +01006557 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006558 PatchBuilder patchBuilder;
6559 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006560 // AUDIO_SOURCE_HOTWORD is for internal use only:
6561 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006562 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6563 auto result = usecase;
6564 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6565 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6566 }
6567 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006568 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006569 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006570 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006571 }
6572 }
6573 return status;
6574}
6575
Eric Laurent6a94d692014-05-20 11:18:06 -07006576status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6577 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006578{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006579 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006580 ssize_t index;
6581 if (patchHandle) {
6582 index = mAudioPatches.indexOfKey(*patchHandle);
6583 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006584 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006585 }
6586 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006587 return INVALID_OPERATION;
6588 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006589 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006590 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006591 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006592 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006593 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006594 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006595 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006596 return status;
6597}
6598
François Gaffie11d30102018-11-02 16:09:09 +01006599sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006600 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006601 audio_format_t& format,
6602 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006603 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006604{
6605 // Choose an input profile based on the requested capture parameters: select the first available
6606 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006607 //
6608 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6609 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006610
Glenn Kasten730b9262018-03-29 15:01:26 -07006611 sp<IOProfile> firstInexact;
6612 uint32_t updatedSamplingRate = 0;
6613 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6614 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006615 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006616 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006617 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006618 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006619 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006620 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006621 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006622 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006623 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006624 &channelMask /*updatedChannelMask*/,
6625 // FIXME ugly cast
6626 (audio_output_flags_t) flags,
6627 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006628 return profile;
6629 }
François Gaffie11d30102018-11-02 16:09:09 +01006630 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006631 samplingRate,
6632 &updatedSamplingRate,
6633 format,
6634 &updatedFormat,
6635 channelMask,
6636 &updatedChannelMask,
6637 // FIXME ugly cast
6638 (audio_output_flags_t) flags,
6639 false /*exactMatchRequiredForInputFlags*/)) {
6640 firstInexact = profile;
6641 }
6642
Eric Laurente552edb2014-03-10 17:42:56 -07006643 }
6644 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006645 if (firstInexact != nullptr) {
6646 samplingRate = updatedSamplingRate;
6647 format = updatedFormat;
6648 channelMask = updatedChannelMask;
6649 return firstInexact;
6650 }
Eric Laurente552edb2014-03-10 17:42:56 -07006651 return NULL;
6652}
6653
François Gaffieaaac0fd2018-11-22 17:56:39 +01006654float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6655 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006656 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006657 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006658{
jiabin9a3361e2019-10-01 09:38:30 -07006659 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006660
6661 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6662 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6663 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6664 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006665 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6666 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
6667 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
6668 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
6669 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006670
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006671 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006672 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6673 mOutputs.isActive(ringVolumeSrc, 0)) {
6674 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006675 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006676 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006677 }
6678
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006679 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006680 if ((volumeSource != callVolumeSrc && (isInCall() ||
6681 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006682 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006683 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6684 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006685 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
6686 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
6687 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006688 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006689 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006690 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006691 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006692 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006693 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006694 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6695 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6696 // programmatically muted.
6697 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6698 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6699 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006700 bool exemptFromCapping =
6701 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6702 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006703 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6704 volumeSource, volumeDb);
6705 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006706 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6707 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6708 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006709 }
6710 }
Eric Laurente552edb2014-03-10 17:42:56 -07006711 // if a headset is connected, apply the following rules to ring tones and notifications
6712 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006713 // - always attenuate notifications volume by 6dB
6714 // - attenuate ring tones volume by 6dB unless music is not playing and
6715 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006716 // - if music is playing, always limit the volume to current music volume,
6717 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006718 if (!Intersection(deviceTypes,
6719 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6720 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006721 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6722 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006723 ((volumeSource == alarmVolumeSrc ||
6724 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006725 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
6726 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
6727 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006728 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6729 curves.canBeMuted()) {
6730
Eric Laurente552edb2014-03-10 17:42:56 -07006731 // when the phone is ringing we must consider that music could have been paused just before
6732 // by the music application and behave as if music was active if the last music track was
6733 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006734 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006735 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006736 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006737 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006738 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6739 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006740 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006741 float musicVolDb = computeVolume(musicCurves,
6742 musicVolumeSrc,
6743 musicCurves.getVolumeIndex(musicDevice),
6744 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006745 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6746 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6747 if (volumeDb > minVolDb) {
6748 volumeDb = minVolDb;
6749 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006750 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006751 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6752 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6753 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006754 // on A2DP, also ensure notification volume is not too low compared to media when
6755 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006756 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006757 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006758 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6759 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006760 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6761 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006762 }
6763 }
jiabin9a3361e2019-10-01 09:38:30 -07006764 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006765 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006766 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006767 }
6768 }
6769
François Gaffie43c73442018-11-08 08:21:55 +01006770 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006771}
6772
Eric Laurent3839bc02018-07-10 18:33:34 -07006773int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006774 VolumeSource fromVolumeSource,
6775 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006776{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006777 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006778 return srcIndex;
6779 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006780 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6781 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006782 float minSrc = (float)srcCurves.getVolumeIndexMin();
6783 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6784 float minDst = (float)dstCurves.getVolumeIndexMin();
6785 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006786
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006787 // preserve mute request or correct range
6788 if (srcIndex < minSrc) {
6789 if (srcIndex == 0) {
6790 return 0;
6791 }
6792 srcIndex = minSrc;
6793 } else if (srcIndex > maxSrc) {
6794 srcIndex = maxSrc;
6795 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006796 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6797}
6798
François Gaffieaaac0fd2018-11-22 17:56:39 +01006799status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6800 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006801 int index,
6802 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006803 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006804 int delayMs,
6805 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006806{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006807 // do not change actual attributes volume if the attributes is muted
6808 if (outputDesc->isMuted(volumeSource)) {
6809 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6810 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006811 return NO_ERROR;
6812 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006813 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6814 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
6815 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
6816 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006817
Eric Laurent2517af32020-11-25 15:31:27 +01006818 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006819 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006820 // if sco and call follow same curves, bypass forceUseForComm
6821 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006822 ((isVoiceVolSrc && isScoRequested) ||
6823 (isBtScoVolSrc && !isScoRequested))) {
6824 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6825 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006826 // Do not return an error here as AudioService will always set both voice call
6827 // and bluetooth SCO volumes due to stream aliasing.
6828 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006829 }
jiabin9a3361e2019-10-01 09:38:30 -07006830 if (deviceTypes.empty()) {
6831 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006832 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006833
jiabin9a3361e2019-10-01 09:38:30 -07006834 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6835 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006836 // Force VoIP volume to max for bluetooth SCO device except if muted
6837 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006838 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006839 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006840 }
Francois Gaffie593634d2021-06-22 13:31:31 +02006841 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07006842 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02006843 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006844
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006845 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006846 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006847 // 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 +01006848 if (isVoiceVolSrc) {
6849 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006850 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006851 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006852 }
Eric Laurent18fba842016-03-31 14:41:26 -07006853 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006854 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6855 mLastVoiceVolume = voiceVolume;
6856 }
6857 }
Eric Laurente552edb2014-03-10 17:42:56 -07006858 return NO_ERROR;
6859}
6860
Eric Laurentc75307b2015-03-17 15:29:32 -07006861void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006862 const DeviceTypeSet& deviceTypes,
6863 int delayMs,
6864 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006865{
jiabincd510522020-01-22 09:40:55 -08006866 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006867 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6868 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6869 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006870 curves.getVolumeIndex(deviceTypes),
6871 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006872 }
6873}
6874
François Gaffiec005e562018-11-06 15:04:49 +01006875void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6876 bool on,
6877 const sp<AudioOutputDescriptor>& outputDesc,
6878 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006879 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006880{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006881 std::vector<VolumeSource> sourcesToMute;
6882 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6883 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6884 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006885 VolumeSource source = toVolumeSource(attributes, false);
6886 if ((source != VOLUME_SOURCE_NONE) &&
6887 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
6888 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006889 sourcesToMute.push_back(source);
6890 }
Eric Laurente552edb2014-03-10 17:42:56 -07006891 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006892 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006893 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006894 }
6895
Eric Laurente552edb2014-03-10 17:42:56 -07006896}
6897
François Gaffieaaac0fd2018-11-22 17:56:39 +01006898void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6899 bool on,
6900 const sp<AudioOutputDescriptor>& outputDesc,
6901 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006902 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006903{
jiabin9a3361e2019-10-01 09:38:30 -07006904 if (deviceTypes.empty()) {
6905 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006906 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006907 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006908 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006909 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006910 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006911 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006912 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6913 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006914 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006915 }
6916 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006917 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6918 // ignored
6919 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006920 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006921 if (!outputDesc->isMuted(volumeSource)) {
6922 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006923 return;
6924 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006925 if (outputDesc->decMuteCount(volumeSource) == 0) {
6926 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006927 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006928 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006929 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006930 delayMs);
6931 }
6932 }
6933}
6934
François Gaffie53615e22015-03-19 09:24:12 +01006935bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6936{
François Gaffiec005e562018-11-06 15:04:49 +01006937 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006938 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6939 return true;
6940 }
6941
6942 // has known usage?
6943 switch (paa->usage) {
6944 case AUDIO_USAGE_UNKNOWN:
6945 case AUDIO_USAGE_MEDIA:
6946 case AUDIO_USAGE_VOICE_COMMUNICATION:
6947 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6948 case AUDIO_USAGE_ALARM:
6949 case AUDIO_USAGE_NOTIFICATION:
6950 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6951 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6952 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6953 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6954 case AUDIO_USAGE_NOTIFICATION_EVENT:
6955 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6956 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6957 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6958 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006959 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006960 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006961 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006962 case AUDIO_USAGE_EMERGENCY:
6963 case AUDIO_USAGE_SAFETY:
6964 case AUDIO_USAGE_VEHICLE_STATUS:
6965 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006966 break;
6967 default:
6968 return false;
6969 }
6970 return true;
6971}
6972
François Gaffie2110e042015-03-24 08:41:51 +01006973audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6974{
6975 return mEngine->getForceUse(usage);
6976}
6977
6978bool AudioPolicyManager::isInCall()
6979{
6980 return isStateInCall(mEngine->getPhoneState());
6981}
6982
6983bool AudioPolicyManager::isStateInCall(int state)
6984{
6985 return is_state_in_call(state);
6986}
6987
Eric Laurent74b71512019-11-06 17:21:57 -08006988bool AudioPolicyManager::isCallAudioAccessible()
6989{
6990 audio_mode_t mode = mEngine->getPhoneState();
6991 return (mode == AUDIO_MODE_IN_CALL)
6992 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6993 || (mode == AUDIO_MODE_CALL_SCREEN);
6994}
6995
Eric Laurentd60560a2015-04-10 11:31:20 -07006996void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6997{
6998 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006999 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007000 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007001 sourceDesc->sinkDevice()->equals(deviceDesc))
7002 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007003 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007004 }
7005 }
7006
7007 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7008 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7009 bool release = false;
7010 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7011 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7012 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7013 source->ext.device.type == deviceDesc->type()) {
7014 release = true;
7015 }
7016 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007017 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007018 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7019 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7020 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007021 sink->ext.device.type == deviceDesc->type() &&
7022 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7023 || strncmp(sink->ext.device.address, address,
7024 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007025 release = true;
7026 }
7027 }
7028 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007029 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7030 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007031 }
7032 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007033
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007034 mInputs.clearSessionRoutesForDevice(deviceDesc);
7035
Francois Gaffie716e1432019-01-14 16:58:59 +01007036 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007037}
7038
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007039void AudioPolicyManager::modifySurroundFormats(
7040 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007041 std::unordered_set<audio_format_t> enforcedSurround(
7042 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007043 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7044 for (const auto& pair : mConfig.getSurroundFormats()) {
7045 allSurround.insert(pair.first);
7046 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7047 }
Phil Burk09bc4612016-02-24 15:58:15 -08007048
7049 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7050 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007051 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007052 // This is the resulting set of formats depending on the surround mode:
7053 // 'all surround' = allSurround
7054 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7055 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7056 // 'manual surround' = mManualSurroundFormats
7057 // AUTO: formats v 'enforced surround'
7058 // ALWAYS: formats v 'all surround' v 'enforced surround'
7059 // NEVER: formats ^ 'non-surround'
7060 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007061
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007062 std::unordered_set<audio_format_t> formatSet;
7063 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7064 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007065 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007066 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007067 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007068 formatSet.insert(*formatIter);
7069 }
7070 }
7071 } else {
7072 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7073 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007074 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007075
jiabin81772902018-04-02 17:52:27 -07007076 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007077 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007078 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7079 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7080 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007081 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007082 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7083 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7084 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007085 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007086 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007087 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007088 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007089 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007090 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007091}
7092
jiabin06e4bab2019-07-29 10:13:34 -07007093void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7094 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007095 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7096 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7097
7098 // If NEVER, then remove support for channelMasks > stereo.
7099 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007100 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7101 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007102 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007103 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007104 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007105 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007106 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007107 }
7108 }
jiabin81772902018-04-02 17:52:27 -07007109 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7110 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7111 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007112 bool supports5dot1 = false;
7113 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007114 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007115 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7116 supports5dot1 = true;
7117 break;
7118 }
7119 }
7120 // If not then add 5.1 support.
7121 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007122 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007123 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007124 }
Phil Burk09bc4612016-02-24 15:58:15 -08007125 }
7126}
7127
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007128void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007129 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007130 AudioProfileVector &profiles)
7131{
7132 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007133 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007134
François Gaffie112b0af2015-11-19 16:13:25 +01007135 // Format MUST be checked first to update the list of AudioProfile
7136 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007137 reply = mpClientInterface->getParameters(
7138 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007139 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007140 AudioParameter repliedParameters(reply);
7141 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007142 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007143 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7144 return;
7145 }
Phil Burk09bc4612016-02-24 15:58:15 -08007146 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007147 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007148 if (device == AUDIO_DEVICE_OUT_HDMI
7149 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007150 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007151 }
jiabin3e277cc2019-09-10 14:27:34 -07007152 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007153 }
François Gaffie112b0af2015-11-19 16:13:25 +01007154
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007155 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007156 ChannelMaskSet channelMasks;
7157 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007158 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007159 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007160
7161 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007162 reply = mpClientInterface->getParameters(
7163 ioHandle,
7164 requestedParameters.toString() + ";" +
7165 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007166 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007167 AudioParameter repliedParameters(reply);
7168 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007169 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007170 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007171 }
7172 }
7173 if (profiles.hasDynamicChannelsFor(format)) {
7174 reply = mpClientInterface->getParameters(ioHandle,
7175 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007176 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007177 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007178 AudioParameter repliedParameters(reply);
7179 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007180 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007181 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007182 if (device == AUDIO_DEVICE_OUT_HDMI
7183 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007184 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007185 }
François Gaffie112b0af2015-11-19 16:13:25 +01007186 }
7187 }
jiabin3e277cc2019-09-10 14:27:34 -07007188 addDynamicAudioProfileAndSort(
7189 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007190 }
7191}
Eric Laurentd60560a2015-04-10 11:31:20 -07007192
Mikhail Naganovdc769682018-05-04 15:34:08 -07007193status_t AudioPolicyManager::installPatch(const char *caller,
7194 audio_patch_handle_t *patchHandle,
7195 AudioIODescriptorInterface *ioDescriptor,
7196 const struct audio_patch *patch,
7197 int delayMs)
7198{
7199 ssize_t index = mAudioPatches.indexOfKey(
7200 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7201 *patchHandle : ioDescriptor->getPatchHandle());
7202 sp<AudioPatch> patchDesc;
7203 status_t status = installPatch(
7204 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7205 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007206 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007207 }
7208 return status;
7209}
7210
7211status_t AudioPolicyManager::installPatch(const char *caller,
7212 ssize_t index,
7213 audio_patch_handle_t *patchHandle,
7214 const struct audio_patch *patch,
7215 int delayMs,
7216 uid_t uid,
7217 sp<AudioPatch> *patchDescPtr)
7218{
7219 sp<AudioPatch> patchDesc;
7220 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7221 if (index >= 0) {
7222 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007223 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007224 }
7225
7226 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7227 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7228 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7229 if (status == NO_ERROR) {
7230 if (index < 0) {
7231 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007232 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007233 } else {
7234 patchDesc->mPatch = *patch;
7235 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007236 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007237 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007238 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007239 }
7240 nextAudioPortGeneration();
7241 mpClientInterface->onAudioPatchListUpdate();
7242 }
7243 if (patchDescPtr) *patchDescPtr = patchDesc;
7244 return status;
7245}
7246
jiabinbce0c1d2020-10-05 11:20:18 -07007247bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7248{
7249 const TrackClientVector activeClients = output->getActiveClients();
7250 if (activeClients.empty()) {
7251 return true;
7252 }
7253 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7254 if (index < 0) {
7255 ALOGE("%s, no audio patch found while there are active clients on output %d",
7256 __func__, output->getId());
7257 return false;
7258 }
7259 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7260 DeviceVector routedDevices;
7261 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7262 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7263 patchDesc->mPatch.sinks[i].id);
7264 if (device == nullptr) {
7265 ALOGE("%s, no audio device found with id(%d)",
7266 __func__, patchDesc->mPatch.sinks[i].id);
7267 return false;
7268 }
7269 routedDevices.add(device);
7270 }
7271 for (const auto& client : activeClients) {
7272 // TODO: b/175343099 only travel the valid client
7273 sp<DeviceDescriptor> preferredDevice =
7274 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7275 if (mEngine->getOutputDevicesForAttributes(
7276 client->attributes(), preferredDevice, false) == routedDevices) {
7277 return false;
7278 }
7279 }
7280 return true;
7281}
7282
7283sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentd23aa162022-01-17 17:37:31 +01007284 const sp<IOProfile>& profile, const DeviceVector& devices,
7285 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007286{
7287 for (const auto& device : devices) {
7288 // TODO: This should be checking if the profile supports the device combo.
7289 if (!profile->supportsDevice(device)) {
7290 return nullptr;
7291 }
7292 }
7293 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7294 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd23aa162022-01-17 17:37:31 +01007295 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007296 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7297 if (status != NO_ERROR) {
7298 return nullptr;
7299 }
7300
7301 // Here is where the out_set_parameters() for card & device gets called
7302 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7303 const audio_devices_t deviceType = device->type();
7304 const String8 &address = String8(device->address().c_str());
7305 if (!address.isEmpty()) {
7306 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7307 mpClientInterface->setParameters(output, String8(param));
7308 free(param);
7309 }
7310 updateAudioProfiles(device, output, profile->getAudioProfiles());
7311 if (!profile->hasValidAudioProfile()) {
7312 ALOGW("%s() missing param", __func__);
7313 desc->close();
7314 return nullptr;
7315 } else if (profile->hasDynamicAudioProfile()) {
7316 desc->close();
7317 output = AUDIO_IO_HANDLE_NONE;
7318 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7319 profile->pickAudioProfile(
7320 config.sample_rate, config.channel_mask, config.format);
7321 config.offload_info.sample_rate = config.sample_rate;
7322 config.offload_info.channel_mask = config.channel_mask;
7323 config.offload_info.format = config.format;
7324
Eric Laurentd23aa162022-01-17 17:37:31 +01007325 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007326 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7327 if (status != NO_ERROR) {
7328 return nullptr;
7329 }
7330 }
7331
7332 addOutput(output, desc);
Eric Laurentd23aa162022-01-17 17:37:31 +01007333
jiabinbce0c1d2020-10-05 11:20:18 -07007334 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7335 sp<AudioPolicyMix> policyMix;
7336 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7337 policyMix->setOutput(desc);
7338 desc->mPolicyMix = policyMix;
7339 } else {
7340 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7341 address.string());
7342 }
7343
Eric Laurentd23aa162022-01-17 17:37:31 +01007344 } else if (hasPrimaryOutput() && profile->getModule()
7345 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7346 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7347 // no duplicated output for:
7348 // - direct outputs
7349 // - outputs used by dynamic policy mixes
7350 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007351 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7352
7353 //TODO: configure audio effect output stage here
7354
7355 // open a duplicating output thread for the new output and the primary output
7356 sp<SwAudioOutputDescriptor> dupOutputDesc =
7357 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7358 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7359 if (status == NO_ERROR) {
7360 // add duplicated output descriptor
7361 addOutput(duplicatedOutput, dupOutputDesc);
7362 } else {
7363 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7364 mPrimaryOutput->mIoHandle, output);
7365 desc->close();
7366 removeOutput(output);
7367 nextAudioPortGeneration();
7368 return nullptr;
7369 }
7370 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007371 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7372 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7373 mPrimaryOutput = desc;
7374 }
jiabinbce0c1d2020-10-05 11:20:18 -07007375 return desc;
7376}
7377
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007378} // namespace android