blob: fb7ae4fe2384d105878044be31b52645ceed5f92 [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
Mikhail Naganov37977152018-07-11 15:54:44 -0700252 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 Laurentf4e63452017-11-06 19:31:46 +0000946audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700947{
François Gaffiec005e562018-11-06 15:04:49 +0100948 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800949
950 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
951 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
952 // format, flags, etc. This may result in some discrepancy for functions that utilize
953 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
954 // and AudioSystem::getOutputSamplingRate().
955
François Gaffie11d30102018-11-02 16:09:09 +0100956 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700957 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700958
François Gaffie11d30102018-11-02 16:09:09 +0100959 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
960 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000961 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700962}
963
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700964status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
965 const audio_attributes_t *srcAttr,
966 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700967{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700968 if (srcAttr != NULL) {
969 if (!isValidAttributes(srcAttr)) {
970 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
971 __func__,
972 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
973 srcAttr->tags);
974 return BAD_VALUE;
975 }
976 *dstAttr = *srcAttr;
977 } else {
978 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
979 ALOGE("%s: invalid stream type", __func__);
980 return BAD_VALUE;
981 }
François Gaffiec005e562018-11-06 15:04:49 +0100982 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700983 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700984
985 // Only honor audibility enforced when required. The client will be
986 // forced to reconnect if the forced usage changes.
987 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700988 dstAttr->flags = static_cast<audio_flags_mask_t>(
989 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700990 }
991
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700992 return NO_ERROR;
993}
994
Kevin Rocard153f92d2018-12-18 18:33:28 -0800995status_t AudioPolicyManager::getOutputForAttrInt(
996 audio_attributes_t *resultAttr,
997 audio_io_handle_t *output,
998 audio_session_t session,
999 const audio_attributes_t *attr,
1000 audio_stream_type_t *stream,
1001 uid_t uid,
1002 const audio_config_t *config,
1003 audio_output_flags_t *flags,
1004 audio_port_handle_t *selectedDeviceId,
1005 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001006 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001007 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001008{
François Gaffiec005e562018-11-06 15:04:49 +01001009 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001010 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001011 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001012 const sp<DeviceDescriptor> requestedDevice =
1013 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1014
Eric Laurent8a1095a2019-11-08 14:44:16 -08001015 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001016 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1017 if (status != NO_ERROR) {
1018 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001019 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001020 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001021 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001022 }
François Gaffiec005e562018-11-06 15:04:49 +01001023 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001024
François Gaffiec005e562018-11-06 15:04:49 +01001025 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1026 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001027
Kevin Rocard153f92d2018-12-18 18:33:28 -08001028 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1029 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1030 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001031 sp<AudioPolicyMix> primaryMix;
1032 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001033 if (status != OK) {
1034 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001035 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001036
Kevin Rocard153f92d2018-12-18 18:33:28 -08001037 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001038 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001039
1040 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001041 if ((usePrimaryOutputFromPolicyMixes
1042 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001043 && !audio_is_linear_pcm(config->format)) {
1044 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001045 return BAD_VALUE;
1046 }
1047 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001048 sp<DeviceDescriptor> deviceDesc =
1049 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1050 primaryMix->mDeviceAddress,
1051 AUDIO_FORMAT_DEFAULT);
1052 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001053 if (deviceDesc != nullptr
1054 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001055 audio_io_handle_t newOutput;
1056 status = openDirectOutput(
1057 *stream, session, config,
1058 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1059 DeviceVector(deviceDesc), &newOutput);
1060 if (status != NO_ERROR) {
1061 policyDesc = nullptr;
1062 } else {
1063 policyDesc = mOutputs.valueFor(newOutput);
1064 primaryMix->setOutput(policyDesc);
1065 }
1066 }
1067 if (policyDesc != nullptr) {
1068 policyDesc->mPolicyMix = primaryMix;
1069 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001070 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001071
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001072 ALOGV("getOutputForAttr() returns output %d", *output);
1073 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1074 *outputType = API_OUT_MIX_PLAYBACK;
1075 } else {
1076 *outputType = API_OUTPUT_LEGACY;
1077 }
1078 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001080 }
François Gaffiec005e562018-11-06 15:04:49 +01001081 // Virtual sources must always be dynamicaly or explicitly routed
1082 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1083 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1084 return BAD_VALUE;
1085 }
1086 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1087 // in order to let the choice of the order to future vendor engine
1088 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001089
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001090 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001091 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001092 }
1093
Nadav Barb2f18162018-07-18 13:01:53 +03001094 // Set incall music only if device was explicitly set, and fallback to the device which is
1095 // chosen by the engine if not.
1096 // FIXME: provide a more generic approach which is not device specific and move this back
1097 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001098 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001099 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001100 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001101 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001102 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001103 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001104 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001105 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001106 }
1107 }
1108
François Gaffiec005e562018-11-06 15:04:49 +01001109 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1110 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1111 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001112
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001113 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001114 if (!msdDevices.isEmpty()) {
1115 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001116 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001117 ALOGV("%s() Using MSD devices %s instead of devices %s",
1118 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001119 } else {
1120 *output = AUDIO_IO_HANDLE_NONE;
1121 }
1122 }
1123 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001124 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001125 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001126 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001127 if (*output == AUDIO_IO_HANDLE_NONE) {
1128 return INVALID_OPERATION;
1129 }
Paul McLeanaa981192015-03-21 09:55:15 -07001130
François Gaffiec005e562018-11-06 15:04:49 +01001131 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001132 for (auto &outputDevice : outputDevices) {
1133 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1134 *selectedDeviceId = outputDevice->getId();
1135 break;
1136 }
1137 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001138
Eric Laurent8a1095a2019-11-08 14:44:16 -08001139 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1140 *outputType = API_OUTPUT_TELEPHONY_TX;
1141 } else {
1142 *outputType = API_OUTPUT_LEGACY;
1143 }
1144
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1146
1147 return NO_ERROR;
1148}
1149
1150status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1151 audio_io_handle_t *output,
1152 audio_session_t session,
1153 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001154 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001155 const audio_config_t *config,
1156 audio_output_flags_t *flags,
1157 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001158 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001159 std::vector<audio_io_handle_t> *secondaryOutputs,
1160 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161{
1162 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1163 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1164 return INVALID_OPERATION;
1165 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001166 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001167 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001168 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001170 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001171 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001172 const sp<DeviceDescriptor> requestedDevice =
1173 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1174
1175 // Prevent from storing invalid requested device id in clients
1176 const audio_port_handle_t sanitizedRequestedPortId =
1177 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1178 *selectedDeviceId = sanitizedRequestedPortId;
1179
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001180 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001182 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 if (status != NO_ERROR) {
1184 return status;
1185 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001187 if (secondaryOutputs != nullptr) {
1188 for (auto &secondaryMix : secondaryMixes) {
1189 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1190 if (outputDesc != nullptr &&
1191 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1192 secondaryOutputs->push_back(outputDesc->mIoHandle);
1193 weakSecondaryOutputDescs.push_back(outputDesc);
1194 }
1195 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001196 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001197
Eric Laurent8fc147b2018-07-22 19:13:55 -07001198 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001199 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001200 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001201 };
jiabin4ef93452019-09-10 14:29:54 -07001202 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001203
Eric Laurentc209fe42020-06-05 18:11:23 -07001204 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001205 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001206 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001207 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001208 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001209 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001211 std::move(weakSecondaryOutputDescs),
1212 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001213 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001214
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001215 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1216 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001217
Eric Laurente83b55d2014-11-14 10:06:21 -08001218 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001219}
1220
Eric Laurentc529cf62020-04-17 18:19:10 -07001221status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1222 audio_session_t session,
1223 const audio_config_t *config,
1224 audio_output_flags_t flags,
1225 const DeviceVector &devices,
1226 audio_io_handle_t *output) {
1227
1228 *output = AUDIO_IO_HANDLE_NONE;
1229
1230 // skip direct output selection if the request can obviously be attached to a mixed output
1231 // and not explicitly requested
1232 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1233 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1234 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1235 return NAME_NOT_FOUND;
1236 }
1237
1238 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1239 // This prevents creating an offloaded track and tearing it down immediately after start
1240 // when audioflinger detects there is an active non offloadable effect.
1241 // FIXME: We should check the audio session here but we do not have it in this context.
1242 // This may prevent offloading in rare situations where effects are left active by apps
1243 // in the background.
1244 sp<IOProfile> profile;
1245 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1246 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1247 profile = getProfileForOutput(
1248 devices, config->sample_rate, config->format, config->channel_mask,
1249 flags, true /* directOnly */);
1250 }
1251
1252 if (profile == nullptr) {
1253 return NAME_NOT_FOUND;
1254 }
1255
1256 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1257 for (size_t i = 0; i < mOutputs.size(); i++) {
1258 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1259 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1260 // reuse direct output if currently open by the same client
1261 // and configured with same parameters
1262 if ((config->sample_rate == desc->getSamplingRate()) &&
1263 (config->format == desc->getFormat()) &&
1264 (config->channel_mask == desc->getChannelMask()) &&
1265 (session == desc->mDirectClientSession)) {
1266 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001267 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001268 mOutputs.keyAt(i), session);
1269 *output = mOutputs.keyAt(i);
1270 return NO_ERROR;
1271 }
1272 }
1273 }
1274
1275 if (!profile->canOpenNewIo()) {
1276 return NAME_NOT_FOUND;
1277 }
1278
1279 sp<SwAudioOutputDescriptor> outputDesc =
1280 new SwAudioOutputDescriptor(profile, mpClientInterface);
1281
Michael Chan6fb34492020-12-08 15:44:49 +11001282 // An MSD patch may be using the only output stream that can service this request. Release
1283 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001284 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001285
1286 status_t status = outputDesc->open(config, devices, stream, flags, output);
1287
1288 // only accept an output with the requested parameters
1289 if (status != NO_ERROR ||
1290 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1291 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1292 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1293 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1294 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1295 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1296 config->channel_mask, outputDesc->getChannelMask());
1297 if (*output != AUDIO_IO_HANDLE_NONE) {
1298 outputDesc->close();
1299 }
1300 // fall back to mixer output if possible when the direct output could not be open
1301 if (audio_is_linear_pcm(config->format) &&
1302 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1303 return NAME_NOT_FOUND;
1304 }
1305 *output = AUDIO_IO_HANDLE_NONE;
1306 return BAD_VALUE;
1307 }
1308 outputDesc->mDirectOpenCount = 1;
1309 outputDesc->mDirectClientSession = session;
1310
1311 addOutput(*output, outputDesc);
1312 mPreviousOutputs = mOutputs;
1313 ALOGV("%s returns new direct output %d", __func__, *output);
1314 mpClientInterface->onAudioPortListUpdate();
1315 return NO_ERROR;
1316}
1317
François Gaffie11d30102018-11-02 16:09:09 +01001318audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1319 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001320 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001321 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001322 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001323 audio_output_flags_t *flags,
1324 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001325{
Andy Hungc88b0642018-04-27 15:42:35 -07001326 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001327
jiabine375d412019-02-26 12:54:53 -08001328 // Discard haptic channel mask when forcing muting haptic channels.
1329 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001330 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1331 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001332
Eric Laurente552edb2014-03-10 17:42:56 -07001333 // open a direct output if required by specified parameters
1334 //force direct flag if offload flag is set: offloading implies a direct output stream
1335 // and all common behaviors are driven by checking only the direct flag
1336 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001337 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1338 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001339 }
Nadav Bar766fb022018-01-07 12:18:03 +02001340 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1341 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001342 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001343 // only allow deep buffering for music stream type
1344 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001345 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001346 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001347 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001348 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1349 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001350 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001351 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001352 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001353 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001354 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001355 audio_is_linear_pcm(config->format) &&
1356 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001357 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001358 AUDIO_OUTPUT_FLAG_DIRECT);
1359 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001360 }
Eric Laurente552edb2014-03-10 17:42:56 -07001361
Eric Laurentc529cf62020-04-17 18:19:10 -07001362 audio_config_t directConfig = *config;
1363 directConfig.channel_mask = channelMask;
1364 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1365 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001366 return output;
1367 }
1368
Eric Laurent14cbfca2016-03-17 09:42:16 -07001369 // A request for HW A/V sync cannot fallback to a mixed output because time
1370 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001371 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001372 return AUDIO_IO_HANDLE_NONE;
1373 }
1374
Eric Laurente552edb2014-03-10 17:42:56 -07001375 // ignoring channel mask due to downmix capability in mixer
1376
1377 // open a non direct output
1378
1379 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001380 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001381 // get which output is suitable for the specified stream. The actual
1382 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001383 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001384
Eric Laurent8838a382014-09-08 16:44:28 -07001385 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001386 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001387 output = selectOutput(
1388 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001389 }
François Gaffie11d30102018-11-02 16:09:09 +01001390 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001391 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001392 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001393
Eric Laurente552edb2014-03-10 17:42:56 -07001394 return output;
1395}
1396
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001397sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001398 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1399 mAvailableInputDevices);
1400 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1401}
1402
1403DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1404 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1405 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001406}
1407
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001408const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001409 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001410 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1411 if (msdModule != 0) {
1412 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1413 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1414 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1415 const struct audio_port_config *source = &patch->mPatch.sources[j];
1416 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1417 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001418 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001419 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001420 }
1421 }
1422 }
1423 return msdPatches;
1424}
1425
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001426status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1427 const InputProfileCollection &inputProfiles,
1428 const OutputProfileCollection &outputProfiles,
1429 const sp<DeviceDescriptor> &sourceDevice,
1430 const sp<DeviceDescriptor> &sinkDevice,
1431 AudioProfileVector& sourceProfiles,
1432 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001433 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001434 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001435 return NO_INIT;
1436 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001438 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001439 return NO_INIT;
1440 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001442 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1443 inProfile->supportsDevice(sourceDevice)) {
1444 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001445 }
1446 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001447 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001448 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001449 outProfile->supportsDevice(sinkDevice)) {
1450 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001451 }
1452 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001453 return NO_ERROR;
1454}
1455
1456status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1457 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1458 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1459{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001460 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001461 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1462 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1463 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001464 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001465 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1466 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001467 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001468 }
1469 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1470 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1471 sinkConfig->format = bestSinkConfig.format;
1472 // For encoded streams force direct flag to prevent downstream mixing.
1473 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1474 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001475 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1476 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001477 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001478 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1479 // raw and IEC61937 framed streams.
1480 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1481 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1482 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1484 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1485 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1486 sourceConfig->format = bestSinkConfig.format;
1487 // Copy input stream directly without any processing (e.g. resampling).
1488 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1489 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1490 if (hwAvSync) {
1491 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1492 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1493 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1494 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1495 }
1496 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1497 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1498 sinkConfig->config_mask |= config_mask;
1499 sourceConfig->config_mask |= config_mask;
1500 return NO_ERROR;
1501}
1502
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001503PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1504 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001505{
1506 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001507 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1508 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1509 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1510 if (deviceModule == nullptr) {
1511 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1512 return patchBuilder;
1513 }
1514 const InputProfileCollection inputProfiles = msdIsSource ?
1515 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1516 const OutputProfileCollection outputProfiles = msdIsSource ?
1517 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1518
1519 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1520 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1521 device : getMsdAudioOutDevices().itemAt(0);
1522 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1523
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001524 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1525 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001526 AudioProfileVector sourceProfiles;
1527 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001528 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1529 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001530 for (auto hwAvSync : { true, false }) {
1531 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1532 sourceProfiles, sinkProfiles) != NO_ERROR) {
1533 continue;
1534 }
1535 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1536 &sinkConfig) == NO_ERROR) {
1537 // Found a matching config. Re-create PatchBuilder with this config.
1538 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1539 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001540 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001541 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001542 " supporting PCM format conversion.", __func__);
1543 return patchBuilder;
1544}
1545
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001546status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001547 DeviceVector devices;
1548 if (outputDevices != nullptr && outputDevices->size() > 0) {
1549 devices.add(*outputDevices);
1550 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 // Use media strategy for unspecified output device. This should only
1552 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1553 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001554 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001555 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001556 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001557 }
Michael Chan6fb34492020-12-08 15:44:49 +11001558 std::vector<PatchBuilder> patchesToCreate;
1559 for (auto i = 0u; i < devices.size(); ++i) {
1560 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001561 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001562 }
1563 // Retain only the MSD patches associated with outputDevices request.
1564 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001565 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001566 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1567 auto retainedPatch = false;
1568 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1569 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1570 patchesToRemove.removeItemsAt(i);
1571 retainedPatch = true;
1572 break;
1573 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 }
Michael Chan6fb34492020-12-08 15:44:49 +11001575 if (retainedPatch) {
1576 it = patchesToCreate.erase(it);
1577 continue;
1578 }
1579 ++it;
1580 }
1581 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1582 return NO_ERROR;
1583 }
1584 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1585 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001586 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001587 }
Michael Chan6fb34492020-12-08 15:44:49 +11001588 status_t status = NO_ERROR;
1589 for (const auto &p : patchesToCreate) {
1590 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1591 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1592 char message[256];
1593 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1594 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1595 currStatus == NO_ERROR ? "Success" : "Error",
1596 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1597 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1598 if (currStatus == NO_ERROR) {
1599 ALOGD("%s", message);
1600 } else {
1601 ALOGE("%s", message);
1602 if (status == NO_ERROR) {
1603 status = currStatus;
1604 }
1605 }
1606 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001607 return status;
1608}
1609
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1611 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001612 for (size_t i = 0; i < msdPatches.size(); i++) {
1613 const auto& patch = msdPatches[i];
1614 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1615 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1616 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1617 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1618 releaseAudioPatch(patch->getHandle(), mUidCached);
1619 break;
1620 }
1621 }
1622 }
1623}
1624
Eric Laurente0720872014-03-11 09:30:41 -07001625audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001626 audio_output_flags_t flags,
1627 audio_format_t format,
1628 audio_channel_mask_t channelMask,
1629 uint32_t samplingRate,
1630 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001631{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001632 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1633 "%s called with format %#x", __func__, format);
1634
jiabinebb6af42020-06-09 17:31:17 -07001635 // Return the output that haptic-generating attached to when 1) session id is specified,
1636 // 2) haptic-generating effect exists for given session id and 3) the output that
1637 // haptic-generating effect attached to is in given outputs.
1638 if (sessionId != AUDIO_SESSION_NONE) {
1639 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1640 sessionId, FX_IID_HAPTICGENERATOR);
1641 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1642 return hapticGeneratingOutput;
1643 }
1644 }
1645
Eric Laurent16c66dd2019-05-01 17:54:10 -07001646 // Flags disqualifying an output: the match must happen before calling selectOutput()
1647 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1648 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1649
1650 // Flags expressing a functional request: must be honored in priority over
1651 // other criteria
1652 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1653 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1654 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1655 // Flags expressing a performance request: have lower priority than serving
1656 // requested sampling rate or channel mask
1657 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1658 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1659 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1660
1661 const audio_output_flags_t functionalFlags =
1662 (audio_output_flags_t)(flags & kFunctionalFlags);
1663 const audio_output_flags_t performanceFlags =
1664 (audio_output_flags_t)(flags & kPerformanceFlags);
1665
1666 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1667
Eric Laurente552edb2014-03-10 17:42:56 -07001668 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001669 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001670 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001671 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001672 // 2: the output with the highest number of requested functional flags
1673 // 3: the output supporting the exact channel mask
1674 // 4: the output with a higher channel count than requested
1675 // 5: the output with a higher sampling rate than requested
1676 // 6: the output with the highest number of requested performance flags
1677 // 7: the output with the bit depth the closest to the requested one
1678 // 8: the primary output
1679 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 // matching criteria values in priority order for best matching output so far
1682 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001683
Eric Laurent16c66dd2019-05-01 17:54:10 -07001684 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1685 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1686 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001687
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001688 for (audio_io_handle_t output : outputs) {
1689 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001690 // matching criteria values in priority order for current output
1691 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001692
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 if (outputDesc->isDuplicated()) {
1694 continue;
1695 }
1696 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1697 continue;
1698 }
Eric Laurent8838a382014-09-08 16:44:28 -07001699
Eric Laurent16c66dd2019-05-01 17:54:10 -07001700 // If haptic channel is specified, use the haptic output if present.
1701 // When using haptic output, same audio format and sample rate are required.
1702 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001703 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001704 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1705 continue;
1706 }
1707 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001708 && format == outputDesc->getFormat()
1709 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001710 currentMatchCriteria[0] = outputHapticChannelCount;
1711 }
1712
1713 // functional flags match
1714 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1715
1716 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001717 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1718 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001719 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1720 channelCount <= outputChannelCount) {
1721 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001722 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1723 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001724 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001726 currentMatchCriteria[3] = outputChannelCount;
1727 }
1728
1729 // sampling rate match
1730 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001731 samplingRate <= outputDesc->getSamplingRate()) {
1732 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001733 }
1734
1735 // performance flags match
1736 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1737
1738 // format match
1739 if (format != AUDIO_FORMAT_INVALID) {
1740 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001741 PolicyAudioPort::kFormatDistanceMax -
1742 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001743 }
1744
1745 // primary output match
1746 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1747
1748 // compare match criteria by priority then value
1749 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1750 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1751 bestMatchCriteria = currentMatchCriteria;
1752 bestOutput = output;
1753
1754 std::stringstream result;
1755 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1756 std::ostream_iterator<int>(result, " "));
1757 ALOGV("%s new bestOutput %d criteria %s",
1758 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001759 }
1760 }
1761
Eric Laurent16c66dd2019-05-01 17:54:10 -07001762 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001763}
1764
Eric Laurent8fc147b2018-07-22 19:13:55 -07001765status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001766{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001767 ALOGV("%s portId %d", __FUNCTION__, portId);
1768
1769 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1770 if (outputDesc == 0) {
1771 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001772 return BAD_VALUE;
1773 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001774 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001775
Eric Laurent8fc147b2018-07-22 19:13:55 -07001776 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001777 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001778
Eric Laurent733ce942017-12-07 12:18:25 -08001779 status_t status = outputDesc->start();
1780 if (status != NO_ERROR) {
1781 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001782 }
1783
Eric Laurent97ac8712018-07-27 18:59:02 -07001784 uint32_t delayMs;
1785 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001786
1787 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001788 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001789 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001790 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001791 if (delayMs != 0) {
1792 usleep(delayMs * 1000);
1793 }
1794
1795 return status;
1796}
1797
Eric Laurent97ac8712018-07-27 18:59:02 -07001798status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1799 const sp<TrackClientDescriptor>& client,
1800 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001801{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001802 // cannot start playback of STREAM_TTS if any other output is being used
1803 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001804
1805 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001806 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001807 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001808 auto clientStrategy = client->strategy();
1809 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001810 if (stream == AUDIO_STREAM_TTS) {
1811 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001812 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001813 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001814 return INVALID_OPERATION;
1815 } else {
1816 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1817 }
1818 } else {
1819 // some playback other than beacon starts
1820 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1821 }
1822
Eric Laurent77305a62016-07-25 16:39:22 -07001823 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001824 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001825 bool force = !outputDesc->isActive() &&
1826 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001827
François Gaffie11d30102018-11-02 16:09:09 +01001828 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001829 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001830 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001831 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001832 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001833 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001834 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001835 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001836 } else {
1837 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001838 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001839 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1840 AUDIO_FORMAT_DEFAULT);
1841 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1842 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001843 }
1844
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001845 // requiresMuteCheck is false when we can bypass mute strategy.
1846 // It covers a common case when there is no materially active audio
1847 // and muting would result in unnecessary delay and dropped audio.
1848 const uint32_t outputLatencyMs = outputDesc->latency();
1849 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1850
Eric Laurente552edb2014-03-10 17:42:56 -07001851 // increment usage count for this stream on the requested output:
1852 // NOTE that the usage count is the same for duplicated output and hardware output which is
1853 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001854 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001855
1856 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001857 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1858 client->isPreferredDeviceForExclusiveUse()) {
1859 // Preferred device may be exclusive, use only if no other active clients on this output
1860 devices = DeviceVector(
1861 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1862 } else {
1863 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1864 }
François Gaffie11d30102018-11-02 16:09:09 +01001865 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001866 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001867 }
1868 }
Eric Laurente552edb2014-03-10 17:42:56 -07001869
François Gaffiec005e562018-11-06 15:04:49 +01001870 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001871 selectOutputForMusicEffects();
1872 }
1873
François Gaffie1c878552018-11-22 16:53:21 +01001874 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001875 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001876 if (devices.isEmpty()) {
1877 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001878 }
François Gaffiec005e562018-11-06 15:04:49 +01001879 bool shouldWait =
1880 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1881 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1882 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001883 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001884 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001885 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001886 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001887 // An output has a shared device if
1888 // - managed by the same hw module
1889 // - supports the currently selected device
1890 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001891 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001892
Eric Laurent77305a62016-07-25 16:39:22 -07001893 // force a device change if any other output is:
1894 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001895 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001896 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001897 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001898 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001899 // change the device currently selected by the other output.
1900 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001901 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001902 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001903 force = true;
1904 }
1905 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001906 // a notification so that audio focus effect can propagate, or that a mute/unmute
1907 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001908 const uint32_t latencyMs = desc->latency();
1909 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1910
1911 if (shouldWait && isActive && (waitMs < latencyMs)) {
1912 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001913 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001914
1915 // Require mute check if another output is on a shared device
1916 // and currently active to have proper drain and avoid pops.
1917 // Note restoring AudioTracks onto this output needs to invoke
1918 // a volume ramp if there is no mute.
1919 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001920 }
1921 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001922
1923 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001924 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001925
Eric Laurente552edb2014-03-10 17:42:56 -07001926 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001927 auto &curves = getVolumeCurves(client->attributes());
1928 checkAndSetVolume(curves, client->volumeSource(),
1929 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001930 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001931 outputDesc->devices().types(), 0 /*delay*/,
1932 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001933
1934 // update the outputs if starting an output with a stream that can affect notification
1935 // routing
1936 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001937
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001938 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001939 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001940 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1941 }
Eric Laurentdc462862016-07-19 12:29:53 -07001942
1943 if (waitMs > muteWaitMs) {
1944 *delayMs = waitMs - muteWaitMs;
1945 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001946
1947 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1948 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1949 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1950 // change occurs after the MixerThread starts and causes a stream volume
1951 // glitch.
1952 //
1953 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001954 }
Eric Laurentdc462862016-07-19 12:29:53 -07001955
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001956 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001957 mEngine->getForceUse(
1958 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001959 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001960 }
1961
Eric Laurent97ac8712018-07-27 18:59:02 -07001962 // Automatically enable the remote submix input when output is started on a re routing mix
1963 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001964 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1965 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001966 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1967 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1968 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001969 "remote-submix",
1970 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001971 }
1972
Eric Laurente552edb2014-03-10 17:42:56 -07001973 return NO_ERROR;
1974}
1975
Eric Laurent8fc147b2018-07-22 19:13:55 -07001976status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001977{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001978 ALOGV("%s portId %d", __FUNCTION__, portId);
1979
1980 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1981 if (outputDesc == 0) {
1982 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001983 return BAD_VALUE;
1984 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001985 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001986
Eric Laurent97ac8712018-07-27 18:59:02 -07001987 ALOGV("stopOutput() output %d, stream %d, session %d",
1988 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001989
Eric Laurent97ac8712018-07-27 18:59:02 -07001990 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001991
Eric Laurent733ce942017-12-07 12:18:25 -08001992 if (status == NO_ERROR ) {
1993 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001994 }
1995 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001996}
1997
Eric Laurent97ac8712018-07-27 18:59:02 -07001998status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1999 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002000{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002001 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002002 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002003 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002004
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002005 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2006
François Gaffie1c878552018-11-22 16:53:21 +01002007 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2008 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002009 // Automatically disable the remote submix input when output is stopped on a
2010 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002011 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002012 if (isSingleDeviceType(
2013 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002014 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002015 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002016 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2017 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002018 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002019 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002020 }
2021 }
2022 bool forceDeviceUpdate = false;
2023 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002024 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002025 forceDeviceUpdate = true;
2026 }
2027
Eric Laurente552edb2014-03-10 17:42:56 -07002028 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002029 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002030
Eric Laurente552edb2014-03-10 17:42:56 -07002031 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002032 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002033 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002034 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002035
2036 // If the routing does not change, if an output is routed on a device using HwGain
2037 // (aka setAudioPortConfig) and there are still active clients following different
2038 // volume group(s), force reapply volume
2039 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2040 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2041
Eric Laurente552edb2014-03-10 17:42:56 -07002042 // delay the device switch by twice the latency because stopOutput() is executed when
2043 // the track stop() command is received and at that time the audio track buffer can
2044 // still contain data that needs to be drained. The latency only covers the audio HAL
2045 // and kernel buffers. Also the latency does not always include additional delay in the
2046 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002047 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2048 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002049
2050 // force restoring the device selection on other active outputs if it differs from the
2051 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002052 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002053 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002054 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002055 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002056 desc->isActive() &&
2057 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002058 (newDevices != desc->devices())) {
2059 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2060 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002061
François Gaffie11d30102018-11-02 16:09:09 +01002062 setOutputDevices(desc, newDevices2, force, delayMs);
2063
Eric Laurent57de36c2016-09-28 16:59:11 -07002064 // re-apply device specific volume if not done by setOutputDevice()
2065 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002066 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002067 }
Eric Laurente552edb2014-03-10 17:42:56 -07002068 }
2069 }
2070 // update the outputs if stopping one with a stream that can affect notification routing
2071 handleNotificationRoutingForStream(stream);
2072 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002073
2074 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2075 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002076 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002077 }
2078
François Gaffiec005e562018-11-06 15:04:49 +01002079 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002080 selectOutputForMusicEffects();
2081 }
Eric Laurente552edb2014-03-10 17:42:56 -07002082 return NO_ERROR;
2083 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002084 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002085 return INVALID_OPERATION;
2086 }
2087}
2088
jiabinbce0c1d2020-10-05 11:20:18 -07002089bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002090{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002091 ALOGV("%s portId %d", __FUNCTION__, portId);
2092
2093 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2094 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002095 // If an output descriptor is closed due to a device routing change,
2096 // then there are race conditions with releaseOutput from tracks
2097 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2098 // destroyed shortly thereafter.
2099 //
2100 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002101 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002102 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002104
2105 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002106
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302107 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2108 if (outputDesc->isClientActive(client)) {
2109 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2110 stopOutput(portId);
2111 }
2112
Eric Laurent8fc147b2018-07-22 19:13:55 -07002113 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2114 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002115 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002116 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002117 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002118 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002119 if (--outputDesc->mDirectOpenCount == 0) {
2120 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002121 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002122 }
2123 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302124
Andy Hung39efb7a2018-09-26 15:39:28 -07002125 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002126 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2127 // The output is pending reopened to query dynamic profiles and
2128 // there is no active clients
2129 closeOutput(outputDesc->mIoHandle);
2130 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2131 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2132 if (newOutputDesc == nullptr) {
2133 ALOGE("%s failed to open output", __func__);
2134 }
2135 return true;
2136 }
2137 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002138}
2139
Eric Laurentcaf7f482014-11-25 17:50:47 -08002140status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2141 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002142 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002143 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002144 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002145 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002146 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002147 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002148 input_type_t *inputType,
2149 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002150{
François Gaffiec005e562018-11-06 15:04:49 +01002151 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2152 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2153 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Eric Laurentad2e7b92017-09-14 20:06:42 -07002155 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002156 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002157 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002158 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002159 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002160 sp<AudioInputDescriptor> inputDesc;
2161 sp<RecordClientDescriptor> clientDesc;
2162 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002163 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002164 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165
2166 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2167 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2168 return INVALID_OPERATION;
2169 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002170
Francois Gaffie716e1432019-01-14 16:58:59 +01002171 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2172 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002173 }
2174
Paul McLean466dc8e2015-04-17 13:15:36 -06002175 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002176 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002177 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002178
Eric Laurentad2e7b92017-09-14 20:06:42 -07002179 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2180 // possible
2181 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2182 *input != AUDIO_IO_HANDLE_NONE) {
2183 ssize_t index = mInputs.indexOfKey(*input);
2184 if (index < 0) {
2185 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2186 status = BAD_VALUE;
2187 goto error;
2188 }
2189 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190 RecordClientVector clients = inputDesc->getClientsForSession(session);
2191 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002192 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2193 status = BAD_VALUE;
2194 goto error;
2195 }
2196 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2197 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002198 // corresponds to a new client and is only permitted from the same UID.
2199 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002200 if (clients.size() > 1) {
2201 for (const auto& client : clients) {
2202 // The client map is ordered by key values (portId) and portIds are allocated
2203 // incrementaly. So the first client in this list is the one opened by audio flinger
2204 // when the mmap stream is created and should be ignored as it does not correspond
2205 // to an actual client
2206 if (client == *clients.cbegin()) {
2207 continue;
2208 }
2209 if (uid != client->uid() && !client->isSilenced()) {
2210 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2211 uid, client->portId(), client->uid());
2212 status = INVALID_OPERATION;
2213 goto error;
2214 }
Eric Laurent331679c2018-04-16 17:03:16 -07002215 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002216 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002217 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002218 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002219
Eric Laurentfecbceb2021-02-09 14:46:43 +01002220 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002221 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002222 }
2223
2224 *input = AUDIO_IO_HANDLE_NONE;
2225 *inputType = API_INPUT_INVALID;
2226
Francois Gaffie716e1432019-01-14 16:58:59 +01002227 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002228
Francois Gaffie716e1432019-01-14 16:58:59 +01002229 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2230 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2231 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002232 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002233 ALOGW("%s could not find input mix for attr %s",
2234 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002235 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002236 }
jiabinc1de2df2019-05-07 14:26:40 -07002237 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2238 String8(attr->tags + strlen("addr=")),
2239 AUDIO_FORMAT_DEFAULT);
2240 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002241 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002242 __func__, attributes.source, attributes.tags);
2243 status = BAD_VALUE;
2244 goto error;
2245 }
2246
Kevin Rocard25f9b052019-02-27 15:08:54 -08002247 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2248 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2249 } else {
2250 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2251 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002252 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002253 if (explicitRoutingDevice != nullptr) {
2254 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002255 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002256 // Prevent from storing invalid requested device id in clients
2257 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002258 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002259 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2260 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002261 }
François Gaffie11d30102018-11-02 16:09:09 +01002262 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002263 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002264 status = BAD_VALUE;
2265 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002266 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002267 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2268 *inputType = API_INPUT_MIX_CAPTURE;
2269 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002270 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2271 // there is an external policy, but this input is attached to a mix of recorders,
2272 // meaning it receives audio injected into the framework, so the recorder doesn't
2273 // know about it and is therefore considered "legacy"
2274 *inputType = API_INPUT_LEGACY;
2275 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002276 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002277 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002278 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002279 } else {
2280 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002281 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002282
Eric Laurent599c7582015-12-07 18:05:55 -08002283 }
2284
François Gaffiec005e562018-11-06 15:04:49 +01002285 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002286 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002287 status = INVALID_OPERATION;
2288 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002289 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002290
Eric Laurent8f42ea12018-08-08 09:08:25 -07002291exit:
2292
François Gaffiec005e562018-11-06 15:04:49 +01002293 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2294 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002295
Francois Gaffie716e1432019-01-14 16:58:59 +01002296 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002297 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002298 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002299
Mikhail Naganov2996f672019-04-18 12:29:59 -07002300 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002301 requestedDeviceId, attributes.source, flags,
2302 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002303 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002304 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002305
2306 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2307 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002308
Eric Laurent599c7582015-12-07 18:05:55 -08002309 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002310
2311error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002312 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002313}
2314
2315
François Gaffie11d30102018-11-02 16:09:09 +01002316audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002317 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002318 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002319 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002320 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002321 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002322{
2323 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002324 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002325 bool isSoundTrigger = false;
2326
François Gaffiec005e562018-11-06 15:04:49 +01002327 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002328 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2329 if (index >= 0) {
2330 input = mSoundTriggerSessions.valueFor(session);
2331 isSoundTrigger = true;
2332 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2333 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2334 } else {
2335 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002336 }
François Gaffiec005e562018-11-06 15:04:49 +01002337 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002338 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002339 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002340 }
2341
Andy Hungf129b032015-04-07 13:45:50 -07002342 // find a compatible input profile (not necessarily identical in parameters)
2343 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002344 // sampling rate and flags may be updated by getInputProfile
2345 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2346 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002347 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002348 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002349 audio_input_flags_t profileFlags = flags;
2350 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002351 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002352 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002353 profileFlags);
2354 if (profile != 0) {
2355 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002356 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2357 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002358 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2359 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2360 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002361 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002362 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002363 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002364 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002365 }
Eric Laurente552edb2014-03-10 17:42:56 -07002366 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002367 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002368 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002369 if (samplingRate == 0) {
2370 samplingRate = profileSamplingRate;
2371 }
Eric Laurente552edb2014-03-10 17:42:56 -07002372
Eric Laurent322b4d22015-04-03 15:57:54 -07002373 if (profile->getModuleHandle() == 0) {
2374 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002375 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002376 }
2377
Eric Laurentec376dc2021-04-08 20:41:22 +02002378 // Reuse an already opened input if a client with the same session ID already exists
2379 // on that input
2380 for (size_t i = 0; i < mInputs.size(); i++) {
2381 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2382 if (desc->mProfile != profile) {
2383 continue;
2384 }
2385 RecordClientVector clients = desc->clientsList();
2386 for (const auto &client : clients) {
2387 if (session == client->session()) {
2388 return desc->mIoHandle;
2389 }
2390 }
2391 }
2392
Eric Laurent3974e3b2017-12-07 17:58:43 -08002393 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002394 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002395 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002396 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002397 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002398 continue;
2399 }
2400 // if sound trigger, reuse input if used by other sound trigger on same session
2401 // else
2402 // reuse input if active client app is not in IDLE state
2403 //
2404 RecordClientVector clients = desc->clientsList();
2405 bool doClose = false;
2406 for (const auto& client : clients) {
2407 if (isSoundTrigger != client->isSoundTrigger()) {
2408 continue;
2409 }
2410 if (client->isSoundTrigger()) {
2411 if (session == client->session()) {
2412 return desc->mIoHandle;
2413 }
2414 continue;
2415 }
2416 if (client->active() && client->appState() != APP_STATE_IDLE) {
2417 return desc->mIoHandle;
2418 }
2419 doClose = true;
2420 }
2421 if (doClose) {
2422 closeInput(desc->mIoHandle);
2423 } else {
2424 i++;
2425 }
2426 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002427 }
2428
Eric Laurentfe231122017-11-17 17:48:06 -08002429 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002430
Eric Laurentfe231122017-11-17 17:48:06 -08002431 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2432 lConfig.sample_rate = profileSamplingRate;
2433 lConfig.channel_mask = profileChannelMask;
2434 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002435
François Gaffie11d30102018-11-02 16:09:09 +01002436 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002437
2438 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002439 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002440 (profileSamplingRate != lConfig.sample_rate) ||
2441 !audio_formats_match(profileFormat, lConfig.format) ||
2442 (profileChannelMask != lConfig.channel_mask)) {
2443 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002444 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002445 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002446 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002447 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002448 }
Eric Laurent599c7582015-12-07 18:05:55 -08002449 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002450 }
2451
Eric Laurentc722f302014-12-10 11:21:49 -08002452 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002453
Eric Laurent599c7582015-12-07 18:05:55 -08002454 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002455 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002456
Eric Laurent599c7582015-12-07 18:05:55 -08002457 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002458}
2459
Eric Laurent4eb58f12018-12-07 16:41:02 -08002460status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002461{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002462 ALOGV("%s portId %d", __FUNCTION__, portId);
2463
2464 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2465 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002467 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002468 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002469 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002470 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002471 if (client->active()) {
2472 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2473 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002474 }
2475
Eric Laurent8f42ea12018-08-08 09:08:25 -07002476 audio_session_t session = client->session();
2477
Eric Laurent4eb58f12018-12-07 16:41:02 -08002478 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479
Eric Laurent4eb58f12018-12-07 16:41:02 -08002480 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002481
Eric Laurent4eb58f12018-12-07 16:41:02 -08002482 status_t status = inputDesc->start();
2483 if (status != NO_ERROR) {
2484 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002485 }
Eric Laurente552edb2014-03-10 17:42:56 -07002486
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002487 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002488 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002489 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002490
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491 // indicate active capture to sound trigger service if starting capture from a mic on
2492 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002493 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002494 if (device != nullptr) {
2495 status = setInputDevice(input, device, true /* force */);
2496 } else {
2497 ALOGW("%s no new input device can be found for descriptor %d",
2498 __FUNCTION__, inputDesc->getId());
2499 status = BAD_VALUE;
2500 }
Eric Laurente552edb2014-03-10 17:42:56 -07002501
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002502 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002503 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002504 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002505 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002506 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2507 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002508 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002509 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002510
François Gaffie11d30102018-11-02 16:09:09 +01002511 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2512 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002513 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002514 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002515 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002516
Eric Laurent8f42ea12018-08-08 09:08:25 -07002517 // automatically enable the remote submix output when input is started if not
2518 // used by a policy mix of type MIX_TYPE_RECORDERS
2519 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002520 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002521 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002522 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002523 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002524 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2525 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002526 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002527 if (address != "") {
2528 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2529 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002530 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002531 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002532 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002533 } else if (status != NO_ERROR) {
2534 // Restore client activity state.
2535 inputDesc->setClientActive(client, false);
2536 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002537 }
2538
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002539 ALOGV("%s input %d source = %d status = %d exit",
2540 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002541
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002542 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002543}
2544
Eric Laurent8fc147b2018-07-22 19:13:55 -07002545status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002546{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002547 ALOGV("%s portId %d", __FUNCTION__, portId);
2548
2549 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2550 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002551 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002552 return BAD_VALUE;
2553 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002554 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002555 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 if (!client->active()) {
2557 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002558 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002559 }
Carter Hsue6139d52021-07-08 10:30:20 +08002560 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002562
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563 inputDesc->stop();
2564 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002565 auto current_source = inputDesc->source();
2566 setInputDevice(input, getNewInputDevice(inputDesc),
2567 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002568 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002569 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002570 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002571 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002572 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2573 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002574 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002575 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002576
2577 // automatically disable the remote submix output when input is stopped if not
2578 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002579 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002580 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002581 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002582 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002583 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2584 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002585 }
2586 if (address != "") {
2587 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2588 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002589 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590 }
2591 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002592 resetInputDevice(input);
2593
2594 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2595 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002596 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2597 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002599 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600 }
2601 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002602 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002603 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002604}
2605
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 ALOGV("%s portId %d", __FUNCTION__, portId);
2609
2610 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2611 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002612 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 return;
2614 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002615 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002616 audio_io_handle_t input = inputDesc->mIoHandle;
2617
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002619
Andy Hung39efb7a2018-09-26 15:39:28 -07002620 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002621
Andy Hung39efb7a2018-09-26 15:39:28 -07002622 if (inputDesc->getClientCount() > 0) {
2623 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002624 return;
2625 }
2626
Eric Laurent05b90f82014-08-27 15:32:29 -07002627 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002628 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002629 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002630}
2631
Eric Laurent8f42ea12018-08-08 09:08:25 -07002632void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002633{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002634 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002635
2636 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002637 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002638 }
2639}
2640
Eric Laurent8f42ea12018-08-08 09:08:25 -07002641void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2642{
2643 stopInput(portId);
2644 releaseInput(portId);
2645}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002646
Eric Laurent0dd51852019-04-19 18:18:58 -07002647void AudioPolicyManager::checkCloseInputs() {
2648 // After connecting or disconnecting an input device, close input if:
2649 // - it has no client (was just opened to check profile) OR
2650 // - none of its supported devices are connected anymore OR
2651 // - one of its clients cannot be routed to one of its supported
2652 // devices anymore. Otherwise update device selection
2653 std::vector<audio_io_handle_t> inputsToClose;
2654 for (size_t i = 0; i < mInputs.size(); i++) {
2655 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2656 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002657 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002658 inputsToClose.push_back(mInputs.keyAt(i));
2659 } else {
2660 bool close = false;
2661 for (const auto& client : input->clientsList()) {
2662 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002663 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002664 if (!input->supportedDevices().contains(device)) {
2665 close = true;
2666 break;
2667 }
2668 }
2669 if (close) {
2670 inputsToClose.push_back(mInputs.keyAt(i));
2671 } else {
2672 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2673 }
2674 }
2675 }
2676
2677 for (const audio_io_handle_t handle : inputsToClose) {
2678 ALOGV("%s closing input %d", __func__, handle);
2679 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002680 }
Eric Laurentd4692962014-05-05 18:13:44 -07002681}
2682
François Gaffie251c7f02018-11-07 10:41:08 +01002683void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002684{
2685 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002686 if (indexMin < 0 || indexMax < 0) {
2687 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2688 return;
2689 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002690 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002691
2692 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002693 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2694 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002695 continue;
2696 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002697 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002698 }
Eric Laurente552edb2014-03-10 17:42:56 -07002699}
2700
Eric Laurente0720872014-03-11 09:30:41 -07002701status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002702 int index,
2703 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002704{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002705 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002706 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2707 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2708 return NO_ERROR;
2709 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002710 ALOGV("%s: stream %s attributes=%s", __func__,
2711 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002712 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002713}
2714
Eric Laurente0720872014-03-11 09:30:41 -07002715status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002716 int *index,
2717 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002718{
François Gaffiec005e562018-11-06 15:04:49 +01002719 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2720 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002721 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002722 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002723 deviceTypes = mEngine->getOutputDevicesForStream(
2724 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002725 }
jiabin9a3361e2019-10-01 09:38:30 -07002726 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002727}
2728
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002729status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002730 int index,
2731 audio_devices_t device)
2732{
2733 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002734 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2735 if (group == VOLUME_GROUP_NONE) {
2736 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002737 return BAD_VALUE;
2738 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002739 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002740 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002741 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002742 VolumeSource vs = toVolumeSource(group);
2743 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2744
2745 status = setVolumeCurveIndex(index, device, curves);
2746 if (status != NO_ERROR) {
2747 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2748 return status;
2749 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002750
jiabin9a3361e2019-10-01 09:38:30 -07002751 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002752 auto curCurvAttrs = curves.getAttributes();
2753 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2754 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002755 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002756 } else if (!curves.getStreamTypes().empty()) {
2757 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002758 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002759 } else {
2760 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2761 return BAD_VALUE;
2762 }
jiabin9a3361e2019-10-01 09:38:30 -07002763 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2764 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002765
François Gaffiecfe17322018-11-07 13:41:29 +01002766 // update volume on all outputs and streams matching the following:
2767 // - The requested stream (or a stream matching for volume control) is active on the output
2768 // - The device (or devices) selected by the engine for this stream includes
2769 // the requested device
2770 // - For non default requested device, currently selected device on the output is either the
2771 // requested device or one of the devices selected by the engine for this stream
2772 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2773 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002774 for (size_t i = 0; i < mOutputs.size(); i++) {
2775 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002776 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002777
jiabin9a3361e2019-10-01 09:38:30 -07002778 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2779 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002780 }
François Gaffieed91f582020-01-31 10:35:37 +01002781 if (!(desc->isActive(vs) || isInCall())) {
2782 continue;
2783 }
2784 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2785 curDevices.find(device) == curDevices.end()) {
2786 continue;
2787 }
2788 bool applyVolume = false;
2789 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2790 curSrcDevices.insert(device);
2791 applyVolume = (curSrcDevices.find(
2792 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2793 } else {
2794 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2795 }
2796 if (!applyVolume) {
2797 continue; // next output
2798 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002799 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2800 // If a higher priority strategy is active, and the output is routed to a device with a
2801 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002802 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002803 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002804 // If the volume source is active with higher priority source, ensure at least Sw Muted
2805 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002806 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2807 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2808 false /*preferredDevice*/);
2809 if (activeClients.empty()) {
2810 continue;
2811 }
2812 bool isPreempted = false;
2813 bool isHigherPriority = productStrategy < strategy;
2814 for (const auto &client : activeClients) {
2815 if (isHigherPriority && (client->volumeSource() != vs)) {
2816 ALOGV("%s: Strategy=%d (\nrequester:\n"
2817 " group %d, volumeGroup=%d attributes=%s)\n"
2818 " higher priority source active:\n"
2819 " volumeGroup=%d attributes=%s) \n"
2820 " on output %zu, bailing out", __func__, productStrategy,
2821 group, group, toString(attributes).c_str(),
2822 client->volumeSource(), toString(client->attributes()).c_str(), i);
2823 applyVolume = false;
2824 isPreempted = true;
2825 break;
2826 }
2827 // However, continue for loop to ensure no higher prio clients running on output
2828 if (client->volumeSource() == vs) {
2829 applyVolume = true;
2830 }
2831 }
2832 if (isPreempted || applyVolume) {
2833 break;
2834 }
2835 }
2836 if (!applyVolume) {
2837 continue; // next output
2838 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002839 }
François Gaffieed91f582020-01-31 10:35:37 +01002840 //FIXME: workaround for truncated touch sounds
2841 // delayed volume change for system stream to be removed when the problem is
2842 // handled by system UI
2843 status_t volStatus = checkAndSetVolume(
2844 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002845 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002846 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2847 if (volStatus != NO_ERROR) {
2848 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002849 }
2850 }
François Gaffiecfe17322018-11-07 13:41:29 +01002851 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2852 return status;
2853}
2854
François Gaffieaaac0fd2018-11-22 17:56:39 +01002855status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002856 audio_devices_t device,
2857 IVolumeCurves &volumeCurves)
2858{
2859 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2860 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002861 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2862 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002863 (index > volumeCurves.getVolumeIndexMax())) {
2864 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2865 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2866 return BAD_VALUE;
2867 }
2868 if (!audio_is_output_device(device)) {
2869 return BAD_VALUE;
2870 }
2871
2872 // Force max volume if stream cannot be muted
2873 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2874
François Gaffieaaac0fd2018-11-22 17:56:39 +01002875 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002876 volumeCurves.addCurrentVolumeIndex(device, index);
2877 return NO_ERROR;
2878}
2879
2880status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2881 int &index,
2882 audio_devices_t device)
2883{
2884 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2885 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002886 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002887 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002888 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2889 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002890 }
jiabin9a3361e2019-10-01 09:38:30 -07002891 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002892}
2893
2894status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2895 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002896 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002897{
jiabin9a3361e2019-10-01 09:38:30 -07002898 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002899 return BAD_VALUE;
2900 }
jiabin9a3361e2019-10-01 09:38:30 -07002901 index = curves.getVolumeIndex(deviceTypes);
2902 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002903 return NO_ERROR;
2904}
2905
2906status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2907 int &index)
2908{
2909 index = getVolumeCurves(attr).getVolumeIndexMin();
2910 return NO_ERROR;
2911}
2912
2913status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2914 int &index)
2915{
2916 index = getVolumeCurves(attr).getVolumeIndexMax();
2917 return NO_ERROR;
2918}
2919
Eric Laurent36829f92017-04-07 19:04:42 -07002920audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002921{
2922 // select one output among several suitable for global effects.
2923 // The priority is as follows:
2924 // 1: An offloaded output. If the effect ends up not being offloadable,
2925 // AudioFlinger will invalidate the track and the offloaded output
2926 // will be closed causing the effect to be moved to a PCM output.
2927 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002928 // 3: The primary output
2929 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002930
François Gaffiec005e562018-11-06 15:04:49 +01002931 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2932 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002933 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002934
Eric Laurent36829f92017-04-07 19:04:42 -07002935 if (outputs.size() == 0) {
2936 return AUDIO_IO_HANDLE_NONE;
2937 }
Eric Laurente552edb2014-03-10 17:42:56 -07002938
Eric Laurent36829f92017-04-07 19:04:42 -07002939 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2940 bool activeOnly = true;
2941
2942 while (output == AUDIO_IO_HANDLE_NONE) {
2943 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2944 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2945 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2946
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002947 for (audio_io_handle_t output : outputs) {
2948 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002949 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002950 continue;
2951 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002952 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2953 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002954 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002955 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002956 }
2957 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002958 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002959 }
2960 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002961 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002962 }
2963 }
2964 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2965 output = outputOffloaded;
2966 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2967 output = outputDeepBuffer;
2968 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2969 output = outputPrimary;
2970 } else {
2971 output = outputs[0];
2972 }
2973 activeOnly = false;
2974 }
2975
2976 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002977 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002978 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2979 mMusicEffectOutput = output;
2980 }
2981
2982 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002983 return output;
2984}
2985
Eric Laurent36829f92017-04-07 19:04:42 -07002986audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2987{
2988 return selectOutputForMusicEffects();
2989}
2990
Eric Laurente0720872014-03-11 09:30:41 -07002991status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002992 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002993 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002994 int session,
2995 int id)
2996{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002997 if (session != AUDIO_SESSION_DEVICE) {
2998 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002999 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003000 index = mInputs.indexOfKey(io);
3001 if (index < 0) {
3002 ALOGW("registerEffect() unknown io %d", io);
3003 return INVALID_OPERATION;
3004 }
Eric Laurente552edb2014-03-10 17:42:56 -07003005 }
3006 }
François Gaffiec005e562018-11-06 15:04:49 +01003007 return mEffects.registerEffect(desc, io, session, id,
3008 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3009 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003010}
3011
Eric Laurentc241b0d2018-11-28 09:08:49 -08003012status_t AudioPolicyManager::unregisterEffect(int id)
3013{
3014 if (mEffects.getEffect(id) == nullptr) {
3015 return INVALID_OPERATION;
3016 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003017 if (mEffects.isEffectEnabled(id)) {
3018 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3019 setEffectEnabled(id, false);
3020 }
3021 return mEffects.unregisterEffect(id);
3022}
3023
3024status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3025{
3026 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3027 if (effect == nullptr) {
3028 return INVALID_OPERATION;
3029 }
3030
3031 status_t status = mEffects.setEffectEnabled(id, enabled);
3032 if (status == NO_ERROR) {
3033 mInputs.trackEffectEnabled(effect, enabled);
3034 }
3035 return status;
3036}
3037
Eric Laurent6c796322019-04-09 14:13:17 -07003038
3039status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3040{
3041 mEffects.moveEffects(ids, io);
3042 return NO_ERROR;
3043}
3044
Eric Laurentc75307b2015-03-17 15:29:32 -07003045bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3046{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003047 auto vs = toVolumeSource(stream, false);
3048 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003049}
3050
3051bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3052{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003053 auto vs = toVolumeSource(stream, false);
3054 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003055}
3056
Eric Laurente0720872014-03-11 09:30:41 -07003057bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003058{
3059 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003060 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003061 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003062 return true;
3063 }
3064 }
3065 return false;
3066}
3067
Eric Laurent275e8e92014-11-30 15:14:47 -08003068// Register a list of custom mixes with their attributes and format.
3069// When a mix is registered, corresponding input and output profiles are
3070// added to the remote submix hw module. The profile contains only the
3071// parameters (sampling rate, format...) specified by the mix.
3072// The corresponding input remote submix device is also connected.
3073//
3074// When a remote submix device is connected, the address is checked to select the
3075// appropriate profile and the corresponding input or output stream is opened.
3076//
3077// When capture starts, getInputForAttr() will:
3078// - 1 look for a mix matching the address passed in attribtutes tags if any
3079// - 2 if none found, getDeviceForInputSource() will:
3080// - 2.1 look for a mix matching the attributes source
3081// - 2.2 if none found, default to device selection by policy rules
3082// At this time, the corresponding output remote submix device is also connected
3083// and active playback use cases can be transferred to this mix if needed when reconnecting
3084// after AudioTracks are invalidated
3085//
3086// When playback starts, getOutputForAttr() will:
3087// - 1 look for a mix matching the address passed in attribtutes tags if any
3088// - 2 if none found, look for a mix matching the attributes usage
3089// - 3 if none found, default to device and output selection by policy rules.
3090
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003091status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003092{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003093 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3094 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003095 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003096 sp<HwModule> rSubmixModule;
3097 // examine each mix's route type
3098 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003099 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003100 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3101 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3102 ALOGE("Unsupported Policy Mix %zu of %zu: "
3103 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3104 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003105 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003106 break;
3107 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003108 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3109 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003110 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003111 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3112 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003113 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003114 rSubmixModule = mHwModules.getModuleFromName(
3115 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3116 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003117 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003118 i);
3119 res = INVALID_OPERATION;
3120 break;
3121 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003122 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003123
Eric Laurent97ac8712018-07-27 18:59:02 -07003124 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003125 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003126 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003127 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003128 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3129 } else {
3130 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3131 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003132 }
François Gaffie036e1e92015-03-19 10:16:24 +01003133
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003134 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003135 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003136 res = INVALID_OPERATION;
3137 break;
3138 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003139 audio_config_t outputConfig = mix.mFormat;
3140 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003141 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3142 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003143 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3144 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003145 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003146 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003147 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003148 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003149
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003150 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003151 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3152 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3153 ALOGE("Failed to set remote submix device available, type %u, address %s",
3154 mix.mDeviceType, address.string());
3155 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003156 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003157 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3158 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003159 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003160 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003161 i, mixes.size(), type, address.string());
3162
3163 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3164 mix.mDeviceType, mix.mDeviceAddress,
3165 String8(), AUDIO_FORMAT_DEFAULT);
3166 if (device == nullptr) {
3167 res = INVALID_OPERATION;
3168 break;
3169 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003170
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003171 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003172 // First try to find an already opened output supporting the device
3173 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003174 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003175
Eric Laurentc529cf62020-04-17 18:19:10 -07003176 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003177 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003178 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3179 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003180 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003181 } else {
3182 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003184 }
3185 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003186 // If no output found, try to find a direct output profile supporting the device
3187 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3188 sp<HwModule> module = mHwModules[i];
3189 for (size_t j = 0;
3190 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3191 j++) {
3192 sp<IOProfile> profile = module->getOutputProfiles()[j];
3193 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3194 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3195 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3196 address.string());
3197 res = INVALID_OPERATION;
3198 } else {
3199 foundOutput = true;
3200 }
3201 }
3202 }
3203 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003204 if (res != NO_ERROR) {
3205 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003206 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003207 res = INVALID_OPERATION;
3208 break;
3209 } else if (!foundOutput) {
3210 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003211 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003212 res = INVALID_OPERATION;
3213 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003214 } else {
3215 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003216 }
Eric Laurentc722f302014-12-10 11:21:49 -08003217 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003218 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003219 if (res != NO_ERROR) {
3220 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003221 } else if (checkOutputs) {
3222 checkForDeviceAndOutputChanges();
3223 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003224 }
3225 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003226}
3227
3228status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3229{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003230 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003231 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003232 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003233 sp<HwModule> rSubmixModule;
3234 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003235 for (const auto& mix : mixes) {
3236 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003237
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003238 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003239 rSubmixModule = mHwModules.getModuleFromName(
3240 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3241 if (rSubmixModule == 0) {
3242 res = INVALID_OPERATION;
3243 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003244 }
3245 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003246
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003247 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003248
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003249 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003250 res = INVALID_OPERATION;
3251 continue;
3252 }
3253
Kevin Rocard04ed0462019-05-02 17:53:24 -07003254 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3255 if (getDeviceConnectionState(device, address.string()) ==
3256 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3257 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3258 address.string(), "remote-submix",
3259 AUDIO_FORMAT_DEFAULT);
3260 if (res != OK) {
3261 ALOGE("Error making RemoteSubmix device unavailable for mix "
3262 "with type %d, address %s", device, address.string());
3263 }
3264 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265 }
jiabin5740f082019-08-19 15:08:30 -07003266 rSubmixModule->removeOutputProfile(address.c_str());
3267 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268
Kevin Rocard153f92d2018-12-18 18:33:28 -08003269 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003270 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003271 res = INVALID_OPERATION;
3272 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003273 } else {
3274 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003275 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003276 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003277 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003278 if (res == NO_ERROR && checkOutputs) {
3279 checkForDeviceAndOutputChanges();
3280 updateCallAndOutputRouting();
3281 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003282 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003283}
3284
Mikhail Naganov100f0122018-11-29 11:22:16 -08003285void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3286{
3287 size_t i = 0;
3288 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3289 for (const auto& fmt : mManualSurroundFormats) {
3290 if (i++ != 0) dst->append(", ");
3291 std::string sfmt;
3292 FormatConverter::toString(fmt, sfmt);
3293 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3294 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3295 }
3296}
3297
Eric Laurentc529cf62020-04-17 18:19:10 -07003298// Returns true if all devices types match the predicate and are supported by one HW module
3299bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003300 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003301 std::function<bool(audio_devices_t)> predicate,
3302 const char *context) {
3303 for (size_t i = 0; i < devices.size(); i++) {
3304 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003305 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003306 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003307 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003308 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003309 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003310 return false;
3311 }
3312 }
3313 return true;
3314}
3315
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003316status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003317 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003318 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003319 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3320 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003321 }
3322 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003323 if (res != NO_ERROR) {
3324 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3325 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003326 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003327
3328 checkForDeviceAndOutputChanges();
3329 updateCallAndOutputRouting();
3330
3331 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003332}
3333
3334status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3335 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003336 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3337 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003338 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003339 __FUNCTION__, uid);
3340 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003341 }
3342
Eric Laurentc529cf62020-04-17 18:19:10 -07003343 checkForDeviceAndOutputChanges();
3344 updateCallAndOutputRouting();
3345
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003346 return res;
3347}
3348
Eric Laurent2517af32020-11-25 15:31:27 +01003349
jiabin0a488932020-08-07 17:32:40 -07003350status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3351 device_role_t role,
3352 const AudioDeviceTypeAddrVector &devices) {
3353 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3354 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003355
Eric Laurentc529cf62020-04-17 18:19:10 -07003356 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003357 return BAD_VALUE;
3358 }
jiabin0a488932020-08-07 17:32:40 -07003359 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003360 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003361 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3362 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003363 return status;
3364 }
3365
3366 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003367
3368 bool forceVolumeReeval = false;
3369 // FIXME: workaround for truncated touch sounds
3370 // to be removed when the problem is handled by system UI
3371 uint32_t delayMs = 0;
3372 if (strategy == mCommunnicationStrategy) {
3373 forceVolumeReeval = true;
3374 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3375 updateInputRouting();
3376 }
3377 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003378
3379 return NO_ERROR;
3380}
3381
3382void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3383{
3384 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003385 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003386 // Only apply special touch sound delay once
3387 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003388 }
3389 for (size_t i = 0; i < mOutputs.size(); i++) {
3390 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3391 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3392 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3393 // As done in setDeviceConnectionState, we could also fix default device issue by
3394 // preventing the force re-routing in case of default dev that distinguishes on address.
3395 // Let's give back to engine full device choice decision however.
3396 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003397 // Only apply special touch sound delay once
3398 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003399 }
3400 if (forceVolumeReeval && !newDevices.isEmpty()) {
3401 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3402 }
3403 }
3404}
3405
Eric Laurent2517af32020-11-25 15:31:27 +01003406void AudioPolicyManager::updateInputRouting() {
3407 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303408 // Skip for hotword recording as the input device switch
3409 // is handled within sound trigger HAL
3410 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3411 continue;
3412 }
Eric Laurent2517af32020-11-25 15:31:27 +01003413 auto newDevice = getNewInputDevice(activeDesc);
3414 // Force new input selection if the new device can not be reached via current input
3415 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3416 setInputDevice(activeDesc->mIoHandle, newDevice);
3417 } else {
3418 closeInput(activeDesc->mIoHandle);
3419 }
3420 }
3421}
3422
jiabin0a488932020-08-07 17:32:40 -07003423status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3424 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003425{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003426 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003427
jiabin0a488932020-08-07 17:32:40 -07003428 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003429 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003430 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3431 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003432 return status;
3433 }
3434
3435 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003436
3437 bool forceVolumeReeval = false;
3438 // FIXME: workaround for truncated touch sounds
3439 // to be removed when the problem is handled by system UI
3440 uint32_t delayMs = 0;
3441 if (strategy == mCommunnicationStrategy) {
3442 forceVolumeReeval = true;
3443 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3444 updateInputRouting();
3445 }
3446 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003447
3448 return NO_ERROR;
3449}
3450
jiabin0a488932020-08-07 17:32:40 -07003451status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3452 device_role_t role,
3453 AudioDeviceTypeAddrVector &devices) {
3454 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003455}
3456
Jiabin Huang3b98d322020-09-03 17:54:16 +00003457status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3458 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3459 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3460 dumpAudioDeviceTypeAddrVector(devices).c_str());
3461
Mikhail Naganov55773032020-10-01 15:08:13 -07003462 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003463 return BAD_VALUE;
3464 }
3465 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3466 ALOGW_IF(status != NO_ERROR,
3467 "Engine could not set preferred devices %s for audio source %d role %d",
3468 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3469
3470 return status;
3471}
3472
3473status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3474 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3475 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3476 dumpAudioDeviceTypeAddrVector(devices).c_str());
3477
Mikhail Naganov55773032020-10-01 15:08:13 -07003478 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003479 return BAD_VALUE;
3480 }
3481 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3482 ALOGW_IF(status != NO_ERROR,
3483 "Engine could not add preferred devices %s for audio source %d role %d",
3484 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3485
Eric Laurent2517af32020-11-25 15:31:27 +01003486 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003487 return status;
3488}
3489
3490status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3491 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3492{
3493 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3494 dumpAudioDeviceTypeAddrVector(devices).c_str());
3495
Mikhail Naganov55773032020-10-01 15:08:13 -07003496 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003497 return BAD_VALUE;
3498 }
3499
3500 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3501 audioSource, role, devices);
3502 ALOGW_IF(status != NO_ERROR,
3503 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3504
Eric Laurent2517af32020-11-25 15:31:27 +01003505 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003506 return status;
3507}
3508
3509status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3510 device_role_t role) {
3511 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3512
3513 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3514 ALOGW_IF(status != NO_ERROR,
3515 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3516
Eric Laurent2517af32020-11-25 15:31:27 +01003517 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003518 return status;
3519}
3520
3521status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3522 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3523 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3524}
3525
Oscar Azucena90e77632019-11-27 17:12:28 -08003526status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003527 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003528 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003529 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3530 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003531 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003532 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3533 if (status != NO_ERROR) {
3534 ALOGE("%s() could not set device affinity for userId %d",
3535 __FUNCTION__, userId);
3536 return status;
3537 }
3538
3539 // reevaluate outputs for all devices
3540 checkForDeviceAndOutputChanges();
3541 updateCallAndOutputRouting();
3542
3543 return NO_ERROR;
3544}
3545
3546status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003547 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003548 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3549 if (status != NO_ERROR) {
3550 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3551 __FUNCTION__, userId);
3552 return status;
3553 }
3554
3555 // reevaluate outputs for all devices
3556 checkForDeviceAndOutputChanges();
3557 updateCallAndOutputRouting();
3558
3559 return NO_ERROR;
3560}
3561
Andy Hungc29d82b2018-10-05 12:23:17 -07003562void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003563{
Andy Hungc29d82b2018-10-05 12:23:17 -07003564 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3565 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003566 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003567 std::string stateLiteral;
3568 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003569 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003570 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3571 "communications", "media", "record", "dock", "system",
3572 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3573 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3574 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003575 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3576 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3577 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3578 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3579 dst->append(" (MANUAL: ");
3580 dumpManualSurroundFormats(dst);
3581 dst->append(")");
3582 }
3583 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003584 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003585 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3586 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003587 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003588 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003589
Andy Hungc29d82b2018-10-05 12:23:17 -07003590 mAvailableOutputDevices.dump(dst, String8("Available output"));
3591 mAvailableInputDevices.dump(dst, String8("Available input"));
3592 mHwModulesAll.dump(dst);
3593 mOutputs.dump(dst);
3594 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003595 mEffects.dump(dst);
3596 mAudioPatches.dump(dst);
3597 mPolicyMixes.dump(dst);
3598 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003599
Kevin Rocardb99cc752019-03-21 20:52:24 -07003600 dst->appendFormat(" AllowedCapturePolicies:\n");
3601 for (auto& policy : mAllowedCapturePolicies) {
3602 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3603 }
3604
François Gaffiec005e562018-11-06 15:04:49 +01003605 dst->appendFormat("\nPolicy Engine dump:\n");
3606 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003607}
3608
3609status_t AudioPolicyManager::dump(int fd)
3610{
3611 String8 result;
3612 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003613 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003614 return NO_ERROR;
3615}
3616
Kevin Rocardb99cc752019-03-21 20:52:24 -07003617status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3618{
3619 mAllowedCapturePolicies[uid] = capturePolicy;
3620 return NO_ERROR;
3621}
3622
Eric Laurente552edb2014-03-10 17:42:56 -07003623// This function checks for the parameters which can be offloaded.
3624// This can be enhanced depending on the capability of the DSP and policy
3625// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003626audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003627{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003628 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003629 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003630 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003631 offloadInfo.format,
3632 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3633 offloadInfo.has_video);
3634
Andy Hung2ddee192015-12-18 17:34:44 -08003635 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003636 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003637 }
3638
Eric Laurente552edb2014-03-10 17:42:56 -07003639 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003640 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003641 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3642 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003643 }
3644
3645 // Check if stream type is music, then only allow offload as of now.
3646 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3647 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003648 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3649 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 }
3651
3652 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003653 const bool allowOffloadWithVideo =
3654 property_get_bool("audio.offload.video", false /* default_value */);
3655 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003656 ALOGV("%s: has_video == true, returning false", __func__);
3657 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003658 }
3659
3660 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003661 const int min_duration_secs = property_get_int32(
3662 "audio.offload.min.duration.secs", -1 /* default_value */);
3663 if (min_duration_secs >= 0) {
3664 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003665 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3666 __func__, min_duration_secs);
3667 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003668 }
3669 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003670 ALOGV("%s: Offload denied by duration < default min(=%u)",
3671 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3672 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003673 }
3674
3675 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3676 // creating an offloaded track and tearing it down immediately after start when audioflinger
3677 // detects there is an active non offloadable effect.
3678 // FIXME: We should check the audio session here but we do not have it in this context.
3679 // This may prevent offloading in rare situations where effects are left active by apps
3680 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003681 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003682 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003683 }
3684
3685 // See if there is a profile to support this.
3686 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003687 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003688 offloadInfo.sample_rate,
3689 offloadInfo.format,
3690 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003691 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3692 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003693 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3694 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3695 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003696 if (profile == nullptr) {
3697 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3698 }
3699 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3700 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3701 }
3702 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003703}
3704
Michael Chana94fbb22018-04-24 14:31:19 +10003705bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3706 const audio_attributes_t& attributes) {
3707 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003708 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003709 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003710 config.sample_rate,
3711 config.format,
3712 config.channel_mask,
3713 output_flags,
3714 true /* directOnly */);
3715 ALOGV("%s() profile %sfound with name: %s, "
3716 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3717 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003718 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003719 config.sample_rate, config.format, config.channel_mask, output_flags);
3720 return (profile != 0);
3721}
3722
Eric Laurent6a94d692014-05-20 11:18:06 -07003723status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3724 audio_port_type_t type,
3725 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003726 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003727 unsigned int *generation)
3728{
jiabin19cdba52020-11-24 11:28:58 -08003729 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3730 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003731 return BAD_VALUE;
3732 }
3733 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003734 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003735 *num_ports = 0;
3736 }
3737
3738 size_t portsWritten = 0;
3739 size_t portsMax = *num_ports;
3740 *num_ports = 0;
3741 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003742 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3743 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003744 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003745 for (const auto& dev : mAvailableOutputDevices) {
3746 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003747 continue;
3748 }
3749 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003750 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003751 }
3752 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003754 }
3755 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003756 for (const auto& dev : mAvailableInputDevices) {
3757 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003758 continue;
3759 }
3760 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003761 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003762 }
3763 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003764 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 }
3766 }
3767 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3768 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3769 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3770 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3771 }
3772 *num_ports += mInputs.size();
3773 }
3774 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003775 size_t numOutputs = 0;
3776 for (size_t i = 0; i < mOutputs.size(); i++) {
3777 if (!mOutputs[i]->isDuplicated()) {
3778 numOutputs++;
3779 if (portsWritten < portsMax) {
3780 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3781 }
3782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003783 }
Eric Laurent84c70242014-06-23 08:46:27 -07003784 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003785 }
3786 }
3787 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003788 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003789 return NO_ERROR;
3790}
3791
jiabin19cdba52020-11-24 11:28:58 -08003792status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003793{
Eric Laurent99fcae42018-05-17 16:59:18 -07003794 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3795 return BAD_VALUE;
3796 }
3797 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3798 if (dev != 0) {
3799 dev->toAudioPort(port);
3800 return NO_ERROR;
3801 }
3802 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3803 if (dev != 0) {
3804 dev->toAudioPort(port);
3805 return NO_ERROR;
3806 }
3807 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3808 if (out != 0) {
3809 out->toAudioPort(port);
3810 return NO_ERROR;
3811 }
3812 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3813 if (in != 0) {
3814 in->toAudioPort(port);
3815 return NO_ERROR;
3816 }
3817 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003818}
3819
François Gaffieafd4cea2019-11-18 15:50:22 +01003820status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3821 audio_patch_handle_t *handle,
3822 uid_t uid, uint32_t delayMs,
3823 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003824{
François Gaffieafd4cea2019-11-18 15:50:22 +01003825 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003826 if (handle == NULL || patch == NULL) {
3827 return BAD_VALUE;
3828 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003829 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003830
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003831 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003832 return BAD_VALUE;
3833 }
3834 // only one source per audio patch supported for now
3835 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 return INVALID_OPERATION;
3837 }
Eric Laurent874c42872014-08-08 15:13:39 -07003838
3839 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003840 return INVALID_OPERATION;
3841 }
Eric Laurent874c42872014-08-08 15:13:39 -07003842 for (size_t i = 0; i < patch->num_sinks; i++) {
3843 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3844 return INVALID_OPERATION;
3845 }
3846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003847
3848 sp<AudioPatch> patchDesc;
3849 ssize_t index = mAudioPatches.indexOfKey(*handle);
3850
François Gaffieafd4cea2019-11-18 15:50:22 +01003851 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3852 patch->sources[0].role,
3853 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003854#if LOG_NDEBUG == 0
3855 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003856 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3857 patch->sinks[i].role,
3858 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003859 }
3860#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003861
3862 if (index >= 0) {
3863 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003864 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3865 __func__, mUidCached, patchDesc->getUid(), uid);
3866 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003867 return INVALID_OPERATION;
3868 }
3869 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003870 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003871 }
3872
3873 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003874 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003875 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003876 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003877 return BAD_VALUE;
3878 }
Eric Laurent84c70242014-06-23 08:46:27 -07003879 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3880 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003881 if (patchDesc != 0) {
3882 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003883 ALOGV("%s source id differs for patch current id %d new id %d",
3884 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003885 return BAD_VALUE;
3886 }
3887 }
Eric Laurent874c42872014-08-08 15:13:39 -07003888 DeviceVector devices;
3889 for (size_t i = 0; i < patch->num_sinks; i++) {
3890 // Only support mix to devices connection
3891 // TODO add support for mix to mix connection
3892 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003893 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003894 return INVALID_OPERATION;
3895 }
3896 sp<DeviceDescriptor> devDesc =
3897 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3898 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003899 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003900 return BAD_VALUE;
3901 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003902
François Gaffie11d30102018-11-02 16:09:09 +01003903 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003904 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003905 NULL, // updatedSamplingRate
3906 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003907 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003908 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003909 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003910 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003911 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003912 return INVALID_OPERATION;
3913 }
3914 devices.add(devDesc);
3915 }
3916 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003917 return INVALID_OPERATION;
3918 }
Eric Laurent874c42872014-08-08 15:13:39 -07003919
Eric Laurent6a94d692014-05-20 11:18:06 -07003920 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003921 ALOGV("%s setting device %s on output %d",
3922 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003923 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 index = mAudioPatches.indexOfKey(*handle);
3925 if (index >= 0) {
3926 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003927 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003928 }
3929 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003930 patchDesc->setUid(uid);
3931 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003932 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003933 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003934 return INVALID_OPERATION;
3935 }
3936 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3937 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3938 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003939 // only one sink supported when connecting an input device to a mix
3940 if (patch->num_sinks > 1) {
3941 return INVALID_OPERATION;
3942 }
François Gaffie53615e22015-03-19 09:24:12 +01003943 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 if (inputDesc == NULL) {
3945 return BAD_VALUE;
3946 }
3947 if (patchDesc != 0) {
3948 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3949 return BAD_VALUE;
3950 }
3951 }
François Gaffie11d30102018-11-02 16:09:09 +01003952 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003953 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003954 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003955 return BAD_VALUE;
3956 }
3957
François Gaffie11d30102018-11-02 16:09:09 +01003958 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003959 patch->sinks[0].sample_rate,
3960 NULL, /*updatedSampleRate*/
3961 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003962 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003963 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003964 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003965 // FIXME for the parameter type,
3966 // and the NONE
3967 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003968 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003969 return INVALID_OPERATION;
3970 }
3971 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003972 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003973 device->toString().c_str(), inputDesc->mIoHandle);
3974 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003975 index = mAudioPatches.indexOfKey(*handle);
3976 if (index >= 0) {
3977 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003978 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003979 }
3980 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003981 patchDesc->setUid(uid);
3982 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003983 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003984 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 return INVALID_OPERATION;
3986 }
3987 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3988 // device to device connection
3989 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003990 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 return BAD_VALUE;
3992 }
3993 }
François Gaffie11d30102018-11-02 16:09:09 +01003994 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003995 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003996 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003997 return BAD_VALUE;
3998 }
Eric Laurent874c42872014-08-08 15:13:39 -07003999
Eric Laurent6a94d692014-05-20 11:18:06 -07004000 //update source and sink with our own data as the data passed in the patch may
4001 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004002 PatchBuilder patchBuilder;
4003 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004004
4005 // if first sink is to MSD, establish single MSD patch
4006 if (getMsdAudioOutDevices().contains(
4007 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4008 ALOGV("%s patching to MSD", __FUNCTION__);
4009 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4010 goto installPatch;
4011 }
4012
François Gaffieafd4cea2019-11-18 15:50:22 +01004013 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4014 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004015
Eric Laurent874c42872014-08-08 15:13:39 -07004016 for (size_t i = 0; i < patch->num_sinks; i++) {
4017 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004018 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004019 return INVALID_OPERATION;
4020 }
François Gaffie11d30102018-11-02 16:09:09 +01004021 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004022 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004023 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004024 return BAD_VALUE;
4025 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004026 audio_port_config sinkPortConfig = {};
4027 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4028 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004029
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004030 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4031 // volume management purpose (tracking activity)
4032 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4033 // in config XML to reach the sink so that is can be declared as available.
4034 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4035 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4036 if (sourceDesc != nullptr) {
4037 // take care of dynamic routing for SwOutput selection,
4038 audio_attributes_t attributes = sourceDesc->attributes();
4039 audio_stream_type_t stream = sourceDesc->stream();
4040 audio_attributes_t resultAttr;
4041 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4042 config.sample_rate = sourceDesc->config().sample_rate;
4043 config.channel_mask = sourceDesc->config().channel_mask;
4044 config.format = sourceDesc->config().format;
4045 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4046 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4047 bool isRequestedDeviceForExclusiveUse = false;
4048 output_type_t outputType;
4049 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4050 &stream, sourceDesc->uid(), &config, &flags,
4051 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4052 nullptr, &outputType);
4053 if (output == AUDIO_IO_HANDLE_NONE) {
4054 ALOGV("%s no output for device %s",
4055 __FUNCTION__, sinkDevice->toString().c_str());
4056 return INVALID_OPERATION;
4057 }
4058 outputDesc = mOutputs.valueFor(output);
4059 if (outputDesc->isDuplicated()) {
4060 ALOGE("%s output is duplicated", __func__);
4061 return INVALID_OPERATION;
4062 }
4063 sourceDesc->setSwOutput(outputDesc);
4064 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004065 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004066 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004067 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004068 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004069 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4070 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004071 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4072 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004073 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4074 (sourceDesc != nullptr &&
4075 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004076 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004077 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004078 return INVALID_OPERATION;
4079 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004080 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004081 SortedVector<audio_io_handle_t> outputs =
4082 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4083 // if the sink device is reachable via an opened output stream, request to
4084 // go via this output stream by adding a second source to the patch
4085 // description
4086 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004087 if (output != AUDIO_IO_HANDLE_NONE) {
4088 outputDesc = mOutputs.valueFor(output);
4089 if (outputDesc->isDuplicated()) {
4090 ALOGV("%s output for device %s is duplicated",
4091 __FUNCTION__, sinkDevice->toString().c_str());
4092 return INVALID_OPERATION;
4093 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004094 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004095 }
4096 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004097 audio_port_config srcMixPortConfig = {};
4098 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004099 // for volume control, we may need a valid stream
4100 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4101 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4102 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004103 }
Eric Laurent83b88082014-06-20 18:31:16 -07004104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 }
4106 // TODO: check from routing capabilities in config file and other conflicting patches
4107
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004108installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004109 status_t status = installPatch(
4110 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004111 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004112 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004113 return INVALID_OPERATION;
4114 }
4115 } else {
4116 return BAD_VALUE;
4117 }
4118 } else {
4119 return BAD_VALUE;
4120 }
4121 return NO_ERROR;
4122}
4123
4124status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4125 uid_t uid)
4126{
4127 ALOGV("releaseAudioPatch() patch %d", handle);
4128
4129 ssize_t index = mAudioPatches.indexOfKey(handle);
4130
4131 if (index < 0) {
4132 return BAD_VALUE;
4133 }
4134 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004135 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4136 __func__, mUidCached, patchDesc->getUid(), uid);
4137 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004138 return INVALID_OPERATION;
4139 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004140 return releaseAudioPatchInternal(handle);
4141}
Eric Laurent6a94d692014-05-20 11:18:06 -07004142
François Gaffieafd4cea2019-11-18 15:50:22 +01004143status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4144 uint32_t delayMs)
4145{
4146 ALOGV("%s patch %d", __func__, handle);
4147 if (mAudioPatches.indexOfKey(handle) < 0) {
4148 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4149 return BAD_VALUE;
4150 }
4151 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004152 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004153 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004155 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004156 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004157 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004158 return BAD_VALUE;
4159 }
4160
François Gaffie11d30102018-11-02 16:09:09 +01004161 setOutputDevices(outputDesc,
4162 getNewOutputDevices(outputDesc, true /*fromCache*/),
4163 true,
4164 0,
4165 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4167 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004168 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004169 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004170 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004171 return BAD_VALUE;
4172 }
4173 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004174 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 true,
4176 NULL);
4177 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004178 status_t status =
4179 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4180 ALOGV("%s patch panel returned %d patchHandle %d",
4181 __func__, status, patchDesc->getAfHandle());
4182 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004183 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004184 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004185 // SW Bridge
4186 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4187 sp<SwAudioOutputDescriptor> outputDesc =
4188 mOutputs.getOutputFromId(patch->sources[1].id);
4189 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004190 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4191 // releaseOutput has already called closeOuput in case of direct output
4192 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004193 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004194 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4195 // force SwOutput patch removal as AF counter part patch has already gone.
4196 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4197 removeAudioPatch(outputDesc->getPatchHandle());
4198 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004199 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4200 setOutputDevices(outputDesc,
4201 getNewOutputDevices(outputDesc, true /*fromCache*/),
4202 true, /*force*/
4203 0,
4204 NULL);
4205 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004206 } else {
4207 return BAD_VALUE;
4208 }
4209 } else {
4210 return BAD_VALUE;
4211 }
4212 return NO_ERROR;
4213}
4214
4215status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4216 struct audio_patch *patches,
4217 unsigned int *generation)
4218{
François Gaffie53615e22015-03-19 09:24:12 +01004219 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 return BAD_VALUE;
4221 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004222 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004223 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004224}
4225
Eric Laurente1715a42014-05-20 11:30:42 -07004226status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004227{
Eric Laurente1715a42014-05-20 11:30:42 -07004228 ALOGV("setAudioPortConfig()");
4229
4230 if (config == NULL) {
4231 return BAD_VALUE;
4232 }
4233 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4234 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004235 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4236 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004237 }
4238
Eric Laurenta121f902014-06-03 13:32:54 -07004239 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004240 if (config->type == AUDIO_PORT_TYPE_MIX) {
4241 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004243 if (outputDesc == NULL) {
4244 return BAD_VALUE;
4245 }
Eric Laurent84c70242014-06-23 08:46:27 -07004246 ALOG_ASSERT(!outputDesc->isDuplicated(),
4247 "setAudioPortConfig() called on duplicated output %d",
4248 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004249 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004250 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004251 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004252 if (inputDesc == NULL) {
4253 return BAD_VALUE;
4254 }
Eric Laurenta121f902014-06-03 13:32:54 -07004255 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004256 } else {
4257 return BAD_VALUE;
4258 }
4259 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4260 sp<DeviceDescriptor> deviceDesc;
4261 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4262 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4263 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4264 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4265 } else {
4266 return BAD_VALUE;
4267 }
4268 if (deviceDesc == NULL) {
4269 return BAD_VALUE;
4270 }
Eric Laurenta121f902014-06-03 13:32:54 -07004271 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004272 } else {
4273 return BAD_VALUE;
4274 }
4275
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004276 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004277 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4278 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004279 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004280 audioPortConfig->toAudioPortConfig(&newConfig, config);
4281 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004282 }
Eric Laurenta121f902014-06-03 13:32:54 -07004283 if (status != NO_ERROR) {
4284 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004285 }
Eric Laurente1715a42014-05-20 11:30:42 -07004286
4287 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004288}
4289
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004290void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4291{
Eric Laurentd60560a2015-04-10 11:31:20 -07004292 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004293 clearAudioPatches(uid);
4294 clearSessionRoutes(uid);
4295}
4296
Eric Laurent6a94d692014-05-20 11:18:06 -07004297void AudioPolicyManager::clearAudioPatches(uid_t uid)
4298{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004299 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004300 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004301 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004302 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 }
4304 }
4305}
4306
François Gaffiec005e562018-11-06 15:04:49 +01004307void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004308{
François Gaffiec005e562018-11-06 15:04:49 +01004309 // Take the first attributes following the product strategy as it is used to retrieve the routed
4310 // device. All attributes wihin a strategy follows the same "routing strategy"
4311 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4312 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004313 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004314 for (size_t j = 0; j < mOutputs.size(); j++) {
4315 if (mOutputs.keyAt(j) == ouptutToSkip) {
4316 continue;
4317 }
4318 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004319 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004320 continue;
4321 }
4322 // If the default device for this strategy is on another output mix,
4323 // invalidate all tracks in this strategy to force re connection.
4324 // Otherwise select new device on the output mix.
4325 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004326 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4327 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004328 }
4329 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004330 setOutputDevices(
4331 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004332 }
4333 }
4334}
4335
4336void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4337{
4338 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004339 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004340 for (size_t i = 0; i < mOutputs.size(); i++) {
4341 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004342 for (const auto& client : outputDesc->getClientIterable()) {
4343 if (client->hasPreferredDevice() && client->uid() == uid) {
4344 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004345 auto clientStrategy = client->strategy();
4346 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4347 end(affectedStrategies)) {
4348 continue;
4349 }
4350 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004351 }
4352 }
4353 }
4354 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004355 for (const auto& strategy : affectedStrategies) {
4356 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004357 }
4358
4359 // remove input routes associated with this uid
4360 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004361 for (size_t i = 0; i < mInputs.size(); i++) {
4362 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004363 for (const auto& client : inputDesc->getClientIterable()) {
4364 if (client->hasPreferredDevice() && client->uid() == uid) {
4365 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4366 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004367 }
4368 }
4369 }
4370 // reroute inputs if necessary
4371 SortedVector<audio_io_handle_t> inputsToClose;
4372 for (size_t i = 0; i < mInputs.size(); i++) {
4373 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004374 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004375 inputsToClose.add(inputDesc->mIoHandle);
4376 }
4377 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004378 for (const auto& input : inputsToClose) {
4379 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004380 }
4381}
4382
Eric Laurentd60560a2015-04-10 11:31:20 -07004383void AudioPolicyManager::clearAudioSources(uid_t uid)
4384{
4385 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004386 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4387 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004388 stopAudioSource(mAudioSources.keyAt(i));
4389 }
4390 }
4391}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004392
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004393status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4394 audio_io_handle_t *ioHandle,
4395 audio_devices_t *device)
4396{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004397 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4398 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004399 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004400 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004401
François Gaffiedf372692015-03-19 10:43:27 +01004402 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004403}
4404
Eric Laurentd60560a2015-04-10 11:31:20 -07004405status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004406 const audio_attributes_t *attributes,
4407 audio_port_handle_t *portId,
4408 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004409{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004410 ALOGV("%s", __FUNCTION__);
4411 *portId = AUDIO_PORT_HANDLE_NONE;
4412
4413 if (source == NULL || attributes == NULL || portId == NULL) {
4414 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4415 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004416 return BAD_VALUE;
4417 }
4418
Eric Laurentd60560a2015-04-10 11:31:20 -07004419 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4420 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004421 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4422 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004423 return INVALID_OPERATION;
4424 }
4425
François Gaffie11d30102018-11-02 16:09:09 +01004426 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004427 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004428 String8(source->ext.device.address),
4429 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004430 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004431 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004432 return BAD_VALUE;
4433 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004434
jiabin4ef93452019-09-10 14:29:54 -07004435 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004436
François Gaffieaaac0fd2018-11-22 17:56:39 +01004437 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004439 mEngine->getStreamTypeForAttributes(*attributes),
4440 mEngine->getProductStrategyForAttributes(*attributes),
4441 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004442
4443 status_t status = connectAudioSource(sourceDesc);
4444 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004445 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004446 }
4447 return status;
4448}
4449
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004450status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004451{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004452 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004453
4454 // make sure we only have one patch per source.
4455 disconnectAudioSource(sourceDesc);
4456
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004457 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004458 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4459 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4460 sourceDesc->srcDevice()->type(),
4461 String8(sourceDesc->srcDevice()->address().c_str()),
4462 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004463 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004464 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004465 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004466 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004467 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4468 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4469 return INVALID_OPERATION;
4470 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004471 PatchBuilder patchBuilder;
4472 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4473 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4474 status_t status =
4475 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4476 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4477 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4478 return INVALID_OPERATION;
4479 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004480 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4482 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4483 if (swOutput != 0) {
4484 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004485 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004487 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004488 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004489 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004490 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004491 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004493 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004494 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004495 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004496 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4497 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004498 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004499 if (delayMs != 0) {
4500 usleep(delayMs * 1000);
4501 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 } else {
4503 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4504 if (hwOutputDesc != 0) {
4505 // create Hwoutput and add to mHwOutputs
4506 } else {
4507 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4508 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004509 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004510 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004511
4512FailureSourceActive:
4513 swOutput->stop();
4514 releaseOutput(sourceDesc->portId());
4515FailureSourceAdded:
4516 sourceDesc->setSwOutput(nullptr);
4517FailureReleasePatch:
4518 releaseAudioPatchInternal(handle);
4519 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004520}
4521
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004522status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004523{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004524 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4525 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004526 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004527 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004528 return BAD_VALUE;
4529 }
4530 status_t status = disconnectAudioSource(sourceDesc);
4531
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004532 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004533 return status;
4534}
4535
Andy Hung2ddee192015-12-18 17:34:44 -08004536status_t AudioPolicyManager::setMasterMono(bool mono)
4537{
4538 if (mMasterMono == mono) {
4539 return NO_ERROR;
4540 }
4541 mMasterMono = mono;
4542 // if enabling mono we close all offloaded devices, which will invalidate the
4543 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4544 // for recreating the new AudioTrack as non-offloaded PCM.
4545 //
4546 // If disabling mono, we leave all tracks as is: we don't know which clients
4547 // and tracks are able to be recreated as offloaded. The next "song" should
4548 // play back offloaded.
4549 if (mMasterMono) {
4550 Vector<audio_io_handle_t> offloaded;
4551 for (size_t i = 0; i < mOutputs.size(); ++i) {
4552 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4553 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4554 offloaded.push(desc->mIoHandle);
4555 }
4556 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004557 for (const auto& handle : offloaded) {
4558 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004559 }
4560 }
4561 // update master mono for all remaining outputs
4562 for (size_t i = 0; i < mOutputs.size(); ++i) {
4563 updateMono(mOutputs.keyAt(i));
4564 }
4565 return NO_ERROR;
4566}
4567
4568status_t AudioPolicyManager::getMasterMono(bool *mono)
4569{
4570 *mono = mMasterMono;
4571 return NO_ERROR;
4572}
4573
Eric Laurentac9cef52017-06-09 15:46:26 -07004574float AudioPolicyManager::getStreamVolumeDB(
4575 audio_stream_type_t stream, int index, audio_devices_t device)
4576{
jiabin9a3361e2019-10-01 09:38:30 -07004577 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004578}
4579
jiabin81772902018-04-02 17:52:27 -07004580status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4581 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004582 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004583{
Kriti Dang6537def2021-03-02 13:46:59 +01004584 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4585 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004586 return BAD_VALUE;
4587 }
Kriti Dang6537def2021-03-02 13:46:59 +01004588 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4589 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004590
4591 size_t formatsWritten = 0;
4592 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004593
Kriti Dang6537def2021-03-02 13:46:59 +01004594 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004595 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4596 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004597 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004598 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004599 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004600 bool formatEnabled = true;
4601 switch (forceUse) {
4602 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004603 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004604 break;
4605 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4606 formatEnabled = false;
4607 break;
4608 default: // AUTO or ALWAYS => true
4609 break;
jiabin81772902018-04-02 17:52:27 -07004610 }
4611 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4612 }
jiabin81772902018-04-02 17:52:27 -07004613 }
4614 return NO_ERROR;
4615}
4616
Kriti Dang6537def2021-03-02 13:46:59 +01004617status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4618 audio_format_t *surroundFormats) {
4619 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4620 return BAD_VALUE;
4621 }
4622 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4623 __func__, *numSurroundFormats, surroundFormats);
4624
4625 size_t formatsWritten = 0;
4626 size_t formatsMax = *numSurroundFormats;
4627 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4628
4629 // Return formats from all device profiles that have already been resolved by
4630 // checkOutputsForDevice().
4631 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4632 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4633 audio_devices_t deviceType = device->type();
4634 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4635 // returns formats reported by HDMI devices.
4636 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4637 continue;
4638 }
4639 // Formats reported by sink devices
4640 std::unordered_set<audio_format_t> formatset;
4641 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4642 formatset.insert(it->second.begin(), it->second.end());
4643 }
4644
4645 // Formats hard-coded in the in policy configuration file (if any).
4646 FormatVector encodedFormats = device->encodedFormats();
4647 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4648 // Filter the formats which are supported by the vendor hardware.
4649 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4650 if (mConfig.getSurroundFormats().count(*it) != 0) {
4651 formats.insert(*it);
4652 } else {
4653 for (const auto& pair : mConfig.getSurroundFormats()) {
4654 if (pair.second.count(*it) != 0) {
4655 formats.insert(pair.first);
4656 break;
4657 }
4658 }
4659 }
4660 }
4661 }
4662 *numSurroundFormats = formats.size();
4663 for (const auto& format: formats) {
4664 if (formatsWritten < formatsMax) {
4665 surroundFormats[formatsWritten++] = format;
4666 }
4667 }
4668 return NO_ERROR;
4669}
4670
jiabin81772902018-04-02 17:52:27 -07004671status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4672{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004673 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004674 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4675 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004676 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004677 return BAD_VALUE;
4678 }
4679
Mikhail Naganov100f0122018-11-29 11:22:16 -08004680 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4681 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004682 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004683 return INVALID_OPERATION;
4684 }
4685
Mikhail Naganov100f0122018-11-29 11:22:16 -08004686 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004687 return NO_ERROR;
4688 }
4689
Mikhail Naganov100f0122018-11-29 11:22:16 -08004690 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004691 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004692 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004693 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004694 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004695 }
4696 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004697 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004698 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004699 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004700 }
4701 }
4702
4703 sp<SwAudioOutputDescriptor> outputDesc;
4704 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004705 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4706 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004707 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4708 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004709 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004710 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004711 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4712 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4713 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004714 name.c_str(),
4715 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004716 if (status != NO_ERROR) {
4717 continue;
4718 }
4719 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4720 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4721 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004722 name.c_str(),
4723 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004724 profileUpdated |= (status == NO_ERROR);
4725 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004726 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004727 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004728 AUDIO_DEVICE_IN_HDMI);
4729 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4730 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004731 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004732 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004733 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4734 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4735 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004736 name.c_str(),
4737 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004738 if (status != NO_ERROR) {
4739 continue;
4740 }
4741 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4742 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4743 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004744 name.c_str(),
4745 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004746 profileUpdated |= (status == NO_ERROR);
4747 }
4748
jiabin81772902018-04-02 17:52:27 -07004749 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004750 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004751 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004752 }
4753
4754 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4755}
4756
Eric Laurent5ada82e2019-08-29 17:53:54 -07004757void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004758{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004759 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004760 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004761 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004762 }
4763}
4764
jiabin6012f912018-11-02 17:06:30 -07004765bool AudioPolicyManager::isHapticPlaybackSupported()
4766{
4767 for (const auto& hwModule : mHwModules) {
4768 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4769 for (const auto &outProfile : outputProfiles) {
4770 struct audio_port audioPort;
4771 outProfile->toAudioPort(&audioPort);
4772 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4773 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4774 return true;
4775 }
4776 }
4777 }
4778 }
4779 return false;
4780}
4781
Eric Laurent8340e672019-11-06 11:01:08 -08004782bool AudioPolicyManager::isCallScreenModeSupported()
4783{
4784 return getConfig().isCallScreenModeSupported();
4785}
4786
4787
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004788status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004789{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004790 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004791 if (!sourceDesc->isConnected()) {
4792 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4793 return NO_ERROR;
4794 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004795 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4796 if (swOutput != 0) {
4797 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004798 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004799 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004800 }
jiabinbce0c1d2020-10-05 11:20:18 -07004801 if (releaseOutput(sourceDesc->portId())) {
4802 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4803 // no need to release audio patch here but just return NO_ERROR.
4804 return NO_ERROR;
4805 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004806 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004807 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004808 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004809 // close Hwoutput and remove from mHwOutputs
4810 } else {
4811 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4812 }
4813 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004814 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4815 sourceDesc->disconnect();
4816 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004817}
4818
François Gaffiec005e562018-11-06 15:04:49 +01004819sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4820 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004821{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004822 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004823 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004824 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004825 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004826 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4827 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004828 source = sourceDesc;
4829 break;
4830 }
4831 }
4832 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004833}
4834
Eric Laurente552edb2014-03-10 17:42:56 -07004835// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004836// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004837// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004838uint32_t AudioPolicyManager::nextAudioPortGeneration()
4839{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004840 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004841}
4842
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004843static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004844 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4845 !audioPolicyXmlConfigFile.empty()) {
4846 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4847 if (ret == NO_ERROR) {
4848 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004849 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004850 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004851 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004852 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004853}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004854
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004855AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4856 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004857 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004858 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004859 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004860 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004861 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004862 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004863 mAudioPortGeneration(1),
4864 mBeaconMuteRefCount(0),
4865 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004866 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004867 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004868 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004869 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004870{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004871}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004872
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004873AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4874 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4875{
4876 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004877}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004878
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004879void AudioPolicyManager::loadConfig() {
4880 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004881 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004882 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004883 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004884}
4885
4886status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004887 {
4888 auto engLib = EngineLibrary::load(
4889 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4890 if (!engLib) {
4891 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4892 return NO_INIT;
4893 }
4894 mEngine = engLib->createEngine();
4895 if (mEngine == nullptr) {
4896 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4897 return NO_INIT;
4898 }
François Gaffie2110e042015-03-24 08:41:51 +01004899 }
4900 mEngine->setObserver(this);
4901 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004902 if (status != NO_ERROR) {
4903 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4904 return status;
4905 }
François Gaffie2110e042015-03-24 08:41:51 +01004906
Eric Laurent1d69c872021-01-11 18:53:01 +01004907 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4908 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4909
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004910 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004911 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004912 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004913
Eric Laurent3a4311c2014-03-17 12:00:47 -07004914 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004915 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4916 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4917 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004918 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004919 }
jiabin9ff780e2018-03-19 18:19:52 -07004920 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004921 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004922 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004923 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004924 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004925 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004926 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004927 }
4928 }
4929 }
Eric Laurente552edb2014-03-10 17:42:56 -07004930
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004931 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004932
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004933 // Silence ALOGV statements
4934 property_set("log.tag." LOG_TAG, "D");
4935
Eric Laurente552edb2014-03-10 17:42:56 -07004936 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004937 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004938}
4939
Eric Laurente0720872014-03-11 09:30:41 -07004940AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004941{
Eric Laurente552edb2014-03-10 17:42:56 -07004942 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004943 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004944 }
4945 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004946 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004947 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004948 mAvailableOutputDevices.clear();
4949 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004950 mOutputs.clear();
4951 mInputs.clear();
4952 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004953 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004954 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004955}
4956
Eric Laurente0720872014-03-11 09:30:41 -07004957status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004958{
Eric Laurent87ffa392015-05-22 10:32:38 -07004959 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004960}
4961
Eric Laurente552edb2014-03-10 17:42:56 -07004962// ---
4963
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004964void AudioPolicyManager::onNewAudioModulesAvailable()
4965{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004966 DeviceVector newDevices;
4967 onNewAudioModulesAvailableInt(&newDevices);
4968 if (!newDevices.empty()) {
4969 nextAudioPortGeneration();
4970 mpClientInterface->onAudioPortListUpdate();
4971 }
4972}
4973
4974void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4975{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004976 for (const auto& hwModule : mHwModulesAll) {
4977 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4978 continue;
4979 }
4980 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4981 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4982 ALOGW("could not open HW module %s", hwModule->getName());
4983 continue;
4984 }
4985 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10004986 // open all output streams needed to access attached devices.
4987 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004988 // This also validates mAvailableOutputDevices list
4989 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4990 if (!outProfile->canOpenNewIo()) {
4991 ALOGE("Invalid Output profile max open count %u for profile %s",
4992 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4993 continue;
4994 }
4995 if (!outProfile->hasSupportedDevices()) {
4996 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4997 continue;
4998 }
4999 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5000 mTtsOutputAvailable = true;
5001 }
5002
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005003 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5004 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5005 sp<DeviceDescriptor> supportedDevice = 0;
5006 if (supportedDevices.contains(mDefaultOutputDevice)) {
5007 supportedDevice = mDefaultOutputDevice;
5008 } else {
5009 // choose first device present in profile's SupportedDevices also part of
5010 // mAvailableOutputDevices.
5011 if (availProfileDevices.isEmpty()) {
5012 continue;
5013 }
5014 supportedDevice = availProfileDevices.itemAt(0);
5015 }
5016 if (!mOutputDevicesAll.contains(supportedDevice)) {
5017 continue;
5018 }
5019 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5020 mpClientInterface);
5021 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5022 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
5023 AUDIO_STREAM_DEFAULT,
5024 AUDIO_OUTPUT_FLAG_NONE, &output);
5025 if (status != NO_ERROR) {
5026 ALOGW("Cannot open output stream for devices %s on hw module %s",
5027 supportedDevice->toString().c_str(), hwModule->getName());
5028 continue;
5029 }
5030 for (const auto &device : availProfileDevices) {
5031 // give a valid ID to an attached device once confirmed it is reachable
5032 if (!device->isAttached()) {
5033 device->attach(hwModule);
5034 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005035 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005036 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005037 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5038 }
5039 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005040 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005041 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5042 mPrimaryOutput = outputDesc;
5043 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005044 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5045 outputDesc->close();
5046 } else {
5047 addOutput(output, outputDesc);
5048 setOutputDevices(outputDesc,
5049 DeviceVector(supportedDevice),
5050 true,
5051 0,
5052 NULL);
5053 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005054 }
5055 // open input streams needed to access attached devices to validate
5056 // mAvailableInputDevices list
5057 for (const auto& inProfile : hwModule->getInputProfiles()) {
5058 if (!inProfile->canOpenNewIo()) {
5059 ALOGE("Invalid Input profile max open count %u for profile %s",
5060 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5061 continue;
5062 }
5063 if (!inProfile->hasSupportedDevices()) {
5064 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5065 continue;
5066 }
5067 // chose first device present in profile's SupportedDevices also part of
5068 // available input devices
5069 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5070 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5071 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005072 ALOGV("%s: Input device list is empty! for profile %s",
5073 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005074 continue;
5075 }
5076 sp<AudioInputDescriptor> inputDesc =
5077 new AudioInputDescriptor(inProfile, mpClientInterface);
5078
5079 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5080 status_t status = inputDesc->open(nullptr,
5081 availProfileDevices.itemAt(0),
5082 AUDIO_SOURCE_MIC,
5083 AUDIO_INPUT_FLAG_NONE,
5084 &input);
5085 if (status != NO_ERROR) {
5086 ALOGW("Cannot open input stream for device %s on hw module %s",
5087 availProfileDevices.toString().c_str(),
5088 hwModule->getName());
5089 continue;
5090 }
5091 for (const auto &device : availProfileDevices) {
5092 // give a valid ID to an attached device once confirmed it is reachable
5093 if (!device->isAttached()) {
5094 device->attach(hwModule);
5095 device->importAudioPortAndPickAudioProfile(inProfile, true);
5096 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005097 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005098 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5099 }
5100 }
5101 inputDesc->close();
5102 }
5103 }
5104}
5105
Eric Laurent98e38192018-02-15 18:31:53 -08005106void AudioPolicyManager::addOutput(audio_io_handle_t output,
5107 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005108{
Eric Laurent1c333e22014-05-20 10:48:17 -07005109 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005110 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005111 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005112 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005113 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005114}
5115
François Gaffie53615e22015-03-19 09:24:12 +01005116void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5117{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005118 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5119 ALOGV("%s: removing primary output", __func__);
5120 mPrimaryOutput = nullptr;
5121 }
François Gaffie53615e22015-03-19 09:24:12 +01005122 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005123 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005124}
5125
Eric Laurent98e38192018-02-15 18:31:53 -08005126void AudioPolicyManager::addInput(audio_io_handle_t input,
5127 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005128{
Eric Laurent1c333e22014-05-20 10:48:17 -07005129 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005130 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005131}
Eric Laurente552edb2014-03-10 17:42:56 -07005132
François Gaffie11d30102018-11-02 16:09:09 +01005133status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005134 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005135 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005136{
François Gaffie11d30102018-11-02 16:09:09 +01005137 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005138 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005139 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005140
François Gaffie11d30102018-11-02 16:09:09 +01005141 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005142 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005143 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005144 }
Eric Laurente552edb2014-03-10 17:42:56 -07005145
Eric Laurent3b73df72014-03-11 09:06:29 -07005146 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005147 // first call getAudioPort to get the supported attributes from the HAL
5148 struct audio_port_v7 port = {};
5149 device->toAudioPort(&port);
5150 status_t status = mpClientInterface->getAudioPort(&port);
5151 if (status == NO_ERROR) {
5152 device->importAudioPort(port);
5153 }
5154
5155 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005156 for (size_t i = 0; i < mOutputs.size(); i++) {
5157 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005158 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005159 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005160 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5161 mOutputs.keyAt(i), device->toString().c_str());
5162 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005163 }
5164 }
5165 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005166 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005167 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005168 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5169 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005170 if (profile->supportsDevice(device)) {
5171 profiles.add(profile);
5172 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5173 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005174 }
5175 }
5176 }
5177
Eric Laurent7b279bb2015-12-14 10:18:23 -08005178 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005179
Eric Laurente552edb2014-03-10 17:42:56 -07005180 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005181 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005182 return BAD_VALUE;
5183 }
5184
5185 // open outputs for matching profiles if needed. Direct outputs are also opened to
5186 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5187 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005188 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005189
5190 // nothing to do if one output is already opened for this profile
5191 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005192 for (j = 0; j < outputs.size(); j++) {
5193 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005194 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005195 // matching profile: save the sample rates, format and channel masks supported
5196 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005197 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005198 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005199 }
Eric Laurente552edb2014-03-10 17:42:56 -07005200 break;
5201 }
5202 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005203 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005204 continue;
5205 }
5206
Eric Laurent3974e3b2017-12-07 17:58:43 -08005207 if (!profile->canOpenNewIo()) {
5208 ALOGW("Max Output number %u already opened for this profile %s",
5209 profile->maxOpenCount, profile->getTagName().c_str());
5210 continue;
5211 }
5212
Eric Laurent83efe1c2017-07-09 16:51:08 -07005213 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005214 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005215 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5216 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005217 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005218 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005219 profiles.removeAt(profile_index);
5220 profile_index--;
5221 } else {
5222 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005223 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005224 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005225 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5226 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005227 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005228 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005229
François Gaffie11d30102018-11-02 16:09:09 +01005230 if (device_distinguishes_on_address(deviceType)) {
5231 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5232 device->toString().c_str());
5233 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5234 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005235 }
Eric Laurente552edb2014-03-10 17:42:56 -07005236 ALOGV("checkOutputsForDevice(): adding output %d", output);
5237 }
5238 }
5239
5240 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005241 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005242 return BAD_VALUE;
5243 }
Eric Laurentd4692962014-05-05 18:13:44 -07005244 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005245 // check if one opened output is not needed any more after disconnecting one device
5246 for (size_t i = 0; i < mOutputs.size(); i++) {
5247 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005248 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005249 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005250 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005251 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005252 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005253 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005254 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5255 mOutputs.keyAt(i));
5256 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005257 }
Eric Laurente552edb2014-03-10 17:42:56 -07005258 }
5259 }
Eric Laurentd4692962014-05-05 18:13:44 -07005260 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005261 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005262 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5263 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005264 if (!profile->supportsDevice(device)) {
5265 continue;
5266 }
5267 ALOGV("checkOutputsForDevice(): "
5268 "clearing direct output profile %zu on module %s",
5269 j, hwModule->getName());
5270 profile->clearAudioProfiles();
5271 if (!profile->hasDynamicAudioProfile()) {
5272 continue;
5273 }
5274 // When a device is disconnected, if there is an IOProfile that contains dynamic
5275 // profiles and supports the disconnected device, call getAudioPort to repopulate
5276 // the capabilities of the devices that is supported by the IOProfile.
5277 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5278 if (supportedDevice == device ||
5279 !mAvailableOutputDevices.contains(supportedDevice)) {
5280 continue;
5281 }
5282 struct audio_port_v7 port;
5283 supportedDevice->toAudioPort(&port);
5284 status_t status = mpClientInterface->getAudioPort(&port);
5285 if (status == NO_ERROR) {
5286 supportedDevice->importAudioPort(port);
5287 }
Eric Laurente552edb2014-03-10 17:42:56 -07005288 }
5289 }
5290 }
5291 }
5292 return NO_ERROR;
5293}
5294
François Gaffie11d30102018-11-02 16:09:09 +01005295status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005296 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005297{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005298 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005299
François Gaffie11d30102018-11-02 16:09:09 +01005300 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005301 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005302 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005303 }
5304
Eric Laurentd4692962014-05-05 18:13:44 -07005305 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005306 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005307 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005308 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005309 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005310 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005311 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005312 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005313
François Gaffie11d30102018-11-02 16:09:09 +01005314 if (profile->supportsDevice(device)) {
5315 profiles.add(profile);
5316 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5317 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005318 }
5319 }
5320 }
5321
Eric Laurent0dd51852019-04-19 18:18:58 -07005322 if (profiles.isEmpty()) {
5323 ALOGW("%s: No input profile available for device %s",
5324 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005325 return BAD_VALUE;
5326 }
5327
5328 // open inputs for matching profiles if needed. Direct inputs are also opened to
5329 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5330 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5331
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005333
Eric Laurentd4692962014-05-05 18:13:44 -07005334 // nothing to do if one input is already opened for this profile
5335 size_t input_index;
5336 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5337 desc = mInputs.valueAt(input_index);
5338 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005339 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005340 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005341 }
Eric Laurentd4692962014-05-05 18:13:44 -07005342 break;
5343 }
5344 }
5345 if (input_index != mInputs.size()) {
5346 continue;
5347 }
5348
Eric Laurent3974e3b2017-12-07 17:58:43 -08005349 if (!profile->canOpenNewIo()) {
5350 ALOGW("Max Input number %u already opened for this profile %s",
5351 profile->maxOpenCount, profile->getTagName().c_str());
5352 continue;
5353 }
5354
Eric Laurentfe231122017-11-17 17:48:06 -08005355 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005356 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005357 status_t status = desc->open(nullptr,
5358 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005359 AUDIO_SOURCE_MIC,
5360 AUDIO_INPUT_FLAG_NONE,
5361 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005362
Eric Laurentcf2c0212014-07-25 16:20:43 -07005363 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005364 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005365 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005366 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005367 mpClientInterface->setParameters(input, String8(param));
5368 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005369 }
François Gaffie11d30102018-11-02 16:09:09 +01005370 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005371 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005372 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005373 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005374 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005375 }
5376
Eric Laurent0dd51852019-04-19 18:18:58 -07005377 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005378 addInput(input, desc);
5379 }
5380 } // endif input != 0
5381
Eric Laurentcf2c0212014-07-25 16:20:43 -07005382 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005383 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005384 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005385 profiles.removeAt(profile_index);
5386 profile_index--;
5387 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005388 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005389 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005390 }
Eric Laurentd4692962014-05-05 18:13:44 -07005391 ALOGV("checkInputsForDevice(): adding input %d", input);
5392 }
5393 } // end scan profiles
5394
5395 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005396 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005397 return BAD_VALUE;
5398 }
5399 } else {
5400 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005401 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005402 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005403 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005404 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005405 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005406 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005407 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005408 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5409 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005410 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005411 }
5412 }
5413 }
5414 } // end disconnect
5415
5416 return NO_ERROR;
5417}
5418
5419
Eric Laurente0720872014-03-11 09:30:41 -07005420void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005421{
5422 ALOGV("closeOutput(%d)", output);
5423
François Gaffie1c878552018-11-22 16:53:21 +01005424 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5425 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005426 ALOGW("closeOutput() unknown output %d", output);
5427 return;
5428 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005429 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005430 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005431
Eric Laurente552edb2014-03-10 17:42:56 -07005432 // look for duplicated outputs connected to the output being removed.
5433 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005434 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5435 if (dupOutput->isDuplicated() &&
5436 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5437 sp<SwAudioOutputDescriptor> remainingOutput =
5438 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005439 // As all active tracks on duplicated output will be deleted,
5440 // and as they were also referenced on the other output, the reference
5441 // count for their stream type must be adjusted accordingly on
5442 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005443 const bool wasActive = remainingOutput->isActive();
5444 // Note: no-op on the closing output where all clients has already been set inactive
5445 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005446 // stop() will be a no op if the output is still active but is needed in case all
5447 // active streams refcounts where cleared above
5448 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005449 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005450 }
Eric Laurente552edb2014-03-10 17:42:56 -07005451 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5452 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5453
5454 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005455 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005456 }
5457 }
5458
Eric Laurent05b90f82014-08-27 15:32:29 -07005459 nextAudioPortGeneration();
5460
François Gaffie1c878552018-11-22 16:53:21 +01005461 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005462 if (index >= 0) {
5463 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5465 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005466 mAudioPatches.removeItemsAt(index);
5467 mpClientInterface->onAudioPatchListUpdate();
5468 }
5469
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005470 if (closingOutputWasActive) {
5471 closingOutput->stop();
5472 }
François Gaffie1c878552018-11-22 16:53:21 +01005473 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005474
François Gaffie53615e22015-03-19 09:24:12 +01005475 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005476 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005477
5478 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5479 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005480 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005481 bool directOutputOpen = false;
5482 for (size_t i = 0; i < mOutputs.size(); i++) {
5483 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5484 directOutputOpen = true;
5485 break;
5486 }
5487 }
5488 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005489 ALOGV("no direct outputs open, reset MSD patches");
5490 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5491 // how output devices for patching are resolved. Avoid by caching and reusing the
5492 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5493 // devices to patch to. This may be complicated by the fact that devices may become
5494 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005495 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005496 }
5497 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005498}
5499
5500void AudioPolicyManager::closeInput(audio_io_handle_t input)
5501{
5502 ALOGV("closeInput(%d)", input);
5503
5504 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5505 if (inputDesc == NULL) {
5506 ALOGW("closeInput() unknown input %d", input);
5507 return;
5508 }
5509
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005511
François Gaffie11d30102018-11-02 16:09:09 +01005512 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005513 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005514 if (index >= 0) {
5515 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005516 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5517 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005518 mAudioPatches.removeItemsAt(index);
5519 mpClientInterface->onAudioPatchListUpdate();
5520 }
5521
Eric Laurentfe231122017-11-17 17:48:06 -08005522 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005523 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005524
François Gaffie11d30102018-11-02 16:09:09 +01005525 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5526 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005527 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005528 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005529 }
Eric Laurente552edb2014-03-10 17:42:56 -07005530}
5531
François Gaffie11d30102018-11-02 16:09:09 +01005532SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5533 const DeviceVector &devices,
5534 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005535{
5536 SortedVector<audio_io_handle_t> outputs;
5537
François Gaffie11d30102018-11-02 16:09:09 +01005538 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005539 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005540 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005541 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005542 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005543 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005544 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005545 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005546 outputs.add(openOutputs.keyAt(i));
5547 }
5548 }
5549 return outputs;
5550}
5551
Mikhail Naganov37977152018-07-11 15:54:44 -07005552void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5553{
5554 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5555 // output is suspended before any tracks are moved to it
5556 checkA2dpSuspend();
5557 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005558 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005559 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005560 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005561 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005562 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5563 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5564 // configuration changes will ultimately be rerouted correctly. We can still avoid
5565 // unnecessary rerouting by caching and reusing the arguments to
5566 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5567 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005568 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005569 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005570 // an event that changed routing likely occurred, inform upper layers
5571 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005572}
5573
François Gaffiec005e562018-11-06 15:04:49 +01005574bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5575 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005576{
François Gaffiec005e562018-11-06 15:04:49 +01005577 return mEngine->getProductStrategyForAttributes(lAttr) ==
5578 mEngine->getProductStrategyForAttributes(rAttr);
5579}
5580
Francois Gaffieff1eb522020-05-06 18:37:04 +02005581void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5582{
5583 for (size_t i = 0; i < mAudioSources.size(); i++) {
5584 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5585 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005586 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5587 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005588 connectAudioSource(sourceDesc);
5589 }
5590 }
5591}
5592
5593void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5594{
5595 for (size_t i = 0; i < mAudioSources.size(); i++) {
5596 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5597 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5598 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5599 disconnectAudioSource(sourceDesc);
5600 }
5601 }
5602}
5603
François Gaffiec005e562018-11-06 15:04:49 +01005604void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5605{
5606 auto psId = mEngine->getProductStrategyForAttributes(attr);
5607
5608 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5609 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005610
François Gaffie11d30102018-11-02 16:09:09 +01005611 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5612 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005613
Eric Laurentc209fe42020-06-05 18:11:23 -07005614 uint32_t maxLatency = 0;
5615 bool invalidate = false;
5616 // take into account dynamic audio policies related changes: if a client is now associated
5617 // to a different policy mix than at creation time, invalidate corresponding stream
5618 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5619 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5620 if (desc->isDuplicated()) {
5621 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005622 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005623 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5624 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5625 continue;
5626 }
5627 sp<AudioPolicyMix> primaryMix;
5628 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5629 client->flags(), primaryMix, nullptr);
5630 if (status != OK) {
5631 continue;
5632 }
yucliuf4de36d2020-09-14 14:57:56 -07005633 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005634 invalidate = true;
5635 if (desc->isStrategyActive(psId)) {
5636 maxLatency = desc->latency();
5637 }
5638 break;
5639 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005640 }
5641 }
5642
Eric Laurentc209fe42020-06-05 18:11:23 -07005643 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005644 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5645 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005646 for (audio_io_handle_t srcOut : srcOutputs) {
5647 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005648 if (desc == nullptr) continue;
5649
5650 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005651 maxLatency = desc->latency();
5652 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005653
5654 if (invalidate) continue;
5655
5656 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005657 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005658 // a client on a non direct outputs has necessarily a linear PCM format
5659 // so we can call selectOutput() safely
5660 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5661 client->flags(),
5662 client->config().format,
5663 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005664 client->config().sample_rate,
5665 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005666 if (newOutput != srcOut) {
5667 invalidate = true;
5668 break;
5669 }
5670 } else {
5671 sp<IOProfile> profile = getProfileForOutput(newDevices,
5672 client->config().sample_rate,
5673 client->config().format,
5674 client->config().channel_mask,
5675 client->flags(),
5676 true /* directOnly */);
5677 if (profile != desc->mProfile) {
5678 invalidate = true;
5679 break;
5680 }
5681 }
5682 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005683 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005684
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005685 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005686 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005687 std::to_string(srcOutputs[0]).c_str(),
5688 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005689 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005690 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005691 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005692 if (desc == nullptr) continue;
5693
5694 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005695 setStrategyMute(psId, true, desc);
5696 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005697 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005698 }
François Gaffiec005e562018-11-06 15:04:49 +01005699 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005700 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005701 connectAudioSource(source);
5702 }
Eric Laurente552edb2014-03-10 17:42:56 -07005703 }
5704
François Gaffiec005e562018-11-06 15:04:49 +01005705 // Move effects associated to this stream from previous output to new output
5706 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005707 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005708 }
François Gaffiec005e562018-11-06 15:04:49 +01005709 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005710 if (invalidate) {
5711 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5712 mpClientInterface->invalidateStream(stream);
5713 }
Eric Laurente552edb2014-03-10 17:42:56 -07005714 }
5715 }
5716}
5717
Eric Laurente0720872014-03-11 09:30:41 -07005718void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005719{
François Gaffiec005e562018-11-06 15:04:49 +01005720 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5721 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5722 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005723 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005724 }
Eric Laurente552edb2014-03-10 17:42:56 -07005725}
5726
Kevin Rocard153f92d2018-12-18 18:33:28 -08005727void AudioPolicyManager::checkSecondaryOutputs() {
5728 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005729 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005730 for (size_t i = 0; i < mOutputs.size(); i++) {
5731 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5732 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005733 sp<AudioPolicyMix> primaryMix;
5734 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005735 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005736 client->flags(), primaryMix, &secondaryMixes);
5737 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5738 for (auto &secondaryMix : secondaryMixes) {
5739 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5740 if (outputDesc != nullptr &&
5741 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5742 secondaryDescs.push_back(outputDesc);
5743 }
5744 }
5745
jiabinf042b9b2021-05-07 23:46:28 +00005746 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005747 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005748 } else if (!std::equal(
5749 client->getSecondaryOutputs().begin(),
5750 client->getSecondaryOutputs().end(),
5751 secondaryDescs.begin(), secondaryDescs.end())) {
jiabin64794372021-11-23 00:10:23 +00005752 if (!audio_is_linear_pcm(client->config().format)) {
5753 // If the format is not PCM, the tracks should be invalidated to get correct
5754 // behavior when the secondary output is changed.
5755 streamsToInvalidate.insert(client->stream());
5756 } else {
5757 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5758 std::vector<audio_io_handle_t> secondaryOutputIds;
5759 for (const auto &secondaryDesc: secondaryDescs) {
5760 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5761 weakSecondaryDescs.push_back(secondaryDesc);
5762 }
5763 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5764 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabinf042b9b2021-05-07 23:46:28 +00005765 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005766 }
5767 }
5768 }
jiabinf042b9b2021-05-07 23:46:28 +00005769 if (!trackSecondaryOutputs.empty()) {
5770 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5771 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005772 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005773 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005774 mpClientInterface->invalidateStream(stream);
5775 }
5776}
5777
Eric Laurent2517af32020-11-25 15:31:27 +01005778bool AudioPolicyManager::isScoRequestedForComm() const {
5779 AudioDeviceTypeAddrVector devices;
5780 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5781 for (const auto &device : devices) {
5782 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5783 return true;
5784 }
5785 }
5786 return false;
5787}
5788
Eric Laurente0720872014-03-11 09:30:41 -07005789void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005790{
François Gaffie53615e22015-03-19 09:24:12 +01005791 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005792 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005793 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005794 return;
5795 }
5796
Eric Laurent3a4311c2014-03-17 12:00:47 -07005797 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005798 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5799 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005800 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005801
5802 // if suspended, restore A2DP output if:
5803 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005804 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005805 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005806 //
Eric Laurentf732e072016-08-03 19:30:28 -07005807 // if not suspended, suspend A2DP output if:
5808 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005809 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005810 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005811 //
5812 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005813 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005814 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005815 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005816 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005817
5818 mpClientInterface->restoreOutput(a2dpOutput);
5819 mA2dpSuspended = false;
5820 }
5821 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005822 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005823 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005824 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005825 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005826
5827 mpClientInterface->suspendOutput(a2dpOutput);
5828 mA2dpSuspended = true;
5829 }
5830 }
5831}
5832
François Gaffie11d30102018-11-02 16:09:09 +01005833DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5834 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005835{
François Gaffie11d30102018-11-02 16:09:09 +01005836 DeviceVector devices;
5837
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005838 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005839 if (index >= 0) {
5840 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005841 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005842 ALOGV("%s device %s forced by patch %d", __func__,
5843 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5844 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005845 }
5846 }
5847
Dean Wheatley514b4312020-06-17 21:45:00 +10005848 // Do not retrieve engine device for outputs through MSD
5849 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5850 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5851 return outputDesc->devices();
5852 }
5853
Eric Laurent97ac8712018-07-27 18:59:02 -07005854 // Honor explicit routing requests only if no client using default routing is active on this
5855 // input: a specific app can not force routing for other apps by setting a preferred device.
5856 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005857 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005858 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005859 if (device != nullptr) {
5860 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005861 }
5862
François Gaffiea807ef92018-11-05 10:44:33 +01005863 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5864 // of setForceUse / Default Bus device here
5865 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5866 if (device != nullptr) {
5867 return DeviceVector(device);
5868 }
5869
François Gaffiec005e562018-11-06 15:04:49 +01005870 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5871 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5872 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305873 auto hasStreamActive = [&](auto stream) {
5874 return hasStream(streams, stream) && isStreamActive(stream, 0);
5875 };
Eric Laurent484e9272018-06-07 17:29:23 -07005876
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305877 auto doGetOutputDevicesForVoice = [&]() {
5878 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01005879 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305880 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02005881 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5882 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305883 };
5884
5885 // With low-latency playing on speaker, music on WFD, when the first low-latency
5886 // output is stopped, getNewOutputDevices checks for a product strategy
5887 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00005888 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305889 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5890 // stream is associated to the output descriptor.
5891 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5892 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5893 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5894 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005895 // Retrieval of devices for voice DL is done on primary output profile, cannot
5896 // check the route (would force modifying configuration file for this profile)
5897 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5898 break;
5899 }
Eric Laurente552edb2014-03-10 17:42:56 -07005900 }
François Gaffiec005e562018-11-06 15:04:49 +01005901 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005902 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005903}
5904
François Gaffie11d30102018-11-02 16:09:09 +01005905sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5906 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005907{
François Gaffie11d30102018-11-02 16:09:09 +01005908 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005909
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005910 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005911 if (index >= 0) {
5912 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005913 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005914 ALOGV("getNewInputDevice() device %s forced by patch %d",
5915 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5916 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005917 }
5918 }
5919
Eric Laurent97ac8712018-07-27 18:59:02 -07005920 // Honor explicit routing requests only if no client using default routing is active on this
5921 // input: a specific app can not force routing for other apps by setting a preferred device.
5922 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005923 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5924 if (device != nullptr) {
5925 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005926 }
5927
Eric Laurentdc95a252018-04-12 12:46:56 -07005928 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005929 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005930 audio_attributes_t attributes;
5931 uid_t uid;
5932 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5933 if (topClient != nullptr) {
5934 attributes = topClient->attributes();
5935 uid = topClient->uid();
5936 } else {
5937 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5938 uid = 0;
5939 }
5940
Francois Gaffie716e1432019-01-14 16:58:59 +01005941 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5942 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005943 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005944 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005945 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005946 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005947
Eric Laurente552edb2014-03-10 17:42:56 -07005948 return device;
5949}
5950
Eric Laurent794fde22016-03-11 09:50:45 -08005951bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5952 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005953 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005954}
5955
Eric Laurente0720872014-03-11 09:30:41 -07005956audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005957 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005958 // getOutputDevicesForStream's behavior for invalid streams.
5959 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5960 // device for music stream), but we want to return the empty set.
5961 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005962 return AUDIO_DEVICE_NONE;
5963 }
François Gaffie11d30102018-11-02 16:09:09 +01005964 DeviceVector activeDevices;
5965 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005966 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5967 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005968 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005969 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005970 }
François Gaffiec005e562018-11-06 15:04:49 +01005971 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005972 devices.merge(curDevices);
5973 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005974 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01005975 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01005976 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005977 }
5978 }
Eric Laurente552edb2014-03-10 17:42:56 -07005979 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005980
Eric Laurentb0688d62018-08-14 15:49:18 -07005981 // Favor devices selected on active streams if any to report correct device in case of
5982 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005983 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005984 devices = activeDevices;
5985 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005986 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5987 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005988 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005989 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005990 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005991 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005992 }
jiabin9a3361e2019-10-01 09:38:30 -07005993 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5994 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005995}
5996
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005997status_t AudioPolicyManager::getDevicesForAttributes(
5998 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5999 if (devices == nullptr) {
6000 return BAD_VALUE;
6001 }
6002 // check dynamic policies but only for primary descriptors (secondary not used for audible
6003 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006004 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006005 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006006 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006007 if (status != OK) {
6008 return status;
6009 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006010 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6011 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6012 devices->push_back(device);
6013 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006014 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006015 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6016 for (const auto& device : curDevices) {
6017 devices->push_back(device->getDeviceTypeAddr());
6018 }
6019 return NO_ERROR;
6020}
6021
Eric Laurente0720872014-03-11 09:30:41 -07006022void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006023 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006024 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006025 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006026 updateDevicesAndOutputs();
6027 break;
6028 default:
6029 break;
6030 }
6031}
6032
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006033uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006034
6035 // skip beacon mute management if a dedicated TTS output is available
6036 if (mTtsOutputAvailable) {
6037 return 0;
6038 }
6039
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006040 switch(event) {
6041 case STARTING_OUTPUT:
6042 mBeaconMuteRefCount++;
6043 break;
6044 case STOPPING_OUTPUT:
6045 if (mBeaconMuteRefCount > 0) {
6046 mBeaconMuteRefCount--;
6047 }
6048 break;
6049 case STARTING_BEACON:
6050 mBeaconPlayingRefCount++;
6051 break;
6052 case STOPPING_BEACON:
6053 if (mBeaconPlayingRefCount > 0) {
6054 mBeaconPlayingRefCount--;
6055 }
6056 break;
6057 }
6058
6059 if (mBeaconMuteRefCount > 0) {
6060 // any playback causes beacon to be muted
6061 return setBeaconMute(true);
6062 } else {
6063 // no other playback: unmute when beacon starts playing, mute when it stops
6064 return setBeaconMute(mBeaconPlayingRefCount == 0);
6065 }
6066}
6067
6068uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6069 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6070 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6071 // keep track of muted state to avoid repeating mute/unmute operations
6072 if (mBeaconMuted != mute) {
6073 // mute/unmute AUDIO_STREAM_TTS on all outputs
6074 ALOGV("\t muting %d", mute);
6075 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006076 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6077 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6078 ALOGV("\t no tts volume source available");
6079 return 0;
6080 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006081 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006082 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006083 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006084 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006085 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006086 maxLatency = latency;
6087 }
6088 }
6089 mBeaconMuted = mute;
6090 return maxLatency;
6091 }
6092 return 0;
6093}
6094
Eric Laurente0720872014-03-11 09:30:41 -07006095void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006096{
François Gaffiec005e562018-11-06 15:04:49 +01006097 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006098 mPreviousOutputs = mOutputs;
6099}
6100
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006101uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006102 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006103 uint32_t delayMs)
6104{
6105 // mute/unmute strategies using an incompatible device combination
6106 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6107 // if unmuting, unmute only after the specified delay
6108 if (outputDesc->isDuplicated()) {
6109 return 0;
6110 }
6111
6112 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006113 DeviceVector devices = outputDesc->devices();
6114 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006115
François Gaffiec005e562018-11-06 15:04:49 +01006116 auto productStrategies = mEngine->getOrderedProductStrategies();
6117 for (const auto &productStrategy : productStrategies) {
6118 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6119 DeviceVector curDevices =
6120 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6121 curDevices = curDevices.filter(outputDesc->supportedDevices());
6122 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006123 bool doMute = false;
6124
François Gaffiec005e562018-11-06 15:04:49 +01006125 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006126 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006127 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6128 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006129 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006130 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006131 }
Eric Laurent99401132014-05-07 19:48:15 -07006132 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006133 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006134 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006135 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006136 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006137 continue;
6138 }
François Gaffiec005e562018-11-06 15:04:49 +01006139 ALOGVV("%s() %s (curDevice %s)", __func__,
6140 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6141 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6142 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006143 if (mute) {
6144 // FIXME: should not need to double latency if volume could be applied
6145 // immediately by the audioflinger mixer. We must account for the delay
6146 // between now and the next time the audioflinger thread for this output
6147 // will process a buffer (which corresponds to one buffer size,
6148 // usually 1/2 or 1/4 of the latency).
6149 if (muteWaitMs < desc->latency() * 2) {
6150 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006151 }
6152 }
6153 }
6154 }
6155 }
6156 }
6157
Eric Laurent99401132014-05-07 19:48:15 -07006158 // temporary mute output if device selection changes to avoid volume bursts due to
6159 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006160 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006161 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6162 // temporary mute duration is conservatively set to 4 times the reported latency
6163 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6164 if (muteWaitMs < tempMuteWaitMs) {
6165 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006166 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006167 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6168 // make sure that we do not start the temporary mute period too early in case of
6169 // delayed device change
6170 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6171 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006172 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006173 }
6174 }
6175
Eric Laurente552edb2014-03-10 17:42:56 -07006176 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6177 if (muteWaitMs > delayMs) {
6178 muteWaitMs -= delayMs;
6179 usleep(muteWaitMs * 1000);
6180 return muteWaitMs;
6181 }
6182 return 0;
6183}
6184
François Gaffie11d30102018-11-02 16:09:09 +01006185uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6186 const DeviceVector &devices,
6187 bool force,
6188 int delayMs,
6189 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006190 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006191{
François Gaffie11d30102018-11-02 16:09:09 +01006192 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006193 uint32_t muteWaitMs;
6194
6195 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006196 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6197 nullptr /* patchHandle */, requiresMuteCheck);
6198 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6199 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006200 return muteWaitMs;
6201 }
Eric Laurente552edb2014-03-10 17:42:56 -07006202
6203 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006204 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006205 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006206 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006207
François Gaffie11d30102018-11-02 16:09:09 +01006208 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6209
6210 if (!filteredDevices.isEmpty()) {
6211 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006212 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006213
6214 // if the outputs are not materially active, there is no need to mute.
6215 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006216 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006217 } else {
6218 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6219 muteWaitMs = 0;
6220 }
Eric Laurente552edb2014-03-10 17:42:56 -07006221
Eric Laurent79ea9582020-06-11 18:49:24 -07006222 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6223 // output profile or if new device is not supported AND previous device(s) is(are) still
6224 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006225 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006226 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6227 // restore previous device after evaluating strategy mute state
6228 outputDesc->setDevices(prevDevices);
6229 return muteWaitMs;
6230 }
6231
Eric Laurente552edb2014-03-10 17:42:56 -07006232 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006233 // the requested device is AUDIO_DEVICE_NONE
6234 // OR the requested device is the same as current device
6235 // AND force is not specified
6236 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006237 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006238 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
Francois Gaffie3523ab32021-06-22 13:24:34 +02006239 !force && outputDesc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006240 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6241 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006242 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6243 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6244 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6245 }
Eric Laurente552edb2014-03-10 17:42:56 -07006246 return muteWaitMs;
6247 }
6248
François Gaffie11d30102018-11-02 16:09:09 +01006249 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006250
Eric Laurente552edb2014-03-10 17:42:56 -07006251 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006252 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006253 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006254 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006255 PatchBuilder patchBuilder;
6256 patchBuilder.addSource(outputDesc);
6257 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6258 for (const auto &filteredDevice : filteredDevices) {
6259 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006260 }
6261
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006262 // Add half reported latency to delayMs when muteWaitMs is null in order
6263 // to avoid disordered sequence of muting volume and changing devices.
6264 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6265 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006266 }
Eric Laurente552edb2014-03-10 17:42:56 -07006267
6268 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006269 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006270
6271 return muteWaitMs;
6272}
6273
Eric Laurentc75307b2015-03-17 15:29:32 -07006274status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006275 int delayMs,
6276 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006277{
Eric Laurent6a94d692014-05-20 11:18:06 -07006278 ssize_t index;
6279 if (patchHandle) {
6280 index = mAudioPatches.indexOfKey(*patchHandle);
6281 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006282 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006283 }
6284 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006285 return INVALID_OPERATION;
6286 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006287 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006288 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006289 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006290 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006291 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006292 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006293 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006294 return status;
6295}
6296
6297status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006298 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006299 bool force,
6300 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006301{
6302 status_t status = NO_ERROR;
6303
Eric Laurent1f2f2232014-06-02 12:01:23 -07006304 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006305 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6306 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006307
François Gaffie11d30102018-11-02 16:09:09 +01006308 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006309 PatchBuilder patchBuilder;
6310 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006311 // AUDIO_SOURCE_HOTWORD is for internal use only:
6312 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006313 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6314 auto result = usecase;
6315 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6316 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6317 }
6318 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006319 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006320 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006321 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006322 }
6323 }
6324 return status;
6325}
6326
Eric Laurent6a94d692014-05-20 11:18:06 -07006327status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6328 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006329{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006330 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006331 ssize_t index;
6332 if (patchHandle) {
6333 index = mAudioPatches.indexOfKey(*patchHandle);
6334 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006335 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006336 }
6337 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006338 return INVALID_OPERATION;
6339 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006340 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006341 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006342 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006343 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006344 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006345 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006346 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006347 return status;
6348}
6349
François Gaffie11d30102018-11-02 16:09:09 +01006350sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006351 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006352 audio_format_t& format,
6353 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006354 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006355{
6356 // Choose an input profile based on the requested capture parameters: select the first available
6357 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006358 //
6359 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6360 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006361
Glenn Kasten730b9262018-03-29 15:01:26 -07006362 sp<IOProfile> firstInexact;
6363 uint32_t updatedSamplingRate = 0;
6364 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6365 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006366 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006367 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006368 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006369 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006370 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006371 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006372 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006373 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006374 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006375 &channelMask /*updatedChannelMask*/,
6376 // FIXME ugly cast
6377 (audio_output_flags_t) flags,
6378 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006379 return profile;
6380 }
François Gaffie11d30102018-11-02 16:09:09 +01006381 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006382 samplingRate,
6383 &updatedSamplingRate,
6384 format,
6385 &updatedFormat,
6386 channelMask,
6387 &updatedChannelMask,
6388 // FIXME ugly cast
6389 (audio_output_flags_t) flags,
6390 false /*exactMatchRequiredForInputFlags*/)) {
6391 firstInexact = profile;
6392 }
6393
Eric Laurente552edb2014-03-10 17:42:56 -07006394 }
6395 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006396 if (firstInexact != nullptr) {
6397 samplingRate = updatedSamplingRate;
6398 format = updatedFormat;
6399 channelMask = updatedChannelMask;
6400 return firstInexact;
6401 }
Eric Laurente552edb2014-03-10 17:42:56 -07006402 return NULL;
6403}
6404
François Gaffieaaac0fd2018-11-22 17:56:39 +01006405float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6406 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006407 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006408 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006409{
jiabin9a3361e2019-10-01 09:38:30 -07006410 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006411
6412 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6413 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6414 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6415 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006416 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6417 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
6418 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
6419 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
6420 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006421
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006422 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006423 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6424 mOutputs.isActive(ringVolumeSrc, 0)) {
6425 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006426 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006427 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006428 }
6429
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006430 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006431 if ((volumeSource != callVolumeSrc && (isInCall() ||
6432 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006433 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006434 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6435 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006436 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
6437 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
6438 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006439 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006440 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006441 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006442 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006443 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006444 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006445 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6446 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6447 // programmatically muted.
6448 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6449 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6450 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006451 bool exemptFromCapping =
6452 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6453 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006454 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6455 volumeSource, volumeDb);
6456 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006457 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6458 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6459 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006460 }
6461 }
Eric Laurente552edb2014-03-10 17:42:56 -07006462 // if a headset is connected, apply the following rules to ring tones and notifications
6463 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006464 // - always attenuate notifications volume by 6dB
6465 // - attenuate ring tones volume by 6dB unless music is not playing and
6466 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006467 // - if music is playing, always limit the volume to current music volume,
6468 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006469 if (!Intersection(deviceTypes,
6470 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6471 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006472 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6473 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006474 ((volumeSource == alarmVolumeSrc ||
6475 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006476 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
6477 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
6478 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006479 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6480 curves.canBeMuted()) {
6481
Eric Laurente552edb2014-03-10 17:42:56 -07006482 // when the phone is ringing we must consider that music could have been paused just before
6483 // by the music application and behave as if music was active if the last music track was
6484 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006485 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006486 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006487 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006488 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006489 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6490 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006491 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006492 float musicVolDb = computeVolume(musicCurves,
6493 musicVolumeSrc,
6494 musicCurves.getVolumeIndex(musicDevice),
6495 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006496 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6497 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6498 if (volumeDb > minVolDb) {
6499 volumeDb = minVolDb;
6500 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006501 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006502 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6503 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6504 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006505 // on A2DP, also ensure notification volume is not too low compared to media when
6506 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006507 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006508 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006509 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6510 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006511 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6512 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006513 }
6514 }
jiabin9a3361e2019-10-01 09:38:30 -07006515 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006516 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006517 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006518 }
6519 }
6520
François Gaffie43c73442018-11-08 08:21:55 +01006521 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006522}
6523
Eric Laurent3839bc02018-07-10 18:33:34 -07006524int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006525 VolumeSource fromVolumeSource,
6526 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006527{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006528 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006529 return srcIndex;
6530 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006531 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6532 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006533 float minSrc = (float)srcCurves.getVolumeIndexMin();
6534 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6535 float minDst = (float)dstCurves.getVolumeIndexMin();
6536 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006537
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006538 // preserve mute request or correct range
6539 if (srcIndex < minSrc) {
6540 if (srcIndex == 0) {
6541 return 0;
6542 }
6543 srcIndex = minSrc;
6544 } else if (srcIndex > maxSrc) {
6545 srcIndex = maxSrc;
6546 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006547 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6548}
6549
François Gaffieaaac0fd2018-11-22 17:56:39 +01006550status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6551 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006552 int index,
6553 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006554 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006555 int delayMs,
6556 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006557{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006558 // do not change actual attributes volume if the attributes is muted
6559 if (outputDesc->isMuted(volumeSource)) {
6560 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6561 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006562 return NO_ERROR;
6563 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006564 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6565 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
6566 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
6567 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006568
Eric Laurent2517af32020-11-25 15:31:27 +01006569 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006570 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006571 // if sco and call follow same curves, bypass forceUseForComm
6572 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006573 ((isVoiceVolSrc && isScoRequested) ||
6574 (isBtScoVolSrc && !isScoRequested))) {
6575 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6576 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006577 // Do not return an error here as AudioService will always set both voice call
6578 // and bluetooth SCO volumes due to stream aliasing.
6579 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006580 }
jiabin9a3361e2019-10-01 09:38:30 -07006581 if (deviceTypes.empty()) {
6582 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006583 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006584
jiabin9a3361e2019-10-01 09:38:30 -07006585 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6586 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006587 // Force VoIP volume to max for bluetooth SCO device except if muted
6588 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006589 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006590 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006591 }
Francois Gaffie593634d2021-06-22 13:31:31 +02006592 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07006593 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02006594 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006595
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006596 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006597 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006598 // 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 +01006599 if (isVoiceVolSrc) {
6600 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006601 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006602 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006603 }
Eric Laurent18fba842016-03-31 14:41:26 -07006604 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006605 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6606 mLastVoiceVolume = voiceVolume;
6607 }
6608 }
Eric Laurente552edb2014-03-10 17:42:56 -07006609 return NO_ERROR;
6610}
6611
Eric Laurentc75307b2015-03-17 15:29:32 -07006612void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006613 const DeviceTypeSet& deviceTypes,
6614 int delayMs,
6615 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006616{
jiabincd510522020-01-22 09:40:55 -08006617 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006618 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6619 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6620 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006621 curves.getVolumeIndex(deviceTypes),
6622 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006623 }
6624}
6625
François Gaffiec005e562018-11-06 15:04:49 +01006626void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6627 bool on,
6628 const sp<AudioOutputDescriptor>& outputDesc,
6629 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006630 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006631{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006632 std::vector<VolumeSource> sourcesToMute;
6633 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6634 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6635 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006636 VolumeSource source = toVolumeSource(attributes, false);
6637 if ((source != VOLUME_SOURCE_NONE) &&
6638 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
6639 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006640 sourcesToMute.push_back(source);
6641 }
Eric Laurente552edb2014-03-10 17:42:56 -07006642 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006643 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006644 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006645 }
6646
Eric Laurente552edb2014-03-10 17:42:56 -07006647}
6648
François Gaffieaaac0fd2018-11-22 17:56:39 +01006649void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6650 bool on,
6651 const sp<AudioOutputDescriptor>& outputDesc,
6652 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006653 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006654{
jiabin9a3361e2019-10-01 09:38:30 -07006655 if (deviceTypes.empty()) {
6656 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006657 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006658 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006659 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006660 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006661 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006662 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006663 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6664 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006665 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006666 }
6667 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006668 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6669 // ignored
6670 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006671 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006672 if (!outputDesc->isMuted(volumeSource)) {
6673 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006674 return;
6675 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006676 if (outputDesc->decMuteCount(volumeSource) == 0) {
6677 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006678 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006679 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006680 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006681 delayMs);
6682 }
6683 }
6684}
6685
François Gaffie53615e22015-03-19 09:24:12 +01006686bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6687{
François Gaffiec005e562018-11-06 15:04:49 +01006688 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006689 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6690 return true;
6691 }
6692
6693 // has known usage?
6694 switch (paa->usage) {
6695 case AUDIO_USAGE_UNKNOWN:
6696 case AUDIO_USAGE_MEDIA:
6697 case AUDIO_USAGE_VOICE_COMMUNICATION:
6698 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6699 case AUDIO_USAGE_ALARM:
6700 case AUDIO_USAGE_NOTIFICATION:
6701 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6702 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6703 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6704 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6705 case AUDIO_USAGE_NOTIFICATION_EVENT:
6706 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6707 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6708 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6709 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006710 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006711 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006712 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006713 case AUDIO_USAGE_EMERGENCY:
6714 case AUDIO_USAGE_SAFETY:
6715 case AUDIO_USAGE_VEHICLE_STATUS:
6716 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006717 break;
6718 default:
6719 return false;
6720 }
6721 return true;
6722}
6723
François Gaffie2110e042015-03-24 08:41:51 +01006724audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6725{
6726 return mEngine->getForceUse(usage);
6727}
6728
6729bool AudioPolicyManager::isInCall()
6730{
6731 return isStateInCall(mEngine->getPhoneState());
6732}
6733
6734bool AudioPolicyManager::isStateInCall(int state)
6735{
6736 return is_state_in_call(state);
6737}
6738
Eric Laurent74b71512019-11-06 17:21:57 -08006739bool AudioPolicyManager::isCallAudioAccessible()
6740{
6741 audio_mode_t mode = mEngine->getPhoneState();
6742 return (mode == AUDIO_MODE_IN_CALL)
6743 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6744 || (mode == AUDIO_MODE_CALL_SCREEN);
6745}
6746
Eric Laurentd60560a2015-04-10 11:31:20 -07006747void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6748{
6749 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006750 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006751 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006752 sourceDesc->sinkDevice()->equals(deviceDesc))
6753 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006754 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006755 }
6756 }
6757
6758 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6759 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6760 bool release = false;
6761 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6762 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6763 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6764 source->ext.device.type == deviceDesc->type()) {
6765 release = true;
6766 }
6767 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006768 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006769 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6770 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6771 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006772 sink->ext.device.type == deviceDesc->type() &&
6773 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6774 || strncmp(sink->ext.device.address, address,
6775 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006776 release = true;
6777 }
6778 }
6779 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006780 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6781 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006782 }
6783 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006784
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006785 mInputs.clearSessionRoutesForDevice(deviceDesc);
6786
Francois Gaffie716e1432019-01-14 16:58:59 +01006787 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006788}
6789
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006790void AudioPolicyManager::modifySurroundFormats(
6791 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006792 std::unordered_set<audio_format_t> enforcedSurround(
6793 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006794 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6795 for (const auto& pair : mConfig.getSurroundFormats()) {
6796 allSurround.insert(pair.first);
6797 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6798 }
Phil Burk09bc4612016-02-24 15:58:15 -08006799
6800 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6801 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006802 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006803 // This is the resulting set of formats depending on the surround mode:
6804 // 'all surround' = allSurround
6805 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6806 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6807 // 'manual surround' = mManualSurroundFormats
6808 // AUTO: formats v 'enforced surround'
6809 // ALWAYS: formats v 'all surround' v 'enforced surround'
6810 // NEVER: formats ^ 'non-surround'
6811 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006812
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006813 std::unordered_set<audio_format_t> formatSet;
6814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6815 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006816 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006817 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006818 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006819 formatSet.insert(*formatIter);
6820 }
6821 }
6822 } else {
6823 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6824 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006825 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006826
jiabin81772902018-04-02 17:52:27 -07006827 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006828 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006829 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6830 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6831 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006832 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006833 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6834 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6835 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006836 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006837 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006838 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006839 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006840 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006841 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006842}
6843
jiabin06e4bab2019-07-29 10:13:34 -07006844void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6845 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006846 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6847 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6848
6849 // If NEVER, then remove support for channelMasks > stereo.
6850 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006851 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6852 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006853 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006854 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006855 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006856 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006857 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006858 }
6859 }
jiabin81772902018-04-02 17:52:27 -07006860 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6861 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6862 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006863 bool supports5dot1 = false;
6864 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006865 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006866 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6867 supports5dot1 = true;
6868 break;
6869 }
6870 }
6871 // If not then add 5.1 support.
6872 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006873 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006874 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006875 }
Phil Burk09bc4612016-02-24 15:58:15 -08006876 }
6877}
6878
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006879void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006880 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006881 AudioProfileVector &profiles)
6882{
6883 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006884 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006885
François Gaffie112b0af2015-11-19 16:13:25 +01006886 // Format MUST be checked first to update the list of AudioProfile
6887 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006888 reply = mpClientInterface->getParameters(
6889 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006890 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006891 AudioParameter repliedParameters(reply);
6892 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006893 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006894 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6895 return;
6896 }
Phil Burk09bc4612016-02-24 15:58:15 -08006897 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006898 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006899 if (device == AUDIO_DEVICE_OUT_HDMI
6900 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006901 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006902 }
jiabin3e277cc2019-09-10 14:27:34 -07006903 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006904 }
François Gaffie112b0af2015-11-19 16:13:25 +01006905
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006906 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006907 ChannelMaskSet channelMasks;
6908 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006909 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006910 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006911
6912 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006913 reply = mpClientInterface->getParameters(
6914 ioHandle,
6915 requestedParameters.toString() + ";" +
6916 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006917 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006918 AudioParameter repliedParameters(reply);
6919 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006920 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006921 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006922 }
6923 }
6924 if (profiles.hasDynamicChannelsFor(format)) {
6925 reply = mpClientInterface->getParameters(ioHandle,
6926 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006927 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006928 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006929 AudioParameter repliedParameters(reply);
6930 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006931 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006932 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006933 if (device == AUDIO_DEVICE_OUT_HDMI
6934 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006935 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006936 }
François Gaffie112b0af2015-11-19 16:13:25 +01006937 }
6938 }
jiabin3e277cc2019-09-10 14:27:34 -07006939 addDynamicAudioProfileAndSort(
6940 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006941 }
6942}
Eric Laurentd60560a2015-04-10 11:31:20 -07006943
Mikhail Naganovdc769682018-05-04 15:34:08 -07006944status_t AudioPolicyManager::installPatch(const char *caller,
6945 audio_patch_handle_t *patchHandle,
6946 AudioIODescriptorInterface *ioDescriptor,
6947 const struct audio_patch *patch,
6948 int delayMs)
6949{
6950 ssize_t index = mAudioPatches.indexOfKey(
6951 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6952 *patchHandle : ioDescriptor->getPatchHandle());
6953 sp<AudioPatch> patchDesc;
6954 status_t status = installPatch(
6955 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6956 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006957 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006958 }
6959 return status;
6960}
6961
6962status_t AudioPolicyManager::installPatch(const char *caller,
6963 ssize_t index,
6964 audio_patch_handle_t *patchHandle,
6965 const struct audio_patch *patch,
6966 int delayMs,
6967 uid_t uid,
6968 sp<AudioPatch> *patchDescPtr)
6969{
6970 sp<AudioPatch> patchDesc;
6971 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6972 if (index >= 0) {
6973 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006974 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006975 }
6976
6977 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6978 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6979 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6980 if (status == NO_ERROR) {
6981 if (index < 0) {
6982 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006983 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006984 } else {
6985 patchDesc->mPatch = *patch;
6986 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006987 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006988 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006989 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006990 }
6991 nextAudioPortGeneration();
6992 mpClientInterface->onAudioPatchListUpdate();
6993 }
6994 if (patchDescPtr) *patchDescPtr = patchDesc;
6995 return status;
6996}
6997
jiabinbce0c1d2020-10-05 11:20:18 -07006998bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6999{
7000 const TrackClientVector activeClients = output->getActiveClients();
7001 if (activeClients.empty()) {
7002 return true;
7003 }
7004 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7005 if (index < 0) {
7006 ALOGE("%s, no audio patch found while there are active clients on output %d",
7007 __func__, output->getId());
7008 return false;
7009 }
7010 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7011 DeviceVector routedDevices;
7012 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7013 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7014 patchDesc->mPatch.sinks[i].id);
7015 if (device == nullptr) {
7016 ALOGE("%s, no audio device found with id(%d)",
7017 __func__, patchDesc->mPatch.sinks[i].id);
7018 return false;
7019 }
7020 routedDevices.add(device);
7021 }
7022 for (const auto& client : activeClients) {
7023 // TODO: b/175343099 only travel the valid client
7024 sp<DeviceDescriptor> preferredDevice =
7025 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7026 if (mEngine->getOutputDevicesForAttributes(
7027 client->attributes(), preferredDevice, false) == routedDevices) {
7028 return false;
7029 }
7030 }
7031 return true;
7032}
7033
7034sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7035 const sp<IOProfile>& profile, const DeviceVector& devices)
7036{
7037 for (const auto& device : devices) {
7038 // TODO: This should be checking if the profile supports the device combo.
7039 if (!profile->supportsDevice(device)) {
7040 return nullptr;
7041 }
7042 }
7043 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7044 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
7045 status_t status = desc->open(nullptr, devices,
7046 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7047 if (status != NO_ERROR) {
7048 return nullptr;
7049 }
7050
7051 // Here is where the out_set_parameters() for card & device gets called
7052 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7053 const audio_devices_t deviceType = device->type();
7054 const String8 &address = String8(device->address().c_str());
7055 if (!address.isEmpty()) {
7056 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7057 mpClientInterface->setParameters(output, String8(param));
7058 free(param);
7059 }
7060 updateAudioProfiles(device, output, profile->getAudioProfiles());
7061 if (!profile->hasValidAudioProfile()) {
7062 ALOGW("%s() missing param", __func__);
7063 desc->close();
7064 return nullptr;
7065 } else if (profile->hasDynamicAudioProfile()) {
7066 desc->close();
7067 output = AUDIO_IO_HANDLE_NONE;
7068 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7069 profile->pickAudioProfile(
7070 config.sample_rate, config.channel_mask, config.format);
7071 config.offload_info.sample_rate = config.sample_rate;
7072 config.offload_info.channel_mask = config.channel_mask;
7073 config.offload_info.format = config.format;
7074
7075 status = desc->open(&config, devices,
7076 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7077 if (status != NO_ERROR) {
7078 return nullptr;
7079 }
7080 }
7081
7082 addOutput(output, desc);
7083 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7084 sp<AudioPolicyMix> policyMix;
7085 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7086 policyMix->setOutput(desc);
7087 desc->mPolicyMix = policyMix;
7088 } else {
7089 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7090 address.string());
7091 }
7092
7093 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7094 // no duplicated output for direct outputs and
7095 // outputs used by dynamic policy mixes
7096 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7097
7098 //TODO: configure audio effect output stage here
7099
7100 // open a duplicating output thread for the new output and the primary output
7101 sp<SwAudioOutputDescriptor> dupOutputDesc =
7102 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7103 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7104 if (status == NO_ERROR) {
7105 // add duplicated output descriptor
7106 addOutput(duplicatedOutput, dupOutputDesc);
7107 } else {
7108 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7109 mPrimaryOutput->mIoHandle, output);
7110 desc->close();
7111 removeOutput(output);
7112 nextAudioPortGeneration();
7113 return nullptr;
7114 }
7115 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007116 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7117 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7118 mPrimaryOutput = desc;
7119 }
jiabinbce0c1d2020-10-05 11:20:18 -07007120 return desc;
7121}
7122
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007123} // namespace android