blob: d6dd7625825f411e64c1c7d8a26967229cb829d8 [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{
jiabince9f20e2019-09-12 16:29:15 -0700115 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200116 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700117 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100118 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200119 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
120}
121
François Gaffie11d30102018-11-02 16:09:09 +0100122status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800123 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800124 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 const char *device_name,
126 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800127{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800128 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
129 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700130
131 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100132 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700133
François Gaffie11d30102018-11-02 16:09:09 +0100134 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800135 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100136 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
138}
Paul McLeane743a472015-01-28 11:07:31 -0800139
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700140status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
141 audio_policy_dev_state_t state)
142{
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700144 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700145 SortedVector <audio_io_handle_t> outputs;
146
François Gaffie11d30102018-11-02 16:09:09 +0100147 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148
Eric Laurente552edb2014-03-10 17:42:56 -0700149 // save a copy of the opened output descriptors before any output is opened or closed
150 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
151 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700152 switch (state)
153 {
154 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800155 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100157 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700158 return INVALID_OPERATION;
159 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800160 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700161 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700162
Eric Laurente552edb2014-03-10 17:42:56 -0700163 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200164 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100170 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200171
François Gaffie11d30102018-11-02 16:09:09 +0100172 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
173 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200174
Francois Gaffie716e1432019-01-14 16:58:59 +0100175 mHwModules.cleanUpForDevice(device);
176
François Gaffie11d30102018-11-02 16:09:09 +0100177 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700178 return INVALID_OPERATION;
179 }
François Gaffie2110e042015-03-24 08:41:51 +0100180
jiabin1c4794b2020-05-05 10:08:05 -0700181 // Populate encapsulation information when a output device is connected.
182 device->setEncapsulationInfoFromHal(mpClientInterface);
183
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700184 // outputs should never be empty here
185 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
186 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100187 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188
Eric Laurent3ae5f312015-02-03 17:12:08 -0800189 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700191 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100193 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700194 return INVALID_OPERATION;
195 }
196
François Gaffie11d30102018-11-02 16:09:09 +0100197 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Paul McLeane743a472015-01-28 11:07:31 -0800199 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100200 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100203 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700204
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100205 mOutputs.clearSessionRoutesForDevice(device);
206
François Gaffie11d30102018-11-02 16:09:09 +0100207 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100208
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800209 // Reset active device codec
210 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
211
Kriti Dangef6be8f2020-11-05 11:58:19 +0100212 // remove device from mReportedFormatsMap cache
213 mReportedFormatsMap.erase(device);
214
Eric Laurente552edb2014-03-10 17:42:56 -0700215 } break;
216
217 default:
François Gaffie11d30102018-11-02 16:09:09 +0100218 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700219 return BAD_VALUE;
220 }
221
Eric Laurent736a1022019-03-27 18:28:46 -0700222 // Propagate device availability to Engine
223 setEngineDeviceConnectionState(device, state);
224
Eric Laurentae970022019-01-29 14:25:04 -0800225 // No need to evaluate playback routing when connecting a remote submix
226 // output device used by a dynamic policy of type recorder as no
227 // playback use case is affected.
228 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700229 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800230 for (audio_io_handle_t output : outputs) {
231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800232 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
233 if (policyMix != nullptr
234 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700235 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800236 doCheckForDeviceAndOutputChanges = false;
237 break;
238 }
239 }
240 }
241
242 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700243 // outputs must be closed after checkOutputForAllStrategies() is executed
244 if (!outputs.isEmpty()) {
245 for (audio_io_handle_t output : outputs) {
246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100247 // close unused outputs after device disconnection or direct outputs that have
248 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700249 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
250 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800251 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200252 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 closeOutput(output);
254 }
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
257 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700258 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700259 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800260 };
261
262 if (doCheckForDeviceAndOutputChanges) {
263 checkForDeviceAndOutputChanges(checkCloseOutputs);
264 } else {
265 checkCloseOutputs();
266 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100267 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700268 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700270 const DeviceVector activeMediaDevices =
271 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530274 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
275 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100276 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700277 // do not force device change on duplicated output because if device is 0, it will
278 // also force a device 0 for the two outputs it is duplicated to which may override
279 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100280 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100281 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 // always force when disconnecting (a non-duplicated device)
284 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100285 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 }
jiabinbce0c1d2020-10-05 11:20:18 -0700287 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000288 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700289 desc->supportsDevicesForPlayback(activeMediaDevices)) {
290 // Reopen the output to query the dynamic profiles when there is not active
291 // clients or all active clients will be rerouted. Otherwise, set the flag
292 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
293 // can be reopened to query dynamic profiles when all clients are inactive.
294 if (areAllActiveTracksRerouted(desc)) {
295 outputsToReopen.push_back(mOutputs.keyAt(i));
296 } else {
297 desc->mPendingReopenToQueryProfiles = true;
298 }
299 }
300 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
301 // Clear the flag that previously set for re-querying profiles.
302 desc->mPendingReopenToQueryProfiles = false;
303 }
304 }
305 for (const auto& output : outputsToReopen) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
307 closeOutput(output);
308 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310
Eric Laurentd60560a2015-04-10 11:31:20 -0700311 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700322 switch (state)
323 {
324 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700330
331 if (mAvailableInputDevices.add(device) < 0) {
332 return NO_MEMORY;
333 }
334
François Gaffie44481e72016-04-20 07:49:57 +0200335 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
336 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200338
Eric Laurent0dd51852019-04-19 18:18:58 -0700339 if (checkInputsForDevice(device, state) != NO_ERROR) {
340 mAvailableInputDevices.remove(device);
341
François Gaffie11d30102018-11-02 16:09:09 +0100342 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100343
344 mHwModules.cleanUpForDevice(device);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 return INVALID_OPERATION;
347 }
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100354 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700355 return INVALID_OPERATION;
356 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700357
François Gaffie11d30102018-11-02 16:09:09 +0100358 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
360 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100361 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
François Gaffie11d30102018-11-02 16:09:09 +0100363 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700364
365 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100366
367 // remove device from mReportedFormatsMap cache
368 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 default:
François Gaffie11d30102018-11-02 16:09:09 +0100372 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700373 return BAD_VALUE;
374 }
375
Eric Laurent736a1022019-03-27 18:28:46 -0700376 // Propagate device availability to Engine
377 setEngineDeviceConnectionState(device, state);
378
Eric Laurent0dd51852019-04-19 18:18:58 -0700379 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700380 // As the input device list can impact the output device selection, update
381 // getDeviceForStrategy() cache
382 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100384 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200385 // Reconnect Audio Source
386 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
387 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
388 checkAudioSourceForAttributes(attributes);
389 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700390 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100391 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700392 }
393
Eric Laurentb52c1522014-05-20 11:27:36 -0700394 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700395 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700396 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700397
François Gaffie11d30102018-11-02 16:09:09 +0100398 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return BAD_VALUE;
400}
401
Eric Laurent736a1022019-03-27 18:28:46 -0700402void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
403 audio_policy_dev_state_t state) {
404
405 // the Engine does not have to know about remote submix devices used by dynamic audio policies
406 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
407 return;
408 }
409 mEngine->setDeviceConnectionState(device, state);
410}
411
412
Eric Laurente0720872014-03-11 09:30:41 -0700413audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100414 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700415{
Eric Laurent634b7142016-04-20 13:48:02 -0700416 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800417 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
418 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700419 (strlen(device_address) != 0)/*matchAddress*/);
420
421 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100422 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700423 device, device_address);
424 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
425 }
François Gaffie53615e22015-03-19 09:24:12 +0100426
Eric Laurent3a4311c2014-03-17 12:00:47 -0700427 DeviceVector *deviceVector;
428
Eric Laurente552edb2014-03-10 17:42:56 -0700429 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700431 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700432 deviceVector = &mAvailableInputDevices;
433 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100434 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 }
Eric Laurent634b7142016-04-20 13:48:02 -0700437
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800438 return (deviceVector->getDevice(
439 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700440 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800441}
442
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800443status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
444 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800445 const char *device_name,
446 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800447{
448 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700449 String8 reply;
450 AudioParameter param;
451 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800452
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800453 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
454 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800455
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800456 // connect/disconnect only 1 device at a time
457 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
458
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700460 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800461 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Nothing to do: device is not connected
463 return NO_ERROR;
464 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800466
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700467 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 // configure codecs.
469 // Handle two specific cases by sending a set parameter to
470 // configure A2DP codecs. No need to toggle device state.
471 // Case 1: A2DP active device switches from primary to primary
472 // module
473 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200474 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700475 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800476 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
477 if (availablePrimaryOutputDevices().contains(devDesc) &&
478 (module != 0 && module->getHandle() == primaryHandle)) {
479 reply = mpClientInterface->getParameters(
480 AUDIO_IO_HANDLE_NONE,
481 String8(AudioParameter::keyReconfigA2dpSupported));
482 AudioParameter repliedParameters(reply);
483 repliedParameters.getInt(
484 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
485 if (isReconfigA2dpSupported) {
486 const String8 key(AudioParameter::keyReconfigA2dp);
487 param.add(key, String8("true"));
488 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
489 devDesc->setEncodedFormat(encodedFormat);
490 return NO_ERROR;
491 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700492 }
493 }
cnx421bd2dcc42020-07-11 14:58:44 +0800494 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
495 for (size_t i = 0; i < mOutputs.size(); i++) {
496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
497 // mute media strategies and delay device switch by the largest
498 // This avoid sending the music tail into the earpiece or headset.
499 setStrategyMute(musicStrategy, true, desc);
500 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
501 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
502 nullptr, true /*fromCache*/).types());
503 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504 // Toggle the device state: UNAVAILABLE -> AVAILABLE
505 // This will force reading again the device configuration
506 status = setDeviceConnectionState(device,
507 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800508 device_address, device_name,
509 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510 if (status != NO_ERROR) {
511 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
512 status);
513 return status;
514 }
515
516 status = setDeviceConnectionState(device,
517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 if (status != NO_ERROR) {
520 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
521 status);
522 return status;
523 }
524
525 return NO_ERROR;
526}
527
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800528status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
529 std::vector<audio_format_t> *formats)
530{
531 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800532 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800533 std::unordered_set<audio_format_t> formatSet;
534 sp<HwModule> primaryModule =
535 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700536 if (primaryModule == nullptr) {
537 ALOGE("%s() unable to get primary module", __func__);
538 return NO_INIT;
539 }
jiabin9a3361e2019-10-01 09:38:30 -0700540 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
541 getAudioDeviceOutAllA2dpSet());
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800542 for (const auto& device : declaredDevices) {
543 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800544 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800545 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800546 return status;
547}
548
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100549DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
550{
551 DeviceVector rxSinkdevices{};
552 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
553 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
554 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
555 auto rxSinkDevice = rxSinkdevices.itemAt(0);
556 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
557 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
558 // retrieve Rx Source device descriptor
559 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
560 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
561
562 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
563 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
564 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
565 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
566 return DeviceVector(rxSinkDevice);
567 }
568 }
569 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
570 // the device returned is not necessarily reachable via this output
571 // (filter later by setOutputDevices())
572 return getNewOutputDevices(mPrimaryOutput, fromCache);
573}
574
575status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
576{
577 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
578 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
579 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
580 }
581 return INVALID_OPERATION;
582}
583
584status_t AudioPolicyManager::updateCallRoutingInternal(
585 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700586{
587 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100588 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700589 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700590 if(!hasPrimaryOutput() ||
591 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100592 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700593 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100594 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100595
Francois Gaffie716e1432019-01-14 16:58:59 +0100596 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100597 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100598 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100599
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100600 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100601 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700602
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200603 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700604 // release TX patch if any
605 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100606 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700607 mCallTxPatch.clear();
608 }
609
François Gaffie9eb18552018-11-05 10:33:26 +0100610 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700611 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100612 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700613 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100614 // retrieve Rx Source and Tx Sink device descriptors
615 sp<DeviceDescriptor> rxSourceDevice =
616 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
617 String8(),
618 AUDIO_FORMAT_DEFAULT);
619 sp<DeviceDescriptor> txSinkDevice =
620 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
621 String8(),
622 AUDIO_FORMAT_DEFAULT);
623
624 // RX and TX Telephony device are declared by Primary Audio HAL
625 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
626 (telephonyRxModule->getHalVersionMajor() >= 3)) {
627 if (rxSourceDevice == 0 || txSinkDevice == 0) {
628 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100629 ALOGE("%s() no telephony Tx and/or RX device", __func__);
630 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100631 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100632 // createAudioPatchInternal now supports both HW / SW bridging
633 createRxPatch = true;
634 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100635 } else {
636 // If the RX device is on the primary HW module, then use legacy routing method for
637 // voice calls via setOutputDevice() on primary output.
638 // Otherwise, create two audio patches for TX and RX path.
639 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
640 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700641 // If the TX device is also on the primary HW module, setOutputDevice() will take care
642 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100643 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
644 (txSinkDevice != 0);
645 }
646 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
647 // Otherwise, create two audio patches for TX and RX path.
648 if (!createRxPatch) {
649 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700650 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200651 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800652 // If the TX device is on the primary HW module but RX device is
653 // on other HW module, SinkMetaData of telephony input should handle it
654 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700656 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100657 // terminate active capture if on the same HW module as the call TX source device
658 // FIXME: would be better to refine to only inputs whose profile connects to the
659 // call TX device but this information is not in the audio patch and logic here must be
660 // symmetric to the one in startInput()
661 for (const auto& activeDesc : mInputs.getActiveInputs()) {
662 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
663 closeActiveClients(activeDesc);
664 }
665 }
François Gaffie9eb18552018-11-05 10:33:26 +0100666 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800667 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 if (waitMs != nullptr) {
669 *waitMs = muteWaitMs;
670 }
671 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800672}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800674sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100675 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700676 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie11d30102018-11-02 16:09:09 +0100678 if (device == nullptr) {
679 return nullptr;
680 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100681
682 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800683 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100684 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800685 addSource(mAvailableInputDevices.getDevice(
686 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800687 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100688 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800689 addSink(mAvailableOutputDevices.getDevice(
690 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800691 }
692
François Gaffieafd4cea2019-11-18 15:50:22 +0100693 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
694 status_t status =
695 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
696 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
697 if (status != NO_ERROR || index < 0) {
698 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
699 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800700 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100701 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800702}
703
Mikhail Naganov100f0122018-11-29 11:22:16 -0800704bool AudioPolicyManager::isDeviceOfModule(
705 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
706 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
707 if (module != 0) {
708 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
709 .indexOf(devDesc) != NAME_NOT_FOUND
710 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
711 .indexOf(devDesc) != NAME_NOT_FOUND;
712 }
713 return false;
714}
715
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200716void AudioPolicyManager::connectTelephonyRxAudioSource()
717{
718 disconnectTelephonyRxAudioSource();
719 const struct audio_port_config source = {
720 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
721 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
722 };
723 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
724 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
725 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
726}
727
728void AudioPolicyManager::disconnectTelephonyRxAudioSource()
729{
730 stopAudioSource(mCallRxSourceClientPort);
731 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
732}
733
Eric Laurente0720872014-03-11 09:30:41 -0700734void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700735{
736 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100737 // store previous phone state for management of sonification strategy below
738 int oldState = mEngine->getPhoneState();
739
740 if (mEngine->setPhoneState(state) != NO_ERROR) {
741 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700742 return;
743 }
François Gaffie2110e042015-03-24 08:41:51 +0100744 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700745 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700746 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700747 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800748 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700749 }
750
François Gaffie2110e042015-03-24 08:41:51 +0100751 /**
752 * Switching to or from incall state or switching between telephony and VoIP lead to force
753 * routing command.
754 */
Eric Laurent74b71512019-11-06 17:21:57 -0800755 bool force = ((isStateInCall(oldState) != isStateInCall(state))
756 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700757
758 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700759 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700760
Eric Laurente552edb2014-03-10 17:42:56 -0700761 int delayMs = 0;
762 if (isStateInCall(state)) {
763 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100764 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
765 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700766 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700767 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700768 // mute media and sonification strategies and delay device switch by the largest
769 // latency of any output where either strategy is active.
770 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100771 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
772 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
773 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700774 (delayMs < (int)desc->latency()*2)) {
775 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700776 }
François Gaffiec005e562018-11-06 15:04:49 +0100777 setStrategyMute(musicStrategy, true, desc);
778 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
779 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
780 nullptr, true /*fromCache*/).types());
781 setStrategyMute(sonificationStrategy, true, desc);
782 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
783 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
784 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700785 }
786 }
787
Eric Laurent87ffa392015-05-22 10:32:38 -0700788 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700789 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100790 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700791 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
793 // force routing command to audio hardware when ending call
794 // even if no device change is needed
795 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
796 rxDevices = mPrimaryOutput->devices();
797 }
798 if (oldState == AUDIO_MODE_IN_CALL) {
799 disconnectTelephonyRxAudioSource();
800 if (mCallTxPatch != 0) {
801 releaseAudioPatchInternal(mCallTxPatch->getHandle());
802 mCallTxPatch.clear();
803 }
804 }
François Gaffie11d30102018-11-02 16:09:09 +0100805 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700807 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700808
809 // reevaluate routing on all outputs in case tracks have been started during the call
810 for (size_t i = 0; i < mOutputs.size(); i++) {
811 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100812 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700813 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100814 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700815 }
816 }
817
Eric Laurente552edb2014-03-10 17:42:56 -0700818 if (isStateInCall(state)) {
819 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700820 // force reevaluating accessibility routing when call starts
821 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700822 }
823
824 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100825 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
826 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700827}
828
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700829audio_mode_t AudioPolicyManager::getPhoneState() {
830 return mEngine->getPhoneState();
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100834 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700835{
François Gaffie2110e042015-03-24 08:41:51 +0100836 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700837 if (config == mEngine->getForceUse(usage)) {
838 return;
839 }
Eric Laurente552edb2014-03-10 17:42:56 -0700840
François Gaffie2110e042015-03-24 08:41:51 +0100841 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
842 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
843 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700844 }
François Gaffie2110e042015-03-24 08:41:51 +0100845 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
846 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
847 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700848
849 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700850 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800851
Eric Laurent22fcda22019-05-17 16:28:47 -0700852 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
853 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
854 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
855 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
856 }
857
Eric Laurentdc462862016-07-19 12:29:53 -0700858 //FIXME: workaround for truncated touch sounds
859 // to be removed when the problem is handled by system UI
860 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700861 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
862 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
863 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700864
865 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100866 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700867}
868
Eric Laurente0720872014-03-11 09:30:41 -0700869void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700870{
871 ALOGV("setSystemProperty() property %s, value %s", property, value);
872}
873
Michael Chana94fbb22018-04-24 14:31:19 +1000874// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
875// search to profiles for direct outputs.
876sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100877 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000878 uint32_t samplingRate,
879 audio_format_t format,
880 audio_channel_mask_t channelMask,
881 audio_output_flags_t flags,
882 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700883{
Michael Chana94fbb22018-04-24 14:31:19 +1000884 if (directOnly) {
885 // only retain flags that will drive the direct output profile selection
886 // if explicitly requested
887 static const uint32_t kRelevantFlags =
888 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700889 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000890 flags =
891 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
892 }
Eric Laurent861a6282015-05-18 15:40:16 -0700893
894 sp<IOProfile> profile;
895
Mikhail Naganovd4120142017-12-06 15:49:22 -0800896 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800897 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100898 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700899 samplingRate, NULL /*updatedSamplingRate*/,
900 format, NULL /*updatedFormat*/,
901 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700902 flags)) {
903 continue;
904 }
905 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100906 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700907 continue;
908 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800909 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700910 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800911 continue;
912 }
Michael Chana94fbb22018-04-24 14:31:19 +1000913 if (!directOnly) return curProfile;
914 // when searching for direct outputs, if several profiles are compatible, give priority
915 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100916 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700917 continue;
918 }
919 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100920 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700921 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923 }
924 }
Eric Laurent861a6282015-05-18 15:40:16 -0700925 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700926}
927
Eric Laurentf4e63452017-11-06 19:31:46 +0000928audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700929{
François Gaffiec005e562018-11-06 15:04:49 +0100930 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800931
932 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
933 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
934 // format, flags, etc. This may result in some discrepancy for functions that utilize
935 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
936 // and AudioSystem::getOutputSamplingRate().
937
François Gaffie11d30102018-11-02 16:09:09 +0100938 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700939 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700940
François Gaffie11d30102018-11-02 16:09:09 +0100941 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
942 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000943 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700944}
945
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700946status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
947 const audio_attributes_t *srcAttr,
948 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700949{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700950 if (srcAttr != NULL) {
951 if (!isValidAttributes(srcAttr)) {
952 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
953 __func__,
954 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
955 srcAttr->tags);
956 return BAD_VALUE;
957 }
958 *dstAttr = *srcAttr;
959 } else {
960 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
961 ALOGE("%s: invalid stream type", __func__);
962 return BAD_VALUE;
963 }
François Gaffiec005e562018-11-06 15:04:49 +0100964 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700965 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700966
967 // Only honor audibility enforced when required. The client will be
968 // forced to reconnect if the forced usage changes.
969 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700970 dstAttr->flags = static_cast<audio_flags_mask_t>(
971 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700972 }
973
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700974 return NO_ERROR;
975}
976
Kevin Rocard153f92d2018-12-18 18:33:28 -0800977status_t AudioPolicyManager::getOutputForAttrInt(
978 audio_attributes_t *resultAttr,
979 audio_io_handle_t *output,
980 audio_session_t session,
981 const audio_attributes_t *attr,
982 audio_stream_type_t *stream,
983 uid_t uid,
984 const audio_config_t *config,
985 audio_output_flags_t *flags,
986 audio_port_handle_t *selectedDeviceId,
987 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -0700988 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -0800989 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700990{
François Gaffiec005e562018-11-06 15:04:49 +0100991 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +0100992 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +0100993 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +0100994 const sp<DeviceDescriptor> requestedDevice =
995 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
996
Eric Laurent8a1095a2019-11-08 14:44:16 -0800997 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700998 status_t status = getAudioAttributes(resultAttr, attr, *stream);
999 if (status != NO_ERROR) {
1000 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001001 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001002 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001003 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001004 }
François Gaffiec005e562018-11-06 15:04:49 +01001005 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001006
François Gaffiec005e562018-11-06 15:04:49 +01001007 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1008 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001009
Kevin Rocard153f92d2018-12-18 18:33:28 -08001010 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1011 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1012 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001013 sp<AudioPolicyMix> primaryMix;
1014 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001015 if (status != OK) {
1016 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001017 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001018
Kevin Rocard153f92d2018-12-18 18:33:28 -08001019 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001020 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001021
1022 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001023 if ((usePrimaryOutputFromPolicyMixes
1024 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001025 && !audio_is_linear_pcm(config->format)) {
1026 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001027 return BAD_VALUE;
1028 }
1029 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001030 sp<DeviceDescriptor> deviceDesc =
1031 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1032 primaryMix->mDeviceAddress,
1033 AUDIO_FORMAT_DEFAULT);
1034 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001035 if (deviceDesc != nullptr
1036 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001037 audio_io_handle_t newOutput;
1038 status = openDirectOutput(
1039 *stream, session, config,
1040 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1041 DeviceVector(deviceDesc), &newOutput);
1042 if (status != NO_ERROR) {
1043 policyDesc = nullptr;
1044 } else {
1045 policyDesc = mOutputs.valueFor(newOutput);
1046 primaryMix->setOutput(policyDesc);
1047 }
1048 }
1049 if (policyDesc != nullptr) {
1050 policyDesc->mPolicyMix = primaryMix;
1051 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001052 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001053
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001054 ALOGV("getOutputForAttr() returns output %d", *output);
1055 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1056 *outputType = API_OUT_MIX_PLAYBACK;
1057 } else {
1058 *outputType = API_OUTPUT_LEGACY;
1059 }
1060 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001061 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001062 }
François Gaffiec005e562018-11-06 15:04:49 +01001063 // Virtual sources must always be dynamicaly or explicitly routed
1064 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1065 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1066 return BAD_VALUE;
1067 }
1068 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1069 // in order to let the choice of the order to future vendor engine
1070 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001071
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001072 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001073 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001074 }
1075
Nadav Barb2f18162018-07-18 13:01:53 +03001076 // Set incall music only if device was explicitly set, and fallback to the device which is
1077 // chosen by the engine if not.
1078 // FIXME: provide a more generic approach which is not device specific and move this back
1079 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001080 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001081 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001082 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001083 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001084 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001085 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001086 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001087 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001088 }
1089 }
1090
François Gaffiec005e562018-11-06 15:04:49 +01001091 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1092 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1093 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001094
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001095 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001096 if (!msdDevices.isEmpty()) {
1097 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001098 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001099 ALOGV("%s() Using MSD devices %s instead of devices %s",
1100 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001101 } else {
1102 *output = AUDIO_IO_HANDLE_NONE;
1103 }
1104 }
1105 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001106 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001107 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001108 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001109 if (*output == AUDIO_IO_HANDLE_NONE) {
1110 return INVALID_OPERATION;
1111 }
Paul McLeanaa981192015-03-21 09:55:15 -07001112
François Gaffiec005e562018-11-06 15:04:49 +01001113 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001114 for (auto &outputDevice : outputDevices) {
1115 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1116 *selectedDeviceId = outputDevice->getId();
1117 break;
1118 }
1119 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001120
Eric Laurent8a1095a2019-11-08 14:44:16 -08001121 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1122 *outputType = API_OUTPUT_TELEPHONY_TX;
1123 } else {
1124 *outputType = API_OUTPUT_LEGACY;
1125 }
1126
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001127 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1128
1129 return NO_ERROR;
1130}
1131
1132status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1133 audio_io_handle_t *output,
1134 audio_session_t session,
1135 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001136 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001137 const audio_config_t *config,
1138 audio_output_flags_t *flags,
1139 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001141 std::vector<audio_io_handle_t> *secondaryOutputs,
1142 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001143{
1144 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1145 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1146 return INVALID_OPERATION;
1147 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001148 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001149 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001150 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001151 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001152 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001153 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001154 const sp<DeviceDescriptor> requestedDevice =
1155 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1156
1157 // Prevent from storing invalid requested device id in clients
1158 const audio_port_handle_t sanitizedRequestedPortId =
1159 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1160 *selectedDeviceId = sanitizedRequestedPortId;
1161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 if (status != NO_ERROR) {
1166 return status;
1167 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001168 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001169 if (secondaryOutputs != nullptr) {
1170 for (auto &secondaryMix : secondaryMixes) {
1171 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1172 if (outputDesc != nullptr &&
1173 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1174 secondaryOutputs->push_back(outputDesc->mIoHandle);
1175 weakSecondaryOutputDescs.push_back(outputDesc);
1176 }
1177 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001178 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001179
Eric Laurent8fc147b2018-07-22 19:13:55 -07001180 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001181 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001182 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001183 };
jiabin4ef93452019-09-10 14:29:54 -07001184 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001185
Eric Laurentc209fe42020-06-05 18:11:23 -07001186 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001187 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001188 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001189 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001190 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001191 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001193 std::move(weakSecondaryOutputDescs),
1194 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001195 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001196
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001197 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1198 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001199
Eric Laurente83b55d2014-11-14 10:06:21 -08001200 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001201}
1202
Eric Laurentc529cf62020-04-17 18:19:10 -07001203status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1204 audio_session_t session,
1205 const audio_config_t *config,
1206 audio_output_flags_t flags,
1207 const DeviceVector &devices,
1208 audio_io_handle_t *output) {
1209
1210 *output = AUDIO_IO_HANDLE_NONE;
1211
1212 // skip direct output selection if the request can obviously be attached to a mixed output
1213 // and not explicitly requested
1214 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1215 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1216 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1217 return NAME_NOT_FOUND;
1218 }
1219
1220 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1221 // This prevents creating an offloaded track and tearing it down immediately after start
1222 // when audioflinger detects there is an active non offloadable effect.
1223 // FIXME: We should check the audio session here but we do not have it in this context.
1224 // This may prevent offloading in rare situations where effects are left active by apps
1225 // in the background.
1226 sp<IOProfile> profile;
1227 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1228 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1229 profile = getProfileForOutput(
1230 devices, config->sample_rate, config->format, config->channel_mask,
1231 flags, true /* directOnly */);
1232 }
1233
1234 if (profile == nullptr) {
1235 return NAME_NOT_FOUND;
1236 }
1237
1238 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1239 for (size_t i = 0; i < mOutputs.size(); i++) {
1240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1241 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1242 // reuse direct output if currently open by the same client
1243 // and configured with same parameters
1244 if ((config->sample_rate == desc->getSamplingRate()) &&
1245 (config->format == desc->getFormat()) &&
1246 (config->channel_mask == desc->getChannelMask()) &&
1247 (session == desc->mDirectClientSession)) {
1248 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001249 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 mOutputs.keyAt(i), session);
1251 *output = mOutputs.keyAt(i);
1252 return NO_ERROR;
1253 }
1254 }
1255 }
1256
1257 if (!profile->canOpenNewIo()) {
1258 return NAME_NOT_FOUND;
1259 }
1260
1261 sp<SwAudioOutputDescriptor> outputDesc =
1262 new SwAudioOutputDescriptor(profile, mpClientInterface);
1263
Michael Chan6fb34492020-12-08 15:44:49 +11001264 // An MSD patch may be using the only output stream that can service this request. Release
1265 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001266 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001267
Eric Laurentf1f22e72021-07-13 14:04:14 +02001268 status_t status =
1269 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001270
1271 // only accept an output with the requested parameters
1272 if (status != NO_ERROR ||
1273 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1274 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1275 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1276 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1277 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1278 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1279 config->channel_mask, outputDesc->getChannelMask());
1280 if (*output != AUDIO_IO_HANDLE_NONE) {
1281 outputDesc->close();
1282 }
1283 // fall back to mixer output if possible when the direct output could not be open
1284 if (audio_is_linear_pcm(config->format) &&
1285 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1286 return NAME_NOT_FOUND;
1287 }
1288 *output = AUDIO_IO_HANDLE_NONE;
1289 return BAD_VALUE;
1290 }
1291 outputDesc->mDirectOpenCount = 1;
1292 outputDesc->mDirectClientSession = session;
1293
1294 addOutput(*output, outputDesc);
1295 mPreviousOutputs = mOutputs;
1296 ALOGV("%s returns new direct output %d", __func__, *output);
1297 mpClientInterface->onAudioPortListUpdate();
1298 return NO_ERROR;
1299}
1300
François Gaffie11d30102018-11-02 16:09:09 +01001301audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1302 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001303 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001304 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001305 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001306 audio_output_flags_t *flags,
1307 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001308{
Andy Hungc88b0642018-04-27 15:42:35 -07001309 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001310
jiabine375d412019-02-26 12:54:53 -08001311 // Discard haptic channel mask when forcing muting haptic channels.
1312 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001313 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1314 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001315
Eric Laurente552edb2014-03-10 17:42:56 -07001316 // open a direct output if required by specified parameters
1317 //force direct flag if offload flag is set: offloading implies a direct output stream
1318 // and all common behaviors are driven by checking only the direct flag
1319 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001320 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1321 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001322 }
Nadav Bar766fb022018-01-07 12:18:03 +02001323 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1324 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001325 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001326 // only allow deep buffering for music stream type
1327 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001328 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001329 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001330 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001331 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1332 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001333 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001334 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001335 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001336 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001337 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001338 audio_is_linear_pcm(config->format) &&
1339 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001340 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001341 AUDIO_OUTPUT_FLAG_DIRECT);
1342 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001343 }
Eric Laurente552edb2014-03-10 17:42:56 -07001344
Eric Laurentc529cf62020-04-17 18:19:10 -07001345 audio_config_t directConfig = *config;
1346 directConfig.channel_mask = channelMask;
1347 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1348 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001349 return output;
1350 }
1351
Eric Laurent14cbfca2016-03-17 09:42:16 -07001352 // A request for HW A/V sync cannot fallback to a mixed output because time
1353 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001354 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001355 return AUDIO_IO_HANDLE_NONE;
1356 }
1357
Eric Laurente552edb2014-03-10 17:42:56 -07001358 // ignoring channel mask due to downmix capability in mixer
1359
1360 // open a non direct output
1361
1362 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001363 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001364 // get which output is suitable for the specified stream. The actual
1365 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001366 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001367
Eric Laurent8838a382014-09-08 16:44:28 -07001368 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001369 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001370 output = selectOutput(
1371 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001372 }
François Gaffie11d30102018-11-02 16:09:09 +01001373 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001374 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001375 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001376
Eric Laurente552edb2014-03-10 17:42:56 -07001377 return output;
1378}
1379
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001380sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001381 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1382 mAvailableInputDevices);
1383 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1384}
1385
1386DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1387 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1388 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001389}
1390
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001391const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001392 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001393 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1394 if (msdModule != 0) {
1395 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1396 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1397 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1398 const struct audio_port_config *source = &patch->mPatch.sources[j];
1399 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1400 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001401 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001402 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001403 }
1404 }
1405 }
1406 return msdPatches;
1407}
1408
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001409status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1410 const InputProfileCollection &inputProfiles,
1411 const OutputProfileCollection &outputProfiles,
1412 const sp<DeviceDescriptor> &sourceDevice,
1413 const sp<DeviceDescriptor> &sinkDevice,
1414 AudioProfileVector& sourceProfiles,
1415 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001416 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001417 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 return NO_INIT;
1419 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001420 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001421 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001422 return NO_INIT;
1423 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001424 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001425 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1426 inProfile->supportsDevice(sourceDevice)) {
1427 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001428 }
1429 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001430 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001431 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001432 outProfile->supportsDevice(sinkDevice)) {
1433 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001434 }
1435 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001436 return NO_ERROR;
1437}
1438
1439status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1440 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1441 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1442{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001443 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001444 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1445 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1446 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001447 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001448 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1449 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001450 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001451 }
1452 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1453 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1454 sinkConfig->format = bestSinkConfig.format;
1455 // For encoded streams force direct flag to prevent downstream mixing.
1456 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1457 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001458 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1459 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001460 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001461 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1462 // raw and IEC61937 framed streams.
1463 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1464 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1465 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001466 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1467 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1468 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1469 sourceConfig->format = bestSinkConfig.format;
1470 // Copy input stream directly without any processing (e.g. resampling).
1471 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1472 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1473 if (hwAvSync) {
1474 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1475 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1476 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1477 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1478 }
1479 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1480 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1481 sinkConfig->config_mask |= config_mask;
1482 sourceConfig->config_mask |= config_mask;
1483 return NO_ERROR;
1484}
1485
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001486PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1487 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001488{
1489 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001490 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1491 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1492 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1493 if (deviceModule == nullptr) {
1494 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1495 return patchBuilder;
1496 }
1497 const InputProfileCollection inputProfiles = msdIsSource ?
1498 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1499 const OutputProfileCollection outputProfiles = msdIsSource ?
1500 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1501
1502 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1503 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1504 device : getMsdAudioOutDevices().itemAt(0);
1505 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1506
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001507 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1508 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001509 AudioProfileVector sourceProfiles;
1510 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001511 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1512 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001513 for (auto hwAvSync : { true, false }) {
1514 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1515 sourceProfiles, sinkProfiles) != NO_ERROR) {
1516 continue;
1517 }
1518 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1519 &sinkConfig) == NO_ERROR) {
1520 // Found a matching config. Re-create PatchBuilder with this config.
1521 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1522 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001523 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001524 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001525 " supporting PCM format conversion.", __func__);
1526 return patchBuilder;
1527}
1528
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001529status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001530 DeviceVector devices;
1531 if (outputDevices != nullptr && outputDevices->size() > 0) {
1532 devices.add(*outputDevices);
1533 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001534 // Use media strategy for unspecified output device. This should only
1535 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1536 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001537 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001538 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001539 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001540 }
Michael Chan6fb34492020-12-08 15:44:49 +11001541 std::vector<PatchBuilder> patchesToCreate;
1542 for (auto i = 0u; i < devices.size(); ++i) {
1543 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001544 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001545 }
1546 // Retain only the MSD patches associated with outputDevices request.
1547 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001548 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001549 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1550 auto retainedPatch = false;
1551 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1552 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1553 patchesToRemove.removeItemsAt(i);
1554 retainedPatch = true;
1555 break;
1556 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001557 }
Michael Chan6fb34492020-12-08 15:44:49 +11001558 if (retainedPatch) {
1559 it = patchesToCreate.erase(it);
1560 continue;
1561 }
1562 ++it;
1563 }
1564 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1565 return NO_ERROR;
1566 }
1567 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1568 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001569 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570 }
Michael Chan6fb34492020-12-08 15:44:49 +11001571 status_t status = NO_ERROR;
1572 for (const auto &p : patchesToCreate) {
1573 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1574 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1575 char message[256];
1576 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1577 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1578 currStatus == NO_ERROR ? "Success" : "Error",
1579 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1580 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1581 if (currStatus == NO_ERROR) {
1582 ALOGD("%s", message);
1583 } else {
1584 ALOGE("%s", message);
1585 if (status == NO_ERROR) {
1586 status = currStatus;
1587 }
1588 }
1589 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001590 return status;
1591}
1592
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001593void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1594 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001595 for (size_t i = 0; i < msdPatches.size(); i++) {
1596 const auto& patch = msdPatches[i];
1597 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1598 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1599 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1600 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1601 releaseAudioPatch(patch->getHandle(), mUidCached);
1602 break;
1603 }
1604 }
1605 }
1606}
1607
Eric Laurente0720872014-03-11 09:30:41 -07001608audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001609 audio_output_flags_t flags,
1610 audio_format_t format,
1611 audio_channel_mask_t channelMask,
1612 uint32_t samplingRate,
1613 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001614{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001615 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1616 "%s called with format %#x", __func__, format);
1617
jiabinebb6af42020-06-09 17:31:17 -07001618 // Return the output that haptic-generating attached to when 1) session id is specified,
1619 // 2) haptic-generating effect exists for given session id and 3) the output that
1620 // haptic-generating effect attached to is in given outputs.
1621 if (sessionId != AUDIO_SESSION_NONE) {
1622 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1623 sessionId, FX_IID_HAPTICGENERATOR);
1624 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1625 return hapticGeneratingOutput;
1626 }
1627 }
1628
Eric Laurent16c66dd2019-05-01 17:54:10 -07001629 // Flags disqualifying an output: the match must happen before calling selectOutput()
1630 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1631 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1632
1633 // Flags expressing a functional request: must be honored in priority over
1634 // other criteria
1635 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1636 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1637 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1638 // Flags expressing a performance request: have lower priority than serving
1639 // requested sampling rate or channel mask
1640 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1641 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1642 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1643
1644 const audio_output_flags_t functionalFlags =
1645 (audio_output_flags_t)(flags & kFunctionalFlags);
1646 const audio_output_flags_t performanceFlags =
1647 (audio_output_flags_t)(flags & kPerformanceFlags);
1648
1649 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1650
Eric Laurente552edb2014-03-10 17:42:56 -07001651 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001652 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001653 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001654 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001655 // 2: the output with the highest number of requested functional flags
1656 // 3: the output supporting the exact channel mask
1657 // 4: the output with a higher channel count than requested
1658 // 5: the output with a higher sampling rate than requested
1659 // 6: the output with the highest number of requested performance flags
1660 // 7: the output with the bit depth the closest to the requested one
1661 // 8: the primary output
1662 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001663
Eric Laurent16c66dd2019-05-01 17:54:10 -07001664 // matching criteria values in priority order for best matching output so far
1665 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001666
Eric Laurent16c66dd2019-05-01 17:54:10 -07001667 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1668 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1669 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001670
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001671 for (audio_io_handle_t output : outputs) {
1672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001673 // matching criteria values in priority order for current output
1674 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001675
Eric Laurent16c66dd2019-05-01 17:54:10 -07001676 if (outputDesc->isDuplicated()) {
1677 continue;
1678 }
1679 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1680 continue;
1681 }
Eric Laurent8838a382014-09-08 16:44:28 -07001682
Eric Laurent16c66dd2019-05-01 17:54:10 -07001683 // If haptic channel is specified, use the haptic output if present.
1684 // When using haptic output, same audio format and sample rate are required.
1685 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001686 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001687 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1688 continue;
1689 }
1690 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001691 && format == outputDesc->getFormat()
1692 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 currentMatchCriteria[0] = outputHapticChannelCount;
1694 }
1695
1696 // functional flags match
1697 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1698
1699 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001700 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1701 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001702 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1703 channelCount <= outputChannelCount) {
1704 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001705 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1706 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001708 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001709 currentMatchCriteria[3] = outputChannelCount;
1710 }
1711
1712 // sampling rate match
1713 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001714 samplingRate <= outputDesc->getSamplingRate()) {
1715 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 }
1717
1718 // performance flags match
1719 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1720
1721 // format match
1722 if (format != AUDIO_FORMAT_INVALID) {
1723 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001724 PolicyAudioPort::kFormatDistanceMax -
1725 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001726 }
1727
1728 // primary output match
1729 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1730
1731 // compare match criteria by priority then value
1732 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1733 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1734 bestMatchCriteria = currentMatchCriteria;
1735 bestOutput = output;
1736
1737 std::stringstream result;
1738 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1739 std::ostream_iterator<int>(result, " "));
1740 ALOGV("%s new bestOutput %d criteria %s",
1741 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001742 }
1743 }
1744
Eric Laurent16c66dd2019-05-01 17:54:10 -07001745 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001746}
1747
Eric Laurent8fc147b2018-07-22 19:13:55 -07001748status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001749{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001750 ALOGV("%s portId %d", __FUNCTION__, portId);
1751
1752 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1753 if (outputDesc == 0) {
1754 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001755 return BAD_VALUE;
1756 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001757 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001758
Eric Laurent8fc147b2018-07-22 19:13:55 -07001759 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001760 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001761
Eric Laurent733ce942017-12-07 12:18:25 -08001762 status_t status = outputDesc->start();
1763 if (status != NO_ERROR) {
1764 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001765 }
1766
Eric Laurent97ac8712018-07-27 18:59:02 -07001767 uint32_t delayMs;
1768 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001769
1770 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001771 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001772 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001773 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001774 if (delayMs != 0) {
1775 usleep(delayMs * 1000);
1776 }
1777
1778 return status;
1779}
1780
Eric Laurent97ac8712018-07-27 18:59:02 -07001781status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1782 const sp<TrackClientDescriptor>& client,
1783 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001784{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001785 // cannot start playback of STREAM_TTS if any other output is being used
1786 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001787
1788 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001789 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001790 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001791 auto clientStrategy = client->strategy();
1792 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001793 if (stream == AUDIO_STREAM_TTS) {
1794 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001795 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001796 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001797 return INVALID_OPERATION;
1798 } else {
1799 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1800 }
1801 } else {
1802 // some playback other than beacon starts
1803 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1804 }
1805
Eric Laurent77305a62016-07-25 16:39:22 -07001806 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001807 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001808 bool force = !outputDesc->isActive() &&
1809 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001810
François Gaffie11d30102018-11-02 16:09:09 +01001811 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001812 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001813 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001814 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001815 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001816 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001817 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001818 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001819 } else {
1820 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001821 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001822 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1823 AUDIO_FORMAT_DEFAULT);
1824 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1825 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001826 }
1827
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001828 // requiresMuteCheck is false when we can bypass mute strategy.
1829 // It covers a common case when there is no materially active audio
1830 // and muting would result in unnecessary delay and dropped audio.
1831 const uint32_t outputLatencyMs = outputDesc->latency();
1832 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1833
Eric Laurente552edb2014-03-10 17:42:56 -07001834 // increment usage count for this stream on the requested output:
1835 // NOTE that the usage count is the same for duplicated output and hardware output which is
1836 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001837 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001838
1839 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001840 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1841 client->isPreferredDeviceForExclusiveUse()) {
1842 // Preferred device may be exclusive, use only if no other active clients on this output
1843 devices = DeviceVector(
1844 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1845 } else {
1846 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1847 }
François Gaffie11d30102018-11-02 16:09:09 +01001848 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001849 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001850 }
1851 }
Eric Laurente552edb2014-03-10 17:42:56 -07001852
François Gaffiec005e562018-11-06 15:04:49 +01001853 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001854 selectOutputForMusicEffects();
1855 }
1856
François Gaffie1c878552018-11-22 16:53:21 +01001857 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001858 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001859 if (devices.isEmpty()) {
1860 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001861 }
François Gaffiec005e562018-11-06 15:04:49 +01001862 bool shouldWait =
1863 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1864 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1865 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001866 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001867 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001868 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001869 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001870 // An output has a shared device if
1871 // - managed by the same hw module
1872 // - supports the currently selected device
1873 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001874 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001875
Eric Laurent77305a62016-07-25 16:39:22 -07001876 // force a device change if any other output is:
1877 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001878 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001879 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001880 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001881 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001882 // change the device currently selected by the other output.
1883 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001884 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001885 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001886 force = true;
1887 }
1888 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001889 // a notification so that audio focus effect can propagate, or that a mute/unmute
1890 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001891 const uint32_t latencyMs = desc->latency();
1892 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1893
1894 if (shouldWait && isActive && (waitMs < latencyMs)) {
1895 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001896 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001897
1898 // Require mute check if another output is on a shared device
1899 // and currently active to have proper drain and avoid pops.
1900 // Note restoring AudioTracks onto this output needs to invoke
1901 // a volume ramp if there is no mute.
1902 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001903 }
1904 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001905
1906 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001907 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001908
Eric Laurente552edb2014-03-10 17:42:56 -07001909 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001910 auto &curves = getVolumeCurves(client->attributes());
1911 checkAndSetVolume(curves, client->volumeSource(),
1912 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001913 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001914 outputDesc->devices().types(), 0 /*delay*/,
1915 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001916
1917 // update the outputs if starting an output with a stream that can affect notification
1918 // routing
1919 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001920
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001921 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001922 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001923 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1924 }
Eric Laurentdc462862016-07-19 12:29:53 -07001925
1926 if (waitMs > muteWaitMs) {
1927 *delayMs = waitMs - muteWaitMs;
1928 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001929
1930 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1931 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1932 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1933 // change occurs after the MixerThread starts and causes a stream volume
1934 // glitch.
1935 //
1936 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001937 }
Eric Laurentdc462862016-07-19 12:29:53 -07001938
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001939 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001940 mEngine->getForceUse(
1941 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001942 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001943 }
1944
Eric Laurent97ac8712018-07-27 18:59:02 -07001945 // Automatically enable the remote submix input when output is started on a re routing mix
1946 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001947 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1948 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001949 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1950 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1951 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001952 "remote-submix",
1953 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001954 }
1955
Eric Laurente552edb2014-03-10 17:42:56 -07001956 return NO_ERROR;
1957}
1958
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001960{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001961 ALOGV("%s portId %d", __FUNCTION__, portId);
1962
1963 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1964 if (outputDesc == 0) {
1965 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001966 return BAD_VALUE;
1967 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001968 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001969
Eric Laurent97ac8712018-07-27 18:59:02 -07001970 ALOGV("stopOutput() output %d, stream %d, session %d",
1971 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001972
Eric Laurent97ac8712018-07-27 18:59:02 -07001973 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001974
Eric Laurent733ce942017-12-07 12:18:25 -08001975 if (status == NO_ERROR ) {
1976 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001977 }
1978 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001979}
1980
Eric Laurent97ac8712018-07-27 18:59:02 -07001981status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1982 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001983{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001984 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001985 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001986 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07001987
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001988 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1989
François Gaffie1c878552018-11-22 16:53:21 +01001990 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1991 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001992 // Automatically disable the remote submix input when output is stopped on a
1993 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001994 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07001995 if (isSingleDeviceType(
1996 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001997 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001998 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001999 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2000 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002001 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002002 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002003 }
2004 }
2005 bool forceDeviceUpdate = false;
2006 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002007 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002008 forceDeviceUpdate = true;
2009 }
2010
Eric Laurente552edb2014-03-10 17:42:56 -07002011 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002012 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002013
Eric Laurente552edb2014-03-10 17:42:56 -07002014 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002015 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002016 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002017 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002018 // delay the device switch by twice the latency because stopOutput() is executed when
2019 // the track stop() command is received and at that time the audio track buffer can
2020 // still contain data that needs to be drained. The latency only covers the audio HAL
2021 // and kernel buffers. Also the latency does not always include additional delay in the
2022 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002023 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002024
2025 // force restoring the device selection on other active outputs if it differs from the
2026 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002027 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002028 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002029 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002030 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002031 desc->isActive() &&
2032 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002033 (newDevices != desc->devices())) {
2034 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2035 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002036
François Gaffie11d30102018-11-02 16:09:09 +01002037 setOutputDevices(desc, newDevices2, force, delayMs);
2038
Eric Laurent57de36c2016-09-28 16:59:11 -07002039 // re-apply device specific volume if not done by setOutputDevice()
2040 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002041 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002042 }
Eric Laurente552edb2014-03-10 17:42:56 -07002043 }
2044 }
2045 // update the outputs if stopping one with a stream that can affect notification routing
2046 handleNotificationRoutingForStream(stream);
2047 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002048
2049 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2050 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002051 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002052 }
2053
François Gaffiec005e562018-11-06 15:04:49 +01002054 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002055 selectOutputForMusicEffects();
2056 }
Eric Laurente552edb2014-03-10 17:42:56 -07002057 return NO_ERROR;
2058 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002059 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002060 return INVALID_OPERATION;
2061 }
2062}
2063
jiabinbce0c1d2020-10-05 11:20:18 -07002064bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002065{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002066 ALOGV("%s portId %d", __FUNCTION__, portId);
2067
2068 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2069 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002070 // If an output descriptor is closed due to a device routing change,
2071 // then there are race conditions with releaseOutput from tracks
2072 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2073 // destroyed shortly thereafter.
2074 //
2075 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002076 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002077 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002078 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002079
2080 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002081
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302082 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2083 if (outputDesc->isClientActive(client)) {
2084 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2085 stopOutput(portId);
2086 }
2087
Eric Laurent8fc147b2018-07-22 19:13:55 -07002088 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2089 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002090 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002091 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002092 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002093 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002094 if (--outputDesc->mDirectOpenCount == 0) {
2095 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002096 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002097 }
2098 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302099
Andy Hung39efb7a2018-09-26 15:39:28 -07002100 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002101 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2102 // The output is pending reopened to query dynamic profiles and
2103 // there is no active clients
2104 closeOutput(outputDesc->mIoHandle);
2105 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2106 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2107 if (newOutputDesc == nullptr) {
2108 ALOGE("%s failed to open output", __func__);
2109 }
2110 return true;
2111 }
2112 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002113}
2114
Eric Laurentcaf7f482014-11-25 17:50:47 -08002115status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2116 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002117 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002118 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002119 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002120 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002121 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002122 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002123 input_type_t *inputType,
2124 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002125{
François Gaffiec005e562018-11-06 15:04:49 +01002126 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2127 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2128 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002129
Eric Laurentad2e7b92017-09-14 20:06:42 -07002130 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002131 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002132 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002133 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002134 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002135 sp<AudioInputDescriptor> inputDesc;
2136 sp<RecordClientDescriptor> clientDesc;
2137 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002138 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002139 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002140
2141 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2142 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2143 return INVALID_OPERATION;
2144 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002145
Francois Gaffie716e1432019-01-14 16:58:59 +01002146 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2147 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002148 }
2149
Paul McLean466dc8e2015-04-17 13:15:36 -06002150 // Explicit routing?
François Gaffie11d30102018-11-02 16:09:09 +01002151 sp<DeviceDescriptor> explicitRoutingDevice =
2152 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002153
Eric Laurentad2e7b92017-09-14 20:06:42 -07002154 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2155 // possible
2156 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2157 *input != AUDIO_IO_HANDLE_NONE) {
2158 ssize_t index = mInputs.indexOfKey(*input);
2159 if (index < 0) {
2160 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2161 status = BAD_VALUE;
2162 goto error;
2163 }
2164 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 RecordClientVector clients = inputDesc->getClientsForSession(session);
2166 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002167 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2168 status = BAD_VALUE;
2169 goto error;
2170 }
2171 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2172 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002173 // corresponds to a new client and is only permitted from the same UID.
2174 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002175 if (clients.size() > 1) {
2176 for (const auto& client : clients) {
2177 // The client map is ordered by key values (portId) and portIds are allocated
2178 // incrementaly. So the first client in this list is the one opened by audio flinger
2179 // when the mmap stream is created and should be ignored as it does not correspond
2180 // to an actual client
2181 if (client == *clients.cbegin()) {
2182 continue;
2183 }
2184 if (uid != client->uid() && !client->isSilenced()) {
2185 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2186 uid, client->portId(), client->uid());
2187 status = INVALID_OPERATION;
2188 goto error;
2189 }
Eric Laurent331679c2018-04-16 17:03:16 -07002190 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002191 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002192 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002193 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002194
Eric Laurentfecbceb2021-02-09 14:46:43 +01002195 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002196 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002197 }
2198
2199 *input = AUDIO_IO_HANDLE_NONE;
2200 *inputType = API_INPUT_INVALID;
2201
Francois Gaffie716e1432019-01-14 16:58:59 +01002202 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002203
Francois Gaffie716e1432019-01-14 16:58:59 +01002204 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2205 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2206 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002207 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002208 ALOGW("%s could not find input mix for attr %s",
2209 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002210 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002211 }
jiabinc1de2df2019-05-07 14:26:40 -07002212 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2213 String8(attr->tags + strlen("addr=")),
2214 AUDIO_FORMAT_DEFAULT);
2215 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002216 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002217 __func__, attributes.source, attributes.tags);
2218 status = BAD_VALUE;
2219 goto error;
2220 }
2221
Kevin Rocard25f9b052019-02-27 15:08:54 -08002222 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2223 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2224 } else {
2225 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2226 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002227 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002228 if (explicitRoutingDevice != nullptr) {
2229 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002230 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002231 // Prevent from storing invalid requested device id in clients
2232 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002233 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002234 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2235 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002236 }
François Gaffie11d30102018-11-02 16:09:09 +01002237 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002238 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002239 status = BAD_VALUE;
2240 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002241 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002242 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2243 *inputType = API_INPUT_MIX_CAPTURE;
2244 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002245 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2246 // there is an external policy, but this input is attached to a mix of recorders,
2247 // meaning it receives audio injected into the framework, so the recorder doesn't
2248 // know about it and is therefore considered "legacy"
2249 *inputType = API_INPUT_LEGACY;
2250 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002251 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002252 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002253 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002254 } else {
2255 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002256 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002257
Eric Laurent599c7582015-12-07 18:05:55 -08002258 }
2259
François Gaffiec005e562018-11-06 15:04:49 +01002260 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002261 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002262 status = INVALID_OPERATION;
2263 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002264 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002265
Eric Laurent8f42ea12018-08-08 09:08:25 -07002266exit:
2267
François Gaffiec005e562018-11-06 15:04:49 +01002268 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2269 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002270
Francois Gaffie716e1432019-01-14 16:58:59 +01002271 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002272 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002273 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002274
Mikhail Naganov2996f672019-04-18 12:29:59 -07002275 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002276 requestedDeviceId, attributes.source, flags,
2277 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002279 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002280
2281 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2282 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002283
Eric Laurent599c7582015-12-07 18:05:55 -08002284 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002285
2286error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002287 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002288}
2289
2290
François Gaffie11d30102018-11-02 16:09:09 +01002291audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002292 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002293 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002294 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002295 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002296 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002297{
2298 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002299 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002300 bool isSoundTrigger = false;
2301
François Gaffiec005e562018-11-06 15:04:49 +01002302 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002303 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2304 if (index >= 0) {
2305 input = mSoundTriggerSessions.valueFor(session);
2306 isSoundTrigger = true;
2307 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2308 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2309 } else {
2310 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002311 }
François Gaffiec005e562018-11-06 15:04:49 +01002312 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002313 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002314 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002315 }
2316
Andy Hungf129b032015-04-07 13:45:50 -07002317 // find a compatible input profile (not necessarily identical in parameters)
2318 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002319 // sampling rate and flags may be updated by getInputProfile
2320 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2321 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002322 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002323 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002324 audio_input_flags_t profileFlags = flags;
2325 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002326 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002327 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002328 profileFlags);
2329 if (profile != 0) {
2330 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002331 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2332 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002333 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2334 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2335 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002336 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2337 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2338 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002339 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002340 }
Eric Laurente552edb2014-03-10 17:42:56 -07002341 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002342 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002343 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002344 if (samplingRate == 0) {
2345 samplingRate = profileSamplingRate;
2346 }
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Eric Laurent322b4d22015-04-03 15:57:54 -07002348 if (profile->getModuleHandle() == 0) {
2349 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002350 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002351 }
2352
Eric Laurentec376dc2021-04-08 20:41:22 +02002353 // Reuse an already opened input if a client with the same session ID already exists
2354 // on that input
2355 for (size_t i = 0; i < mInputs.size(); i++) {
2356 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2357 if (desc->mProfile != profile) {
2358 continue;
2359 }
2360 RecordClientVector clients = desc->clientsList();
2361 for (const auto &client : clients) {
2362 if (session == client->session()) {
2363 return desc->mIoHandle;
2364 }
2365 }
2366 }
2367
Eric Laurent3974e3b2017-12-07 17:58:43 -08002368 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002369 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002370 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002371 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002372 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002373 continue;
2374 }
2375 // if sound trigger, reuse input if used by other sound trigger on same session
2376 // else
2377 // reuse input if active client app is not in IDLE state
2378 //
2379 RecordClientVector clients = desc->clientsList();
2380 bool doClose = false;
2381 for (const auto& client : clients) {
2382 if (isSoundTrigger != client->isSoundTrigger()) {
2383 continue;
2384 }
2385 if (client->isSoundTrigger()) {
2386 if (session == client->session()) {
2387 return desc->mIoHandle;
2388 }
2389 continue;
2390 }
2391 if (client->active() && client->appState() != APP_STATE_IDLE) {
2392 return desc->mIoHandle;
2393 }
2394 doClose = true;
2395 }
2396 if (doClose) {
2397 closeInput(desc->mIoHandle);
2398 } else {
2399 i++;
2400 }
2401 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002402 }
2403
Eric Laurentfe231122017-11-17 17:48:06 -08002404 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002405
Eric Laurentfe231122017-11-17 17:48:06 -08002406 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2407 lConfig.sample_rate = profileSamplingRate;
2408 lConfig.channel_mask = profileChannelMask;
2409 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002410
François Gaffie11d30102018-11-02 16:09:09 +01002411 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002412
2413 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002414 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002415 (profileSamplingRate != lConfig.sample_rate) ||
2416 !audio_formats_match(profileFormat, lConfig.format) ||
2417 (profileChannelMask != lConfig.channel_mask)) {
2418 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002419 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002420 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002421 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002422 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002423 }
Eric Laurent599c7582015-12-07 18:05:55 -08002424 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002425 }
2426
Eric Laurentc722f302014-12-10 11:21:49 -08002427 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002428
Eric Laurent599c7582015-12-07 18:05:55 -08002429 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002430 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002431
Eric Laurent599c7582015-12-07 18:05:55 -08002432 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002433}
2434
Eric Laurent4eb58f12018-12-07 16:41:02 -08002435status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002436{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002437 ALOGV("%s portId %d", __FUNCTION__, portId);
2438
2439 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2440 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002441 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002442 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002443 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002444 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002445 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002446 if (client->active()) {
2447 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2448 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002449 }
2450
Eric Laurent8f42ea12018-08-08 09:08:25 -07002451 audio_session_t session = client->session();
2452
Eric Laurent4eb58f12018-12-07 16:41:02 -08002453 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002454
Eric Laurent4eb58f12018-12-07 16:41:02 -08002455 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002456
Eric Laurent4eb58f12018-12-07 16:41:02 -08002457 status_t status = inputDesc->start();
2458 if (status != NO_ERROR) {
2459 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002460 }
Eric Laurente552edb2014-03-10 17:42:56 -07002461
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002462 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002463 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002464 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002465
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 // indicate active capture to sound trigger service if starting capture from a mic on
2467 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002468 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002469 if (device != nullptr) {
2470 status = setInputDevice(input, device, true /* force */);
2471 } else {
2472 ALOGW("%s no new input device can be found for descriptor %d",
2473 __FUNCTION__, inputDesc->getId());
2474 status = BAD_VALUE;
2475 }
Eric Laurente552edb2014-03-10 17:42:56 -07002476
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002477 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002478 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002480 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002481 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2482 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002483 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002484 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002485
François Gaffie11d30102018-11-02 16:09:09 +01002486 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2487 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002488 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002489 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002491
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 // automatically enable the remote submix output when input is started if not
2493 // used by a policy mix of type MIX_TYPE_RECORDERS
2494 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002495 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002496 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002497 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002498 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002499 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2500 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002501 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 if (address != "") {
2503 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2504 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002505 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002506 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002507 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002508 } else if (status != NO_ERROR) {
2509 // Restore client activity state.
2510 inputDesc->setClientActive(client, false);
2511 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002512 }
2513
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002514 ALOGV("%s input %d source = %d status = %d exit",
2515 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002516
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002517 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002518}
2519
Eric Laurent8fc147b2018-07-22 19:13:55 -07002520status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002521{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002522 ALOGV("%s portId %d", __FUNCTION__, portId);
2523
2524 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2525 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002526 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002527 return BAD_VALUE;
2528 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002529 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002530 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531 if (!client->active()) {
2532 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002533 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002534 }
Carter Hsue6139d52021-07-08 10:30:20 +08002535 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002536 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002537
Eric Laurent8f42ea12018-08-08 09:08:25 -07002538 inputDesc->stop();
2539 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002540 auto current_source = inputDesc->source();
2541 setInputDevice(input, getNewInputDevice(inputDesc),
2542 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002543 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002544 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002545 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002546 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002547 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2548 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002549 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002550 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002551
2552 // automatically disable the remote submix output when input is stopped if not
2553 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002554 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002555 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002556 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002557 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002558 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2559 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002560 }
2561 if (address != "") {
2562 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2563 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002564 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002565 }
2566 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002567 resetInputDevice(input);
2568
2569 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2570 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002571 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2572 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002573 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002574 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002575 }
2576 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002577 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002578 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002579}
2580
Eric Laurent8fc147b2018-07-22 19:13:55 -07002581void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002582{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002583 ALOGV("%s portId %d", __FUNCTION__, portId);
2584
2585 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2586 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002587 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002588 return;
2589 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002590 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002591 audio_io_handle_t input = inputDesc->mIoHandle;
2592
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002594
Andy Hung39efb7a2018-09-26 15:39:28 -07002595 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002596
Andy Hung39efb7a2018-09-26 15:39:28 -07002597 if (inputDesc->getClientCount() > 0) {
2598 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002599 return;
2600 }
2601
Eric Laurent05b90f82014-08-27 15:32:29 -07002602 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002603 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002604 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002605}
2606
Eric Laurent8f42ea12018-08-08 09:08:25 -07002607void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002609 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002610
2611 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002612 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002613 }
2614}
2615
Eric Laurent8f42ea12018-08-08 09:08:25 -07002616void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2617{
2618 stopInput(portId);
2619 releaseInput(portId);
2620}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002621
Eric Laurent0dd51852019-04-19 18:18:58 -07002622void AudioPolicyManager::checkCloseInputs() {
2623 // After connecting or disconnecting an input device, close input if:
2624 // - it has no client (was just opened to check profile) OR
2625 // - none of its supported devices are connected anymore OR
2626 // - one of its clients cannot be routed to one of its supported
2627 // devices anymore. Otherwise update device selection
2628 std::vector<audio_io_handle_t> inputsToClose;
2629 for (size_t i = 0; i < mInputs.size(); i++) {
2630 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2631 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002632 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002633 inputsToClose.push_back(mInputs.keyAt(i));
2634 } else {
2635 bool close = false;
2636 for (const auto& client : input->clientsList()) {
2637 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002638 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002639 if (!input->supportedDevices().contains(device)) {
2640 close = true;
2641 break;
2642 }
2643 }
2644 if (close) {
2645 inputsToClose.push_back(mInputs.keyAt(i));
2646 } else {
2647 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2648 }
2649 }
2650 }
2651
2652 for (const audio_io_handle_t handle : inputsToClose) {
2653 ALOGV("%s closing input %d", __func__, handle);
2654 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002655 }
Eric Laurentd4692962014-05-05 18:13:44 -07002656}
2657
François Gaffie251c7f02018-11-07 10:41:08 +01002658void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002659{
2660 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002661 if (indexMin < 0 || indexMax < 0) {
2662 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2663 return;
2664 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002665 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002666
2667 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002668 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2669 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002670 continue;
2671 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002672 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002673 }
Eric Laurente552edb2014-03-10 17:42:56 -07002674}
2675
Eric Laurente0720872014-03-11 09:30:41 -07002676status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002677 int index,
2678 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002679{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002680 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002681 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2682 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2683 return NO_ERROR;
2684 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002685 ALOGV("%s: stream %s attributes=%s", __func__,
2686 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002687 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002688}
2689
Eric Laurente0720872014-03-11 09:30:41 -07002690status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002691 int *index,
2692 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002693{
François Gaffiec005e562018-11-06 15:04:49 +01002694 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2695 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002696 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002697 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002698 deviceTypes = mEngine->getOutputDevicesForStream(
2699 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002700 }
jiabin9a3361e2019-10-01 09:38:30 -07002701 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002702}
2703
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002704status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002705 int index,
2706 audio_devices_t device)
2707{
2708 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002709 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2710 if (group == VOLUME_GROUP_NONE) {
2711 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002712 return BAD_VALUE;
2713 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002714 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002715 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002716 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002717 VolumeSource vs = toVolumeSource(group);
2718 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2719
2720 status = setVolumeCurveIndex(index, device, curves);
2721 if (status != NO_ERROR) {
2722 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2723 return status;
2724 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002725
jiabin9a3361e2019-10-01 09:38:30 -07002726 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002727 auto curCurvAttrs = curves.getAttributes();
2728 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2729 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002730 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002731 } else if (!curves.getStreamTypes().empty()) {
2732 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002733 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002734 } else {
2735 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2736 return BAD_VALUE;
2737 }
jiabin9a3361e2019-10-01 09:38:30 -07002738 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2739 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002740
François Gaffiecfe17322018-11-07 13:41:29 +01002741 // update volume on all outputs and streams matching the following:
2742 // - The requested stream (or a stream matching for volume control) is active on the output
2743 // - The device (or devices) selected by the engine for this stream includes
2744 // the requested device
2745 // - For non default requested device, currently selected device on the output is either the
2746 // requested device or one of the devices selected by the engine for this stream
2747 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2748 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002749 for (size_t i = 0; i < mOutputs.size(); i++) {
2750 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002751 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002752
jiabin9a3361e2019-10-01 09:38:30 -07002753 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2754 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002755 }
François Gaffieed91f582020-01-31 10:35:37 +01002756 if (!(desc->isActive(vs) || isInCall())) {
2757 continue;
2758 }
2759 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2760 curDevices.find(device) == curDevices.end()) {
2761 continue;
2762 }
2763 bool applyVolume = false;
2764 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2765 curSrcDevices.insert(device);
2766 applyVolume = (curSrcDevices.find(
2767 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2768 } else {
2769 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2770 }
2771 if (!applyVolume) {
2772 continue; // next output
2773 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002774 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2775 // If a higher priority strategy is active, and the output is routed to a device with a
2776 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002777 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002778 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002779 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2780 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2781 false /*preferredDevice*/);
2782 if (activeClients.empty()) {
2783 continue;
2784 }
2785 bool isPreempted = false;
2786 bool isHigherPriority = productStrategy < strategy;
2787 for (const auto &client : activeClients) {
2788 if (isHigherPriority && (client->volumeSource() != vs)) {
2789 ALOGV("%s: Strategy=%d (\nrequester:\n"
2790 " group %d, volumeGroup=%d attributes=%s)\n"
2791 " higher priority source active:\n"
2792 " volumeGroup=%d attributes=%s) \n"
2793 " on output %zu, bailing out", __func__, productStrategy,
2794 group, group, toString(attributes).c_str(),
2795 client->volumeSource(), toString(client->attributes()).c_str(), i);
2796 applyVolume = false;
2797 isPreempted = true;
2798 break;
2799 }
2800 // However, continue for loop to ensure no higher prio clients running on output
2801 if (client->volumeSource() == vs) {
2802 applyVolume = true;
2803 }
2804 }
2805 if (isPreempted || applyVolume) {
2806 break;
2807 }
2808 }
2809 if (!applyVolume) {
2810 continue; // next output
2811 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002812 }
François Gaffieed91f582020-01-31 10:35:37 +01002813 //FIXME: workaround for truncated touch sounds
2814 // delayed volume change for system stream to be removed when the problem is
2815 // handled by system UI
2816 status_t volStatus = checkAndSetVolume(
2817 curves, vs, index, desc, curDevices,
2818 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2819 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2820 if (volStatus != NO_ERROR) {
2821 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002822 }
2823 }
François Gaffiecfe17322018-11-07 13:41:29 +01002824 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2825 return status;
2826}
2827
François Gaffieaaac0fd2018-11-22 17:56:39 +01002828status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002829 audio_devices_t device,
2830 IVolumeCurves &volumeCurves)
2831{
2832 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2833 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002834 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2835 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002836 (index > volumeCurves.getVolumeIndexMax())) {
2837 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2838 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2839 return BAD_VALUE;
2840 }
2841 if (!audio_is_output_device(device)) {
2842 return BAD_VALUE;
2843 }
2844
2845 // Force max volume if stream cannot be muted
2846 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2847
François Gaffieaaac0fd2018-11-22 17:56:39 +01002848 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002849 volumeCurves.addCurrentVolumeIndex(device, index);
2850 return NO_ERROR;
2851}
2852
2853status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2854 int &index,
2855 audio_devices_t device)
2856{
2857 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2858 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002859 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002860 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002861 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2862 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002863 }
jiabin9a3361e2019-10-01 09:38:30 -07002864 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002865}
2866
2867status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2868 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002869 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002870{
jiabin9a3361e2019-10-01 09:38:30 -07002871 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002872 return BAD_VALUE;
2873 }
jiabin9a3361e2019-10-01 09:38:30 -07002874 index = curves.getVolumeIndex(deviceTypes);
2875 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002876 return NO_ERROR;
2877}
2878
2879status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2880 int &index)
2881{
2882 index = getVolumeCurves(attr).getVolumeIndexMin();
2883 return NO_ERROR;
2884}
2885
2886status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2887 int &index)
2888{
2889 index = getVolumeCurves(attr).getVolumeIndexMax();
2890 return NO_ERROR;
2891}
2892
Eric Laurent36829f92017-04-07 19:04:42 -07002893audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002894{
2895 // select one output among several suitable for global effects.
2896 // The priority is as follows:
2897 // 1: An offloaded output. If the effect ends up not being offloadable,
2898 // AudioFlinger will invalidate the track and the offloaded output
2899 // will be closed causing the effect to be moved to a PCM output.
2900 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002901 // 3: The primary output
2902 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002903
François Gaffiec005e562018-11-06 15:04:49 +01002904 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2905 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002906 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002907
Eric Laurent36829f92017-04-07 19:04:42 -07002908 if (outputs.size() == 0) {
2909 return AUDIO_IO_HANDLE_NONE;
2910 }
Eric Laurente552edb2014-03-10 17:42:56 -07002911
Eric Laurent36829f92017-04-07 19:04:42 -07002912 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2913 bool activeOnly = true;
2914
2915 while (output == AUDIO_IO_HANDLE_NONE) {
2916 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2917 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2918 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2919
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002920 for (audio_io_handle_t output : outputs) {
2921 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002922 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002923 continue;
2924 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002925 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2926 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002927 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002928 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002929 }
2930 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002931 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002932 }
2933 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002934 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002935 }
2936 }
2937 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2938 output = outputOffloaded;
2939 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2940 output = outputDeepBuffer;
2941 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2942 output = outputPrimary;
2943 } else {
2944 output = outputs[0];
2945 }
2946 activeOnly = false;
2947 }
2948
2949 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002950 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002951 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2952 mMusicEffectOutput = output;
2953 }
2954
2955 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002956 return output;
2957}
2958
Eric Laurent36829f92017-04-07 19:04:42 -07002959audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2960{
2961 return selectOutputForMusicEffects();
2962}
2963
Eric Laurente0720872014-03-11 09:30:41 -07002964status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002965 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002966 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002967 int session,
2968 int id)
2969{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002970 if (session != AUDIO_SESSION_DEVICE) {
2971 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002972 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002973 index = mInputs.indexOfKey(io);
2974 if (index < 0) {
2975 ALOGW("registerEffect() unknown io %d", io);
2976 return INVALID_OPERATION;
2977 }
Eric Laurente552edb2014-03-10 17:42:56 -07002978 }
2979 }
François Gaffiec005e562018-11-06 15:04:49 +01002980 return mEffects.registerEffect(desc, io, session, id,
2981 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2982 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002983}
2984
Eric Laurentc241b0d2018-11-28 09:08:49 -08002985status_t AudioPolicyManager::unregisterEffect(int id)
2986{
2987 if (mEffects.getEffect(id) == nullptr) {
2988 return INVALID_OPERATION;
2989 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08002990 if (mEffects.isEffectEnabled(id)) {
2991 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2992 setEffectEnabled(id, false);
2993 }
2994 return mEffects.unregisterEffect(id);
2995}
2996
2997status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2998{
2999 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3000 if (effect == nullptr) {
3001 return INVALID_OPERATION;
3002 }
3003
3004 status_t status = mEffects.setEffectEnabled(id, enabled);
3005 if (status == NO_ERROR) {
3006 mInputs.trackEffectEnabled(effect, enabled);
3007 }
3008 return status;
3009}
3010
Eric Laurent6c796322019-04-09 14:13:17 -07003011
3012status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3013{
3014 mEffects.moveEffects(ids, io);
3015 return NO_ERROR;
3016}
3017
Eric Laurentc75307b2015-03-17 15:29:32 -07003018bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3019{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003020 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003021}
3022
3023bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3024{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003025 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003026}
3027
Eric Laurente0720872014-03-11 09:30:41 -07003028bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003029{
3030 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003031 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003032 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003033 return true;
3034 }
3035 }
3036 return false;
3037}
3038
Eric Laurent275e8e92014-11-30 15:14:47 -08003039// Register a list of custom mixes with their attributes and format.
3040// When a mix is registered, corresponding input and output profiles are
3041// added to the remote submix hw module. The profile contains only the
3042// parameters (sampling rate, format...) specified by the mix.
3043// The corresponding input remote submix device is also connected.
3044//
3045// When a remote submix device is connected, the address is checked to select the
3046// appropriate profile and the corresponding input or output stream is opened.
3047//
3048// When capture starts, getInputForAttr() will:
3049// - 1 look for a mix matching the address passed in attribtutes tags if any
3050// - 2 if none found, getDeviceForInputSource() will:
3051// - 2.1 look for a mix matching the attributes source
3052// - 2.2 if none found, default to device selection by policy rules
3053// At this time, the corresponding output remote submix device is also connected
3054// and active playback use cases can be transferred to this mix if needed when reconnecting
3055// after AudioTracks are invalidated
3056//
3057// When playback starts, getOutputForAttr() will:
3058// - 1 look for a mix matching the address passed in attribtutes tags if any
3059// - 2 if none found, look for a mix matching the attributes usage
3060// - 3 if none found, default to device and output selection by policy rules.
3061
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003062status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003063{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003064 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3065 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003066 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003067 sp<HwModule> rSubmixModule;
3068 // examine each mix's route type
3069 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003070 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003071 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3072 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3073 ALOGE("Unsupported Policy Mix %zu of %zu: "
3074 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3075 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003076 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003077 break;
3078 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003079 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3080 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003081 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003082 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3083 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003084 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003085 rSubmixModule = mHwModules.getModuleFromName(
3086 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3087 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003088 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003089 i);
3090 res = INVALID_OPERATION;
3091 break;
3092 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003093 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003094
Eric Laurent97ac8712018-07-27 18:59:02 -07003095 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003096 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003097 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003098 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003099 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3100 } else {
3101 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3102 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003103 }
François Gaffie036e1e92015-03-19 10:16:24 +01003104
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003105 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003106 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003107 res = INVALID_OPERATION;
3108 break;
3109 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003110 audio_config_t outputConfig = mix.mFormat;
3111 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003112 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3113 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3115 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003116 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003118 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003119 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003120
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003121 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3123 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3124 ALOGE("Failed to set remote submix device available, type %u, address %s",
3125 mix.mDeviceType, address.string());
3126 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003127 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003128 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3129 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003130 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003131 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003132 i, mixes.size(), type, address.string());
3133
3134 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3135 mix.mDeviceType, mix.mDeviceAddress,
3136 String8(), AUDIO_FORMAT_DEFAULT);
3137 if (device == nullptr) {
3138 res = INVALID_OPERATION;
3139 break;
3140 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003141
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003142 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003143 // First try to find an already opened output supporting the device
3144 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003145 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003146
Eric Laurentc529cf62020-04-17 18:19:10 -07003147 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003148 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003149 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3150 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003151 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003152 } else {
3153 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003154 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003155 }
3156 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003157 // If no output found, try to find a direct output profile supporting the device
3158 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3159 sp<HwModule> module = mHwModules[i];
3160 for (size_t j = 0;
3161 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3162 j++) {
3163 sp<IOProfile> profile = module->getOutputProfiles()[j];
3164 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3165 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3166 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3167 address.string());
3168 res = INVALID_OPERATION;
3169 } else {
3170 foundOutput = true;
3171 }
3172 }
3173 }
3174 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003175 if (res != NO_ERROR) {
3176 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003177 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003178 res = INVALID_OPERATION;
3179 break;
3180 } else if (!foundOutput) {
3181 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003182 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003183 res = INVALID_OPERATION;
3184 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003185 } else {
3186 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003187 }
Eric Laurentc722f302014-12-10 11:21:49 -08003188 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003189 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003190 if (res != NO_ERROR) {
3191 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003192 } else if (checkOutputs) {
3193 checkForDeviceAndOutputChanges();
3194 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 }
3196 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003197}
3198
3199status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3200{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003201 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003202 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003203 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003204 sp<HwModule> rSubmixModule;
3205 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003206 for (const auto& mix : mixes) {
3207 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003208
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003209 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003210 rSubmixModule = mHwModules.getModuleFromName(
3211 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3212 if (rSubmixModule == 0) {
3213 res = INVALID_OPERATION;
3214 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003215 }
3216 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003217
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003218 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003219
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003220 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003221 res = INVALID_OPERATION;
3222 continue;
3223 }
3224
Kevin Rocard04ed0462019-05-02 17:53:24 -07003225 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3226 if (getDeviceConnectionState(device, address.string()) ==
3227 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3228 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3229 address.string(), "remote-submix",
3230 AUDIO_FORMAT_DEFAULT);
3231 if (res != OK) {
3232 ALOGE("Error making RemoteSubmix device unavailable for mix "
3233 "with type %d, address %s", device, address.string());
3234 }
3235 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003236 }
jiabin5740f082019-08-19 15:08:30 -07003237 rSubmixModule->removeOutputProfile(address.c_str());
3238 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003239
Kevin Rocard153f92d2018-12-18 18:33:28 -08003240 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003241 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003242 res = INVALID_OPERATION;
3243 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003244 } else {
3245 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003246 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003247 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003248 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003249 if (res == NO_ERROR && checkOutputs) {
3250 checkForDeviceAndOutputChanges();
3251 updateCallAndOutputRouting();
3252 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003253 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003254}
3255
Mikhail Naganov100f0122018-11-29 11:22:16 -08003256void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3257{
3258 size_t i = 0;
3259 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3260 for (const auto& fmt : mManualSurroundFormats) {
3261 if (i++ != 0) dst->append(", ");
3262 std::string sfmt;
3263 FormatConverter::toString(fmt, sfmt);
3264 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3265 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3266 }
3267}
3268
Eric Laurentc529cf62020-04-17 18:19:10 -07003269// Returns true if all devices types match the predicate and are supported by one HW module
3270bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003271 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003272 std::function<bool(audio_devices_t)> predicate,
3273 const char *context) {
3274 for (size_t i = 0; i < devices.size(); i++) {
3275 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003276 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003277 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003278 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003279 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003280 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003281 return false;
3282 }
3283 }
3284 return true;
3285}
3286
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003287status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003288 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003289 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003290 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3291 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003292 }
3293 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003294 if (res != NO_ERROR) {
3295 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3296 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003297 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003298
3299 checkForDeviceAndOutputChanges();
3300 updateCallAndOutputRouting();
3301
3302 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003303}
3304
3305status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3306 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003307 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3308 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003309 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003310 __FUNCTION__, uid);
3311 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003312 }
3313
Eric Laurentc529cf62020-04-17 18:19:10 -07003314 checkForDeviceAndOutputChanges();
3315 updateCallAndOutputRouting();
3316
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003317 return res;
3318}
3319
Eric Laurent2517af32020-11-25 15:31:27 +01003320
jiabin0a488932020-08-07 17:32:40 -07003321status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3322 device_role_t role,
3323 const AudioDeviceTypeAddrVector &devices) {
3324 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3325 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003326
Eric Laurentc529cf62020-04-17 18:19:10 -07003327 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003328 return BAD_VALUE;
3329 }
jiabin0a488932020-08-07 17:32:40 -07003330 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003331 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003332 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3333 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003334 return status;
3335 }
3336
3337 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003338
3339 bool forceVolumeReeval = false;
3340 // FIXME: workaround for truncated touch sounds
3341 // to be removed when the problem is handled by system UI
3342 uint32_t delayMs = 0;
3343 if (strategy == mCommunnicationStrategy) {
3344 forceVolumeReeval = true;
3345 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3346 updateInputRouting();
3347 }
3348 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003349
3350 return NO_ERROR;
3351}
3352
3353void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3354{
3355 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003356 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003357 // Only apply special touch sound delay once
3358 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003359 }
3360 for (size_t i = 0; i < mOutputs.size(); i++) {
3361 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3362 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3363 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3364 // As done in setDeviceConnectionState, we could also fix default device issue by
3365 // preventing the force re-routing in case of default dev that distinguishes on address.
3366 // Let's give back to engine full device choice decision however.
3367 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003368 // Only apply special touch sound delay once
3369 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003370 }
3371 if (forceVolumeReeval && !newDevices.isEmpty()) {
3372 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3373 }
3374 }
3375}
3376
Eric Laurent2517af32020-11-25 15:31:27 +01003377void AudioPolicyManager::updateInputRouting() {
3378 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303379 // Skip for hotword recording as the input device switch
3380 // is handled within sound trigger HAL
3381 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3382 continue;
3383 }
Eric Laurent2517af32020-11-25 15:31:27 +01003384 auto newDevice = getNewInputDevice(activeDesc);
3385 // Force new input selection if the new device can not be reached via current input
3386 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3387 setInputDevice(activeDesc->mIoHandle, newDevice);
3388 } else {
3389 closeInput(activeDesc->mIoHandle);
3390 }
3391 }
3392}
3393
jiabin0a488932020-08-07 17:32:40 -07003394status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3395 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003396{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003397 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003398
jiabin0a488932020-08-07 17:32:40 -07003399 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003400 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003401 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3402 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003403 return status;
3404 }
3405
3406 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003407
3408 bool forceVolumeReeval = false;
3409 // FIXME: workaround for truncated touch sounds
3410 // to be removed when the problem is handled by system UI
3411 uint32_t delayMs = 0;
3412 if (strategy == mCommunnicationStrategy) {
3413 forceVolumeReeval = true;
3414 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3415 updateInputRouting();
3416 }
3417 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003418
3419 return NO_ERROR;
3420}
3421
jiabin0a488932020-08-07 17:32:40 -07003422status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3423 device_role_t role,
3424 AudioDeviceTypeAddrVector &devices) {
3425 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003426}
3427
Jiabin Huang3b98d322020-09-03 17:54:16 +00003428status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3429 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3430 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3431 dumpAudioDeviceTypeAddrVector(devices).c_str());
3432
Mikhail Naganov55773032020-10-01 15:08:13 -07003433 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003434 return BAD_VALUE;
3435 }
3436 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3437 ALOGW_IF(status != NO_ERROR,
3438 "Engine could not set preferred devices %s for audio source %d role %d",
3439 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3440
3441 return status;
3442}
3443
3444status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3445 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3446 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3447 dumpAudioDeviceTypeAddrVector(devices).c_str());
3448
Mikhail Naganov55773032020-10-01 15:08:13 -07003449 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003450 return BAD_VALUE;
3451 }
3452 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3453 ALOGW_IF(status != NO_ERROR,
3454 "Engine could not add preferred devices %s for audio source %d role %d",
3455 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3456
Eric Laurent2517af32020-11-25 15:31:27 +01003457 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003458 return status;
3459}
3460
3461status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3462 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3463{
3464 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3465 dumpAudioDeviceTypeAddrVector(devices).c_str());
3466
Mikhail Naganov55773032020-10-01 15:08:13 -07003467 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003468 return BAD_VALUE;
3469 }
3470
3471 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3472 audioSource, role, devices);
3473 ALOGW_IF(status != NO_ERROR,
3474 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3475
Eric Laurent2517af32020-11-25 15:31:27 +01003476 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003477 return status;
3478}
3479
3480status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3481 device_role_t role) {
3482 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3483
3484 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3485 ALOGW_IF(status != NO_ERROR,
3486 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3487
Eric Laurent2517af32020-11-25 15:31:27 +01003488 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003489 return status;
3490}
3491
3492status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3493 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3494 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3495}
3496
Oscar Azucena90e77632019-11-27 17:12:28 -08003497status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003498 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003499 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003500 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3501 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003502 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003503 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3504 if (status != NO_ERROR) {
3505 ALOGE("%s() could not set device affinity for userId %d",
3506 __FUNCTION__, userId);
3507 return status;
3508 }
3509
3510 // reevaluate outputs for all devices
3511 checkForDeviceAndOutputChanges();
3512 updateCallAndOutputRouting();
3513
3514 return NO_ERROR;
3515}
3516
3517status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003518 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003519 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3520 if (status != NO_ERROR) {
3521 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3522 __FUNCTION__, userId);
3523 return status;
3524 }
3525
3526 // reevaluate outputs for all devices
3527 checkForDeviceAndOutputChanges();
3528 updateCallAndOutputRouting();
3529
3530 return NO_ERROR;
3531}
3532
Andy Hungc29d82b2018-10-05 12:23:17 -07003533void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003534{
Andy Hungc29d82b2018-10-05 12:23:17 -07003535 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3536 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003537 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003538 std::string stateLiteral;
3539 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003540 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003541 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3542 "communications", "media", "record", "dock", "system",
3543 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3544 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3545 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003546 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3547 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3548 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3549 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3550 dst->append(" (MANUAL: ");
3551 dumpManualSurroundFormats(dst);
3552 dst->append(")");
3553 }
3554 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003555 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003556 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3557 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003558 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003559 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003560
Andy Hungc29d82b2018-10-05 12:23:17 -07003561 mAvailableOutputDevices.dump(dst, String8("Available output"));
3562 mAvailableInputDevices.dump(dst, String8("Available input"));
3563 mHwModulesAll.dump(dst);
3564 mOutputs.dump(dst);
3565 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003566 mEffects.dump(dst);
3567 mAudioPatches.dump(dst);
3568 mPolicyMixes.dump(dst);
3569 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003570
Kevin Rocardb99cc752019-03-21 20:52:24 -07003571 dst->appendFormat(" AllowedCapturePolicies:\n");
3572 for (auto& policy : mAllowedCapturePolicies) {
3573 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3574 }
3575
François Gaffiec005e562018-11-06 15:04:49 +01003576 dst->appendFormat("\nPolicy Engine dump:\n");
3577 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003578}
3579
3580status_t AudioPolicyManager::dump(int fd)
3581{
3582 String8 result;
3583 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003584 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003585 return NO_ERROR;
3586}
3587
Kevin Rocardb99cc752019-03-21 20:52:24 -07003588status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3589{
3590 mAllowedCapturePolicies[uid] = capturePolicy;
3591 return NO_ERROR;
3592}
3593
Eric Laurente552edb2014-03-10 17:42:56 -07003594// This function checks for the parameters which can be offloaded.
3595// This can be enhanced depending on the capability of the DSP and policy
3596// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003597audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003598{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003599 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003600 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003601 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003602 offloadInfo.format,
3603 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3604 offloadInfo.has_video);
3605
Andy Hung2ddee192015-12-18 17:34:44 -08003606 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003607 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003608 }
3609
Eric Laurente552edb2014-03-10 17:42:56 -07003610 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003611 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003612 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3613 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003614 }
3615
3616 // Check if stream type is music, then only allow offload as of now.
3617 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3618 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003619 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3620 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003621 }
3622
3623 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003624 const bool allowOffloadWithVideo =
3625 property_get_bool("audio.offload.video", false /* default_value */);
3626 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003627 ALOGV("%s: has_video == true, returning false", __func__);
3628 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003629 }
3630
3631 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003632 const int min_duration_secs = property_get_int32(
3633 "audio.offload.min.duration.secs", -1 /* default_value */);
3634 if (min_duration_secs >= 0) {
3635 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003636 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3637 __func__, min_duration_secs);
3638 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003639 }
3640 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003641 ALOGV("%s: Offload denied by duration < default min(=%u)",
3642 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3643 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003644 }
3645
3646 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3647 // creating an offloaded track and tearing it down immediately after start when audioflinger
3648 // detects there is an active non offloadable effect.
3649 // FIXME: We should check the audio session here but we do not have it in this context.
3650 // This may prevent offloading in rare situations where effects are left active by apps
3651 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003652 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003653 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003654 }
3655
3656 // See if there is a profile to support this.
3657 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003658 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003659 offloadInfo.sample_rate,
3660 offloadInfo.format,
3661 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003662 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3663 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003664 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3665 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3666 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003667 if (profile == nullptr) {
3668 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3669 }
3670 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3671 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3672 }
3673 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003674}
3675
Michael Chana94fbb22018-04-24 14:31:19 +10003676bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3677 const audio_attributes_t& attributes) {
3678 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003679 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003680 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003681 config.sample_rate,
3682 config.format,
3683 config.channel_mask,
3684 output_flags,
3685 true /* directOnly */);
3686 ALOGV("%s() profile %sfound with name: %s, "
3687 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3688 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003689 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003690 config.sample_rate, config.format, config.channel_mask, output_flags);
3691 return (profile != 0);
3692}
3693
Eric Laurent6a94d692014-05-20 11:18:06 -07003694status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3695 audio_port_type_t type,
3696 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003697 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003698 unsigned int *generation)
3699{
jiabin19cdba52020-11-24 11:28:58 -08003700 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3701 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003702 return BAD_VALUE;
3703 }
3704 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003705 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003706 *num_ports = 0;
3707 }
3708
3709 size_t portsWritten = 0;
3710 size_t portsMax = *num_ports;
3711 *num_ports = 0;
3712 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003713 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3714 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003715 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003716 for (const auto& dev : mAvailableOutputDevices) {
3717 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003718 continue;
3719 }
3720 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003721 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003722 }
3723 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003725 }
3726 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003727 for (const auto& dev : mAvailableInputDevices) {
3728 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003729 continue;
3730 }
3731 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003732 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003733 }
3734 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003735 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003736 }
3737 }
3738 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3739 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3740 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3741 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3742 }
3743 *num_ports += mInputs.size();
3744 }
3745 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003746 size_t numOutputs = 0;
3747 for (size_t i = 0; i < mOutputs.size(); i++) {
3748 if (!mOutputs[i]->isDuplicated()) {
3749 numOutputs++;
3750 if (portsWritten < portsMax) {
3751 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3752 }
3753 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003754 }
Eric Laurent84c70242014-06-23 08:46:27 -07003755 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003756 }
3757 }
3758 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003759 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003760 return NO_ERROR;
3761}
3762
jiabin19cdba52020-11-24 11:28:58 -08003763status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003764{
Eric Laurent99fcae42018-05-17 16:59:18 -07003765 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3766 return BAD_VALUE;
3767 }
3768 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3769 if (dev != 0) {
3770 dev->toAudioPort(port);
3771 return NO_ERROR;
3772 }
3773 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3774 if (dev != 0) {
3775 dev->toAudioPort(port);
3776 return NO_ERROR;
3777 }
3778 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3779 if (out != 0) {
3780 out->toAudioPort(port);
3781 return NO_ERROR;
3782 }
3783 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3784 if (in != 0) {
3785 in->toAudioPort(port);
3786 return NO_ERROR;
3787 }
3788 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003789}
3790
François Gaffieafd4cea2019-11-18 15:50:22 +01003791status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3792 audio_patch_handle_t *handle,
3793 uid_t uid, uint32_t delayMs,
3794 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003795{
François Gaffieafd4cea2019-11-18 15:50:22 +01003796 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003797 if (handle == NULL || patch == NULL) {
3798 return BAD_VALUE;
3799 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003800 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003801
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003802 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003803 return BAD_VALUE;
3804 }
3805 // only one source per audio patch supported for now
3806 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003807 return INVALID_OPERATION;
3808 }
Eric Laurent874c42872014-08-08 15:13:39 -07003809
3810 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003811 return INVALID_OPERATION;
3812 }
Eric Laurent874c42872014-08-08 15:13:39 -07003813 for (size_t i = 0; i < patch->num_sinks; i++) {
3814 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3815 return INVALID_OPERATION;
3816 }
3817 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003818
3819 sp<AudioPatch> patchDesc;
3820 ssize_t index = mAudioPatches.indexOfKey(*handle);
3821
François Gaffieafd4cea2019-11-18 15:50:22 +01003822 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3823 patch->sources[0].role,
3824 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003825#if LOG_NDEBUG == 0
3826 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003827 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3828 patch->sinks[i].role,
3829 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003830 }
3831#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003832
3833 if (index >= 0) {
3834 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003835 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3836 __func__, mUidCached, patchDesc->getUid(), uid);
3837 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003838 return INVALID_OPERATION;
3839 }
3840 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003841 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003842 }
3843
3844 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003845 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003846 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003847 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003848 return BAD_VALUE;
3849 }
Eric Laurent84c70242014-06-23 08:46:27 -07003850 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3851 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 if (patchDesc != 0) {
3853 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003854 ALOGV("%s source id differs for patch current id %d new id %d",
3855 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003856 return BAD_VALUE;
3857 }
3858 }
Eric Laurent874c42872014-08-08 15:13:39 -07003859 DeviceVector devices;
3860 for (size_t i = 0; i < patch->num_sinks; i++) {
3861 // Only support mix to devices connection
3862 // TODO add support for mix to mix connection
3863 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003864 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003865 return INVALID_OPERATION;
3866 }
3867 sp<DeviceDescriptor> devDesc =
3868 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3869 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003870 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003871 return BAD_VALUE;
3872 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003873
François Gaffie11d30102018-11-02 16:09:09 +01003874 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003875 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003876 NULL, // updatedSamplingRate
3877 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003878 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003879 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003880 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003881 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003882 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003883 return INVALID_OPERATION;
3884 }
3885 devices.add(devDesc);
3886 }
3887 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003888 return INVALID_OPERATION;
3889 }
Eric Laurent874c42872014-08-08 15:13:39 -07003890
Eric Laurent6a94d692014-05-20 11:18:06 -07003891 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003892 ALOGV("%s setting device %s on output %d",
3893 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003894 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003895 index = mAudioPatches.indexOfKey(*handle);
3896 if (index >= 0) {
3897 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003898 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003899 }
3900 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003901 patchDesc->setUid(uid);
3902 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003903 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003904 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003905 return INVALID_OPERATION;
3906 }
3907 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3908 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3909 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003910 // only one sink supported when connecting an input device to a mix
3911 if (patch->num_sinks > 1) {
3912 return INVALID_OPERATION;
3913 }
François Gaffie53615e22015-03-19 09:24:12 +01003914 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003915 if (inputDesc == NULL) {
3916 return BAD_VALUE;
3917 }
3918 if (patchDesc != 0) {
3919 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3920 return BAD_VALUE;
3921 }
3922 }
François Gaffie11d30102018-11-02 16:09:09 +01003923 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003924 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003925 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 return BAD_VALUE;
3927 }
3928
François Gaffie11d30102018-11-02 16:09:09 +01003929 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003930 patch->sinks[0].sample_rate,
3931 NULL, /*updatedSampleRate*/
3932 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003933 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003934 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003935 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003936 // FIXME for the parameter type,
3937 // and the NONE
3938 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003939 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 return INVALID_OPERATION;
3941 }
3942 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003943 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003944 device->toString().c_str(), inputDesc->mIoHandle);
3945 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003946 index = mAudioPatches.indexOfKey(*handle);
3947 if (index >= 0) {
3948 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003949 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003950 }
3951 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003952 patchDesc->setUid(uid);
3953 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003954 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003955 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003956 return INVALID_OPERATION;
3957 }
3958 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3959 // device to device connection
3960 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003961 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 return BAD_VALUE;
3963 }
3964 }
François Gaffie11d30102018-11-02 16:09:09 +01003965 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003967 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003968 return BAD_VALUE;
3969 }
Eric Laurent874c42872014-08-08 15:13:39 -07003970
Eric Laurent6a94d692014-05-20 11:18:06 -07003971 //update source and sink with our own data as the data passed in the patch may
3972 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003973 PatchBuilder patchBuilder;
3974 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003975
3976 // if first sink is to MSD, establish single MSD patch
3977 if (getMsdAudioOutDevices().contains(
3978 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3979 ALOGV("%s patching to MSD", __FUNCTION__);
3980 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3981 goto installPatch;
3982 }
3983
François Gaffieafd4cea2019-11-18 15:50:22 +01003984 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3985 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07003986
Eric Laurent874c42872014-08-08 15:13:39 -07003987 for (size_t i = 0; i < patch->num_sinks; i++) {
3988 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003989 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003990 return INVALID_OPERATION;
3991 }
François Gaffie11d30102018-11-02 16:09:09 +01003992 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07003993 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01003994 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003995 return BAD_VALUE;
3996 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003997 audio_port_config sinkPortConfig = {};
3998 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
3999 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004000
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004001 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4002 // volume management purpose (tracking activity)
4003 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4004 // in config XML to reach the sink so that is can be declared as available.
4005 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4006 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4007 if (sourceDesc != nullptr) {
4008 // take care of dynamic routing for SwOutput selection,
4009 audio_attributes_t attributes = sourceDesc->attributes();
4010 audio_stream_type_t stream = sourceDesc->stream();
4011 audio_attributes_t resultAttr;
4012 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4013 config.sample_rate = sourceDesc->config().sample_rate;
4014 config.channel_mask = sourceDesc->config().channel_mask;
4015 config.format = sourceDesc->config().format;
4016 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4017 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4018 bool isRequestedDeviceForExclusiveUse = false;
4019 output_type_t outputType;
4020 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4021 &stream, sourceDesc->uid(), &config, &flags,
4022 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4023 nullptr, &outputType);
4024 if (output == AUDIO_IO_HANDLE_NONE) {
4025 ALOGV("%s no output for device %s",
4026 __FUNCTION__, sinkDevice->toString().c_str());
4027 return INVALID_OPERATION;
4028 }
4029 outputDesc = mOutputs.valueFor(output);
4030 if (outputDesc->isDuplicated()) {
4031 ALOGE("%s output is duplicated", __func__);
4032 return INVALID_OPERATION;
4033 }
4034 sourceDesc->setSwOutput(outputDesc);
4035 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004036 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004037 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004038 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004039 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004040 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4041 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004042 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4043 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004044 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4045 (sourceDesc != nullptr &&
4046 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004047 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004048 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004049 return INVALID_OPERATION;
4050 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004051 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004052 SortedVector<audio_io_handle_t> outputs =
4053 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4054 // if the sink device is reachable via an opened output stream, request to
4055 // go via this output stream by adding a second source to the patch
4056 // description
4057 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004058 if (output != AUDIO_IO_HANDLE_NONE) {
4059 outputDesc = mOutputs.valueFor(output);
4060 if (outputDesc->isDuplicated()) {
4061 ALOGV("%s output for device %s is duplicated",
4062 __FUNCTION__, sinkDevice->toString().c_str());
4063 return INVALID_OPERATION;
4064 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004065 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004066 }
4067 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004068 audio_port_config srcMixPortConfig = {};
4069 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004070 // for volume control, we may need a valid stream
4071 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4072 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4073 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004074 }
Eric Laurent83b88082014-06-20 18:31:16 -07004075 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004076 }
4077 // TODO: check from routing capabilities in config file and other conflicting patches
4078
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004079installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004080 status_t status = installPatch(
4081 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004082 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004083 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004084 return INVALID_OPERATION;
4085 }
4086 } else {
4087 return BAD_VALUE;
4088 }
4089 } else {
4090 return BAD_VALUE;
4091 }
4092 return NO_ERROR;
4093}
4094
4095status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4096 uid_t uid)
4097{
4098 ALOGV("releaseAudioPatch() patch %d", handle);
4099
4100 ssize_t index = mAudioPatches.indexOfKey(handle);
4101
4102 if (index < 0) {
4103 return BAD_VALUE;
4104 }
4105 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004106 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4107 __func__, mUidCached, patchDesc->getUid(), uid);
4108 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004109 return INVALID_OPERATION;
4110 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004111 return releaseAudioPatchInternal(handle);
4112}
Eric Laurent6a94d692014-05-20 11:18:06 -07004113
François Gaffieafd4cea2019-11-18 15:50:22 +01004114status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4115 uint32_t delayMs)
4116{
4117 ALOGV("%s patch %d", __func__, handle);
4118 if (mAudioPatches.indexOfKey(handle) < 0) {
4119 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4120 return BAD_VALUE;
4121 }
4122 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004124 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004125 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004126 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004127 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004128 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004129 return BAD_VALUE;
4130 }
4131
François Gaffie11d30102018-11-02 16:09:09 +01004132 setOutputDevices(outputDesc,
4133 getNewOutputDevices(outputDesc, true /*fromCache*/),
4134 true,
4135 0,
4136 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4138 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004139 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004140 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004141 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 return BAD_VALUE;
4143 }
4144 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004145 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004146 true,
4147 NULL);
4148 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004149 status_t status =
4150 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4151 ALOGV("%s patch panel returned %d patchHandle %d",
4152 __func__, status, patchDesc->getAfHandle());
4153 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004155 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004156 // SW Bridge
4157 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4158 sp<SwAudioOutputDescriptor> outputDesc =
4159 mOutputs.getOutputFromId(patch->sources[1].id);
4160 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004161 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4162 // releaseOutput has already called closeOuput in case of direct output
4163 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004164 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004165 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4166 // force SwOutput patch removal as AF counter part patch has already gone.
4167 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4168 removeAudioPatch(outputDesc->getPatchHandle());
4169 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004170 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4171 setOutputDevices(outputDesc,
4172 getNewOutputDevices(outputDesc, true /*fromCache*/),
4173 true, /*force*/
4174 0,
4175 NULL);
4176 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004177 } else {
4178 return BAD_VALUE;
4179 }
4180 } else {
4181 return BAD_VALUE;
4182 }
4183 return NO_ERROR;
4184}
4185
4186status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4187 struct audio_patch *patches,
4188 unsigned int *generation)
4189{
François Gaffie53615e22015-03-19 09:24:12 +01004190 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 return BAD_VALUE;
4192 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004194 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004195}
4196
Eric Laurente1715a42014-05-20 11:30:42 -07004197status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004198{
Eric Laurente1715a42014-05-20 11:30:42 -07004199 ALOGV("setAudioPortConfig()");
4200
4201 if (config == NULL) {
4202 return BAD_VALUE;
4203 }
4204 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4205 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004206 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4207 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004208 }
4209
Eric Laurenta121f902014-06-03 13:32:54 -07004210 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004211 if (config->type == AUDIO_PORT_TYPE_MIX) {
4212 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004213 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004214 if (outputDesc == NULL) {
4215 return BAD_VALUE;
4216 }
Eric Laurent84c70242014-06-23 08:46:27 -07004217 ALOG_ASSERT(!outputDesc->isDuplicated(),
4218 "setAudioPortConfig() called on duplicated output %d",
4219 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004220 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004221 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004222 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004223 if (inputDesc == NULL) {
4224 return BAD_VALUE;
4225 }
Eric Laurenta121f902014-06-03 13:32:54 -07004226 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004227 } else {
4228 return BAD_VALUE;
4229 }
4230 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4231 sp<DeviceDescriptor> deviceDesc;
4232 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4233 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4234 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4235 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4236 } else {
4237 return BAD_VALUE;
4238 }
4239 if (deviceDesc == NULL) {
4240 return BAD_VALUE;
4241 }
Eric Laurenta121f902014-06-03 13:32:54 -07004242 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004243 } else {
4244 return BAD_VALUE;
4245 }
4246
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004247 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004248 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4249 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004250 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004251 audioPortConfig->toAudioPortConfig(&newConfig, config);
4252 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004253 }
Eric Laurenta121f902014-06-03 13:32:54 -07004254 if (status != NO_ERROR) {
4255 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004256 }
Eric Laurente1715a42014-05-20 11:30:42 -07004257
4258 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004259}
4260
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004261void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4262{
Eric Laurentd60560a2015-04-10 11:31:20 -07004263 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004264 clearAudioPatches(uid);
4265 clearSessionRoutes(uid);
4266}
4267
Eric Laurent6a94d692014-05-20 11:18:06 -07004268void AudioPolicyManager::clearAudioPatches(uid_t uid)
4269{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004270 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004271 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004272 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004273 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004274 }
4275 }
4276}
4277
François Gaffiec005e562018-11-06 15:04:49 +01004278void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004279{
François Gaffiec005e562018-11-06 15:04:49 +01004280 // Take the first attributes following the product strategy as it is used to retrieve the routed
4281 // device. All attributes wihin a strategy follows the same "routing strategy"
4282 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4283 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004284 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004285 for (size_t j = 0; j < mOutputs.size(); j++) {
4286 if (mOutputs.keyAt(j) == ouptutToSkip) {
4287 continue;
4288 }
4289 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004290 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004291 continue;
4292 }
4293 // If the default device for this strategy is on another output mix,
4294 // invalidate all tracks in this strategy to force re connection.
4295 // Otherwise select new device on the output mix.
4296 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004297 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4298 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004299 }
4300 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004301 setOutputDevices(
4302 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004303 }
4304 }
4305}
4306
4307void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4308{
4309 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004310 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004311 for (size_t i = 0; i < mOutputs.size(); i++) {
4312 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004313 for (const auto& client : outputDesc->getClientIterable()) {
4314 if (client->hasPreferredDevice() && client->uid() == uid) {
4315 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004316 auto clientStrategy = client->strategy();
4317 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4318 end(affectedStrategies)) {
4319 continue;
4320 }
4321 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004322 }
4323 }
4324 }
4325 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004326 for (const auto& strategy : affectedStrategies) {
4327 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004328 }
4329
4330 // remove input routes associated with this uid
4331 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004332 for (size_t i = 0; i < mInputs.size(); i++) {
4333 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004334 for (const auto& client : inputDesc->getClientIterable()) {
4335 if (client->hasPreferredDevice() && client->uid() == uid) {
4336 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4337 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004338 }
4339 }
4340 }
4341 // reroute inputs if necessary
4342 SortedVector<audio_io_handle_t> inputsToClose;
4343 for (size_t i = 0; i < mInputs.size(); i++) {
4344 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004345 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004346 inputsToClose.add(inputDesc->mIoHandle);
4347 }
4348 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004349 for (const auto& input : inputsToClose) {
4350 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004351 }
4352}
4353
Eric Laurentd60560a2015-04-10 11:31:20 -07004354void AudioPolicyManager::clearAudioSources(uid_t uid)
4355{
4356 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004357 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4358 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004359 stopAudioSource(mAudioSources.keyAt(i));
4360 }
4361 }
4362}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004363
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004364status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4365 audio_io_handle_t *ioHandle,
4366 audio_devices_t *device)
4367{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004368 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4369 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004370 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004371 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004372
François Gaffiedf372692015-03-19 10:43:27 +01004373 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004374}
4375
Eric Laurentd60560a2015-04-10 11:31:20 -07004376status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004377 const audio_attributes_t *attributes,
4378 audio_port_handle_t *portId,
4379 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004380{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004381 ALOGV("%s", __FUNCTION__);
4382 *portId = AUDIO_PORT_HANDLE_NONE;
4383
4384 if (source == NULL || attributes == NULL || portId == NULL) {
4385 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4386 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004387 return BAD_VALUE;
4388 }
4389
Eric Laurentd60560a2015-04-10 11:31:20 -07004390 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4391 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004392 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4393 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004394 return INVALID_OPERATION;
4395 }
4396
François Gaffie11d30102018-11-02 16:09:09 +01004397 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004398 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004399 String8(source->ext.device.address),
4400 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004401 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004402 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004403 return BAD_VALUE;
4404 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004405
jiabin4ef93452019-09-10 14:29:54 -07004406 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004407
François Gaffieaaac0fd2018-11-22 17:56:39 +01004408 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004409 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004410 mEngine->getStreamTypeForAttributes(*attributes),
4411 mEngine->getProductStrategyForAttributes(*attributes),
4412 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004413
4414 status_t status = connectAudioSource(sourceDesc);
4415 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004416 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004417 }
4418 return status;
4419}
4420
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004421status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004422{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004423 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004424
4425 // make sure we only have one patch per source.
4426 disconnectAudioSource(sourceDesc);
4427
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004428 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004429 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4430 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4431 sourceDesc->srcDevice()->type(),
4432 String8(sourceDesc->srcDevice()->address().c_str()),
4433 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004434 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004435 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004436 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004437 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004438 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4439 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4440 return INVALID_OPERATION;
4441 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004442 PatchBuilder patchBuilder;
4443 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4444 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4445 status_t status =
4446 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4447 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4448 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4449 return INVALID_OPERATION;
4450 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004451 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004452 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4453 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4454 if (swOutput != 0) {
4455 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004456 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004457 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004458 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004460 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004461 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004462 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004463 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004464 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004465 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004466 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004467 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4468 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004469 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004470 if (delayMs != 0) {
4471 usleep(delayMs * 1000);
4472 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004473 } else {
4474 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4475 if (hwOutputDesc != 0) {
4476 // create Hwoutput and add to mHwOutputs
4477 } else {
4478 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4479 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004480 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004481 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004482
4483FailureSourceActive:
4484 swOutput->stop();
4485 releaseOutput(sourceDesc->portId());
4486FailureSourceAdded:
4487 sourceDesc->setSwOutput(nullptr);
4488FailureReleasePatch:
4489 releaseAudioPatchInternal(handle);
4490 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004491}
4492
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004493status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004494{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004495 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4496 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004497 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004498 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004499 return BAD_VALUE;
4500 }
4501 status_t status = disconnectAudioSource(sourceDesc);
4502
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004503 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004504 return status;
4505}
4506
Andy Hung2ddee192015-12-18 17:34:44 -08004507status_t AudioPolicyManager::setMasterMono(bool mono)
4508{
4509 if (mMasterMono == mono) {
4510 return NO_ERROR;
4511 }
4512 mMasterMono = mono;
4513 // if enabling mono we close all offloaded devices, which will invalidate the
4514 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4515 // for recreating the new AudioTrack as non-offloaded PCM.
4516 //
4517 // If disabling mono, we leave all tracks as is: we don't know which clients
4518 // and tracks are able to be recreated as offloaded. The next "song" should
4519 // play back offloaded.
4520 if (mMasterMono) {
4521 Vector<audio_io_handle_t> offloaded;
4522 for (size_t i = 0; i < mOutputs.size(); ++i) {
4523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4524 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4525 offloaded.push(desc->mIoHandle);
4526 }
4527 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004528 for (const auto& handle : offloaded) {
4529 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004530 }
4531 }
4532 // update master mono for all remaining outputs
4533 for (size_t i = 0; i < mOutputs.size(); ++i) {
4534 updateMono(mOutputs.keyAt(i));
4535 }
4536 return NO_ERROR;
4537}
4538
4539status_t AudioPolicyManager::getMasterMono(bool *mono)
4540{
4541 *mono = mMasterMono;
4542 return NO_ERROR;
4543}
4544
Eric Laurentac9cef52017-06-09 15:46:26 -07004545float AudioPolicyManager::getStreamVolumeDB(
4546 audio_stream_type_t stream, int index, audio_devices_t device)
4547{
jiabin9a3361e2019-10-01 09:38:30 -07004548 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004549}
4550
jiabin81772902018-04-02 17:52:27 -07004551status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4552 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004553 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004554{
Kriti Dang6537def2021-03-02 13:46:59 +01004555 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4556 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004557 return BAD_VALUE;
4558 }
Kriti Dang6537def2021-03-02 13:46:59 +01004559 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4560 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004561
4562 size_t formatsWritten = 0;
4563 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004564
Kriti Dang6537def2021-03-02 13:46:59 +01004565 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004566 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4567 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004568 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004569 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004570 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004571 bool formatEnabled = true;
4572 switch (forceUse) {
4573 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004574 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004575 break;
4576 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4577 formatEnabled = false;
4578 break;
4579 default: // AUTO or ALWAYS => true
4580 break;
jiabin81772902018-04-02 17:52:27 -07004581 }
4582 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4583 }
jiabin81772902018-04-02 17:52:27 -07004584 }
4585 return NO_ERROR;
4586}
4587
Kriti Dang6537def2021-03-02 13:46:59 +01004588status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4589 audio_format_t *surroundFormats) {
4590 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4591 return BAD_VALUE;
4592 }
4593 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4594 __func__, *numSurroundFormats, surroundFormats);
4595
4596 size_t formatsWritten = 0;
4597 size_t formatsMax = *numSurroundFormats;
4598 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4599
4600 // Return formats from all device profiles that have already been resolved by
4601 // checkOutputsForDevice().
4602 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4603 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4604 audio_devices_t deviceType = device->type();
4605 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4606 // returns formats reported by HDMI devices.
4607 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4608 continue;
4609 }
4610 // Formats reported by sink devices
4611 std::unordered_set<audio_format_t> formatset;
4612 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4613 formatset.insert(it->second.begin(), it->second.end());
4614 }
4615
4616 // Formats hard-coded in the in policy configuration file (if any).
4617 FormatVector encodedFormats = device->encodedFormats();
4618 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4619 // Filter the formats which are supported by the vendor hardware.
4620 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4621 if (mConfig.getSurroundFormats().count(*it) != 0) {
4622 formats.insert(*it);
4623 } else {
4624 for (const auto& pair : mConfig.getSurroundFormats()) {
4625 if (pair.second.count(*it) != 0) {
4626 formats.insert(pair.first);
4627 break;
4628 }
4629 }
4630 }
4631 }
4632 }
4633 *numSurroundFormats = formats.size();
4634 for (const auto& format: formats) {
4635 if (formatsWritten < formatsMax) {
4636 surroundFormats[formatsWritten++] = format;
4637 }
4638 }
4639 return NO_ERROR;
4640}
4641
jiabin81772902018-04-02 17:52:27 -07004642status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4643{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004644 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004645 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4646 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004647 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004648 return BAD_VALUE;
4649 }
4650
Mikhail Naganov100f0122018-11-29 11:22:16 -08004651 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4652 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004653 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004654 return INVALID_OPERATION;
4655 }
4656
Mikhail Naganov100f0122018-11-29 11:22:16 -08004657 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004658 return NO_ERROR;
4659 }
4660
Mikhail Naganov100f0122018-11-29 11:22:16 -08004661 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004662 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004663 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004664 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004665 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004666 }
4667 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004668 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004669 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004670 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004671 }
4672 }
4673
4674 sp<SwAudioOutputDescriptor> outputDesc;
4675 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004676 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4677 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004678 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4679 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004680 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004681 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004682 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4683 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4684 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004685 name.c_str(),
4686 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004687 if (status != NO_ERROR) {
4688 continue;
4689 }
4690 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4691 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4692 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004693 name.c_str(),
4694 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004695 profileUpdated |= (status == NO_ERROR);
4696 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004697 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004698 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004699 AUDIO_DEVICE_IN_HDMI);
4700 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4701 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004702 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004703 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004704 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4705 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4706 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004707 name.c_str(),
4708 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004709 if (status != NO_ERROR) {
4710 continue;
4711 }
4712 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4713 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4714 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004715 name.c_str(),
4716 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004717 profileUpdated |= (status == NO_ERROR);
4718 }
4719
jiabin81772902018-04-02 17:52:27 -07004720 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004721 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004722 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004723 }
4724
4725 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4726}
4727
Eric Laurent5ada82e2019-08-29 17:53:54 -07004728void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004729{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004730 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004731 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004732 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004733 }
4734}
4735
jiabin6012f912018-11-02 17:06:30 -07004736bool AudioPolicyManager::isHapticPlaybackSupported()
4737{
4738 for (const auto& hwModule : mHwModules) {
4739 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4740 for (const auto &outProfile : outputProfiles) {
4741 struct audio_port audioPort;
4742 outProfile->toAudioPort(&audioPort);
4743 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4744 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4745 return true;
4746 }
4747 }
4748 }
4749 }
4750 return false;
4751}
4752
Eric Laurent8340e672019-11-06 11:01:08 -08004753bool AudioPolicyManager::isCallScreenModeSupported()
4754{
4755 return getConfig().isCallScreenModeSupported();
4756}
4757
4758
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004759status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004760{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004761 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004762 if (!sourceDesc->isConnected()) {
4763 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4764 return NO_ERROR;
4765 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004766 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4767 if (swOutput != 0) {
4768 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004769 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004770 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004771 }
jiabinbce0c1d2020-10-05 11:20:18 -07004772 if (releaseOutput(sourceDesc->portId())) {
4773 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4774 // no need to release audio patch here but just return NO_ERROR.
4775 return NO_ERROR;
4776 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004777 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004778 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004779 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004780 // close Hwoutput and remove from mHwOutputs
4781 } else {
4782 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4783 }
4784 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004785 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4786 sourceDesc->disconnect();
4787 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004788}
4789
François Gaffiec005e562018-11-06 15:04:49 +01004790sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4791 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004792{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004793 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004794 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004795 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004796 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004797 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4798 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004799 source = sourceDesc;
4800 break;
4801 }
4802 }
4803 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004804}
4805
Eric Laurente552edb2014-03-10 17:42:56 -07004806// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004807// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004808// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004809uint32_t AudioPolicyManager::nextAudioPortGeneration()
4810{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004811 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004812}
4813
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004814static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004815 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4816 !audioPolicyXmlConfigFile.empty()) {
4817 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4818 if (ret == NO_ERROR) {
4819 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004820 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004821 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004822 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004823 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004824}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004825
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004826AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4827 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004828 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004829 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004830 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004831 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004832 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004833 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004834 mAudioPortGeneration(1),
4835 mBeaconMuteRefCount(0),
4836 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004837 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004838 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004839 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004840 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004841{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004842}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004843
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004844AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4845 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4846{
4847 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004848}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004849
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004850void AudioPolicyManager::loadConfig() {
4851 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004852 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004853 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004854 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004855}
4856
4857status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004858 {
4859 auto engLib = EngineLibrary::load(
4860 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4861 if (!engLib) {
4862 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4863 return NO_INIT;
4864 }
4865 mEngine = engLib->createEngine();
4866 if (mEngine == nullptr) {
4867 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4868 return NO_INIT;
4869 }
François Gaffie2110e042015-03-24 08:41:51 +01004870 }
4871 mEngine->setObserver(this);
4872 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004873 if (status != NO_ERROR) {
4874 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4875 return status;
4876 }
François Gaffie2110e042015-03-24 08:41:51 +01004877
Eric Laurent1d69c872021-01-11 18:53:01 +01004878 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4879 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4880
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004881 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004882 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004883 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004884
Eric Laurent3a4311c2014-03-17 12:00:47 -07004885 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004886 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4887 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4888 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004889 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004890 }
jiabin9ff780e2018-03-19 18:19:52 -07004891 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004892 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004893 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004894 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004895 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004896 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004897 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004898 }
4899 }
4900 }
Eric Laurente552edb2014-03-10 17:42:56 -07004901
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004902 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004903
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004904 // Silence ALOGV statements
4905 property_set("log.tag." LOG_TAG, "D");
4906
Eric Laurente552edb2014-03-10 17:42:56 -07004907 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004908 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004909}
4910
Eric Laurente0720872014-03-11 09:30:41 -07004911AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004912{
Eric Laurente552edb2014-03-10 17:42:56 -07004913 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004914 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004915 }
4916 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004917 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004918 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004919 mAvailableOutputDevices.clear();
4920 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004921 mOutputs.clear();
4922 mInputs.clear();
4923 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004924 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004925 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004926}
4927
Eric Laurente0720872014-03-11 09:30:41 -07004928status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004929{
Eric Laurent87ffa392015-05-22 10:32:38 -07004930 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004931}
4932
Eric Laurente552edb2014-03-10 17:42:56 -07004933// ---
4934
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004935void AudioPolicyManager::onNewAudioModulesAvailable()
4936{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004937 DeviceVector newDevices;
4938 onNewAudioModulesAvailableInt(&newDevices);
4939 if (!newDevices.empty()) {
4940 nextAudioPortGeneration();
4941 mpClientInterface->onAudioPortListUpdate();
4942 }
4943}
4944
4945void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4946{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004947 for (const auto& hwModule : mHwModulesAll) {
4948 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4949 continue;
4950 }
4951 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4952 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4953 ALOGW("could not open HW module %s", hwModule->getName());
4954 continue;
4955 }
4956 mHwModules.push_back(hwModule);
4957 // open all output streams needed to access attached devices
4958 // except for direct output streams that are only opened when they are actually
4959 // required by an app.
4960 // This also validates mAvailableOutputDevices list
4961 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4962 if (!outProfile->canOpenNewIo()) {
4963 ALOGE("Invalid Output profile max open count %u for profile %s",
4964 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4965 continue;
4966 }
4967 if (!outProfile->hasSupportedDevices()) {
4968 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4969 continue;
4970 }
4971 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4972 mTtsOutputAvailable = true;
4973 }
4974
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004975 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4976 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4977 sp<DeviceDescriptor> supportedDevice = 0;
4978 if (supportedDevices.contains(mDefaultOutputDevice)) {
4979 supportedDevice = mDefaultOutputDevice;
4980 } else {
4981 // choose first device present in profile's SupportedDevices also part of
4982 // mAvailableOutputDevices.
4983 if (availProfileDevices.isEmpty()) {
4984 continue;
4985 }
4986 supportedDevice = availProfileDevices.itemAt(0);
4987 }
4988 if (!mOutputDevicesAll.contains(supportedDevice)) {
4989 continue;
4990 }
4991 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4992 mpClientInterface);
4993 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02004994 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
4995 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004996 AUDIO_STREAM_DEFAULT,
4997 AUDIO_OUTPUT_FLAG_NONE, &output);
4998 if (status != NO_ERROR) {
4999 ALOGW("Cannot open output stream for devices %s on hw module %s",
5000 supportedDevice->toString().c_str(), hwModule->getName());
5001 continue;
5002 }
5003 for (const auto &device : availProfileDevices) {
5004 // give a valid ID to an attached device once confirmed it is reachable
5005 if (!device->isAttached()) {
5006 device->attach(hwModule);
5007 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005008 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005009 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005010 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5011 }
5012 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005013 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005014 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5015 mPrimaryOutput = outputDesc;
5016 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005017 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5018 outputDesc->close();
5019 } else {
5020 addOutput(output, outputDesc);
5021 setOutputDevices(outputDesc,
5022 DeviceVector(supportedDevice),
5023 true,
5024 0,
5025 NULL);
5026 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005027 }
5028 // open input streams needed to access attached devices to validate
5029 // mAvailableInputDevices list
5030 for (const auto& inProfile : hwModule->getInputProfiles()) {
5031 if (!inProfile->canOpenNewIo()) {
5032 ALOGE("Invalid Input profile max open count %u for profile %s",
5033 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5034 continue;
5035 }
5036 if (!inProfile->hasSupportedDevices()) {
5037 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5038 continue;
5039 }
5040 // chose first device present in profile's SupportedDevices also part of
5041 // available input devices
5042 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5043 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5044 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005045 ALOGV("%s: Input device list is empty! for profile %s",
5046 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005047 continue;
5048 }
5049 sp<AudioInputDescriptor> inputDesc =
5050 new AudioInputDescriptor(inProfile, mpClientInterface);
5051
5052 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5053 status_t status = inputDesc->open(nullptr,
5054 availProfileDevices.itemAt(0),
5055 AUDIO_SOURCE_MIC,
5056 AUDIO_INPUT_FLAG_NONE,
5057 &input);
5058 if (status != NO_ERROR) {
5059 ALOGW("Cannot open input stream for device %s on hw module %s",
5060 availProfileDevices.toString().c_str(),
5061 hwModule->getName());
5062 continue;
5063 }
5064 for (const auto &device : availProfileDevices) {
5065 // give a valid ID to an attached device once confirmed it is reachable
5066 if (!device->isAttached()) {
5067 device->attach(hwModule);
5068 device->importAudioPortAndPickAudioProfile(inProfile, true);
5069 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005070 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005071 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5072 }
5073 }
5074 inputDesc->close();
5075 }
5076 }
5077}
5078
Eric Laurent98e38192018-02-15 18:31:53 -08005079void AudioPolicyManager::addOutput(audio_io_handle_t output,
5080 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005081{
Eric Laurent1c333e22014-05-20 10:48:17 -07005082 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005083 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005084 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005085 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005087}
5088
François Gaffie53615e22015-03-19 09:24:12 +01005089void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5090{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005091 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5092 ALOGV("%s: removing primary output", __func__);
5093 mPrimaryOutput = nullptr;
5094 }
François Gaffie53615e22015-03-19 09:24:12 +01005095 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005096 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005097}
5098
Eric Laurent98e38192018-02-15 18:31:53 -08005099void AudioPolicyManager::addInput(audio_io_handle_t input,
5100 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005101{
Eric Laurent1c333e22014-05-20 10:48:17 -07005102 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005103 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005104}
Eric Laurente552edb2014-03-10 17:42:56 -07005105
François Gaffie11d30102018-11-02 16:09:09 +01005106status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005107 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005108 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005109{
François Gaffie11d30102018-11-02 16:09:09 +01005110 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005111 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005112 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005113
François Gaffie11d30102018-11-02 16:09:09 +01005114 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005115 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005116 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005117 }
Eric Laurente552edb2014-03-10 17:42:56 -07005118
Eric Laurent3b73df72014-03-11 09:06:29 -07005119 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005120 // first call getAudioPort to get the supported attributes from the HAL
5121 struct audio_port_v7 port = {};
5122 device->toAudioPort(&port);
5123 status_t status = mpClientInterface->getAudioPort(&port);
5124 if (status == NO_ERROR) {
5125 device->importAudioPort(port);
5126 }
5127
5128 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005129 for (size_t i = 0; i < mOutputs.size(); i++) {
5130 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005131 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005132 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005133 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5134 mOutputs.keyAt(i), device->toString().c_str());
5135 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005136 }
5137 }
5138 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005139 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005140 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005141 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5142 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005143 if (profile->supportsDevice(device)) {
5144 profiles.add(profile);
5145 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5146 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005147 }
5148 }
5149 }
5150
Eric Laurent7b279bb2015-12-14 10:18:23 -08005151 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005152
Eric Laurente552edb2014-03-10 17:42:56 -07005153 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005154 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005155 return BAD_VALUE;
5156 }
5157
5158 // open outputs for matching profiles if needed. Direct outputs are also opened to
5159 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5160 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005161 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005162
5163 // nothing to do if one output is already opened for this profile
5164 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005165 for (j = 0; j < outputs.size(); j++) {
5166 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005167 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005168 // matching profile: save the sample rates, format and channel masks supported
5169 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005170 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005171 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005172 }
Eric Laurente552edb2014-03-10 17:42:56 -07005173 break;
5174 }
5175 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005176 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005177 continue;
5178 }
5179
Eric Laurent3974e3b2017-12-07 17:58:43 -08005180 if (!profile->canOpenNewIo()) {
5181 ALOGW("Max Output number %u already opened for this profile %s",
5182 profile->maxOpenCount, profile->getTagName().c_str());
5183 continue;
5184 }
5185
Eric Laurent83efe1c2017-07-09 16:51:08 -07005186 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005187 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005188 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5189 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005190 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005191 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005192 profiles.removeAt(profile_index);
5193 profile_index--;
5194 } else {
5195 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005196 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005197 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005198 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5199 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005200 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005201 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005202
François Gaffie11d30102018-11-02 16:09:09 +01005203 if (device_distinguishes_on_address(deviceType)) {
5204 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5205 device->toString().c_str());
5206 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5207 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005208 }
Eric Laurente552edb2014-03-10 17:42:56 -07005209 ALOGV("checkOutputsForDevice(): adding output %d", output);
5210 }
5211 }
5212
5213 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005214 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005215 return BAD_VALUE;
5216 }
Eric Laurentd4692962014-05-05 18:13:44 -07005217 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005218 // check if one opened output is not needed any more after disconnecting one device
5219 for (size_t i = 0; i < mOutputs.size(); i++) {
5220 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005221 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005222 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005223 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
jiabinbce0c1d2020-10-05 11:20:18 -07005224 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005225 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005226 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005227 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5228 mOutputs.keyAt(i));
5229 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005230 }
Eric Laurente552edb2014-03-10 17:42:56 -07005231 }
5232 }
Eric Laurentd4692962014-05-05 18:13:44 -07005233 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005234 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005235 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5236 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005237 if (!profile->supportsDevice(device)) {
5238 continue;
5239 }
5240 ALOGV("checkOutputsForDevice(): "
5241 "clearing direct output profile %zu on module %s",
5242 j, hwModule->getName());
5243 profile->clearAudioProfiles();
5244 if (!profile->hasDynamicAudioProfile()) {
5245 continue;
5246 }
5247 // When a device is disconnected, if there is an IOProfile that contains dynamic
5248 // profiles and supports the disconnected device, call getAudioPort to repopulate
5249 // the capabilities of the devices that is supported by the IOProfile.
5250 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5251 if (supportedDevice == device ||
5252 !mAvailableOutputDevices.contains(supportedDevice)) {
5253 continue;
5254 }
5255 struct audio_port_v7 port;
5256 supportedDevice->toAudioPort(&port);
5257 status_t status = mpClientInterface->getAudioPort(&port);
5258 if (status == NO_ERROR) {
5259 supportedDevice->importAudioPort(port);
5260 }
Eric Laurente552edb2014-03-10 17:42:56 -07005261 }
5262 }
5263 }
5264 }
5265 return NO_ERROR;
5266}
5267
François Gaffie11d30102018-11-02 16:09:09 +01005268status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005269 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005270{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005271 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005272
François Gaffie11d30102018-11-02 16:09:09 +01005273 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005274 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005275 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005276 }
5277
Eric Laurentd4692962014-05-05 18:13:44 -07005278 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005279 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005280 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005281 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005282 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005283 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005284 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005285 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005286
François Gaffie11d30102018-11-02 16:09:09 +01005287 if (profile->supportsDevice(device)) {
5288 profiles.add(profile);
5289 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5290 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005291 }
5292 }
5293 }
5294
Eric Laurent0dd51852019-04-19 18:18:58 -07005295 if (profiles.isEmpty()) {
5296 ALOGW("%s: No input profile available for device %s",
5297 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005298 return BAD_VALUE;
5299 }
5300
5301 // open inputs for matching profiles if needed. Direct inputs are also opened to
5302 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5303 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5304
Eric Laurent1c333e22014-05-20 10:48:17 -07005305 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005306
Eric Laurentd4692962014-05-05 18:13:44 -07005307 // nothing to do if one input is already opened for this profile
5308 size_t input_index;
5309 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5310 desc = mInputs.valueAt(input_index);
5311 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005312 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005313 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005314 }
Eric Laurentd4692962014-05-05 18:13:44 -07005315 break;
5316 }
5317 }
5318 if (input_index != mInputs.size()) {
5319 continue;
5320 }
5321
Eric Laurent3974e3b2017-12-07 17:58:43 -08005322 if (!profile->canOpenNewIo()) {
5323 ALOGW("Max Input number %u already opened for this profile %s",
5324 profile->maxOpenCount, profile->getTagName().c_str());
5325 continue;
5326 }
5327
Eric Laurentfe231122017-11-17 17:48:06 -08005328 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005329 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005330 status_t status = desc->open(nullptr,
5331 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005332 AUDIO_SOURCE_MIC,
5333 AUDIO_INPUT_FLAG_NONE,
5334 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005335
Eric Laurentcf2c0212014-07-25 16:20:43 -07005336 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005337 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005338 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005339 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005340 mpClientInterface->setParameters(input, String8(param));
5341 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005342 }
François Gaffie11d30102018-11-02 16:09:09 +01005343 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005344 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005345 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005346 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005347 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005348 }
5349
Eric Laurent0dd51852019-04-19 18:18:58 -07005350 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005351 addInput(input, desc);
5352 }
5353 } // endif input != 0
5354
Eric Laurentcf2c0212014-07-25 16:20:43 -07005355 if (input == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005356 ALOGW("%s could not open input for device %s", __func__,
5357 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005358 profiles.removeAt(profile_index);
5359 profile_index--;
5360 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005361 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005362 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005363 }
Eric Laurentd4692962014-05-05 18:13:44 -07005364 ALOGV("checkInputsForDevice(): adding input %d", input);
5365 }
5366 } // end scan profiles
5367
5368 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005369 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005370 return BAD_VALUE;
5371 }
5372 } else {
5373 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005374 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005375 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005376 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005377 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005378 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005379 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005380 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005381 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5382 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005383 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005384 }
5385 }
5386 }
5387 } // end disconnect
5388
5389 return NO_ERROR;
5390}
5391
5392
Eric Laurente0720872014-03-11 09:30:41 -07005393void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005394{
5395 ALOGV("closeOutput(%d)", output);
5396
François Gaffie1c878552018-11-22 16:53:21 +01005397 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5398 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005399 ALOGW("closeOutput() unknown output %d", output);
5400 return;
5401 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005402 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005403 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005404
Eric Laurente552edb2014-03-10 17:42:56 -07005405 // look for duplicated outputs connected to the output being removed.
5406 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005407 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5408 if (dupOutput->isDuplicated() &&
5409 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5410 sp<SwAudioOutputDescriptor> remainingOutput =
5411 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005412 // As all active tracks on duplicated output will be deleted,
5413 // and as they were also referenced on the other output, the reference
5414 // count for their stream type must be adjusted accordingly on
5415 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005416 const bool wasActive = remainingOutput->isActive();
5417 // Note: no-op on the closing output where all clients has already been set inactive
5418 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005419 // stop() will be a no op if the output is still active but is needed in case all
5420 // active streams refcounts where cleared above
5421 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005422 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005423 }
Eric Laurente552edb2014-03-10 17:42:56 -07005424 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5425 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5426
5427 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005428 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005429 }
5430 }
5431
Eric Laurent05b90f82014-08-27 15:32:29 -07005432 nextAudioPortGeneration();
5433
François Gaffie1c878552018-11-22 16:53:21 +01005434 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005435 if (index >= 0) {
5436 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005437 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5438 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005439 mAudioPatches.removeItemsAt(index);
5440 mpClientInterface->onAudioPatchListUpdate();
5441 }
5442
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005443 if (closingOutputWasActive) {
5444 closingOutput->stop();
5445 }
François Gaffie1c878552018-11-22 16:53:21 +01005446 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005447
François Gaffie53615e22015-03-19 09:24:12 +01005448 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005449 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005450
5451 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5452 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005453 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005454 bool directOutputOpen = false;
5455 for (size_t i = 0; i < mOutputs.size(); i++) {
5456 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5457 directOutputOpen = true;
5458 break;
5459 }
5460 }
5461 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005462 ALOGV("no direct outputs open, reset MSD patches");
5463 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5464 // how output devices for patching are resolved. Avoid by caching and reusing the
5465 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5466 // devices to patch to. This may be complicated by the fact that devices may become
5467 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005468 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005469 }
5470 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005471}
5472
5473void AudioPolicyManager::closeInput(audio_io_handle_t input)
5474{
5475 ALOGV("closeInput(%d)", input);
5476
5477 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5478 if (inputDesc == NULL) {
5479 ALOGW("closeInput() unknown input %d", input);
5480 return;
5481 }
5482
Eric Laurent6a94d692014-05-20 11:18:06 -07005483 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005484
François Gaffie11d30102018-11-02 16:09:09 +01005485 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005486 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005487 if (index >= 0) {
5488 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005489 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5490 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005491 mAudioPatches.removeItemsAt(index);
5492 mpClientInterface->onAudioPatchListUpdate();
5493 }
5494
Eric Laurentfe231122017-11-17 17:48:06 -08005495 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005496 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005497
François Gaffie11d30102018-11-02 16:09:09 +01005498 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5499 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005500 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005501 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005502 }
Eric Laurente552edb2014-03-10 17:42:56 -07005503}
5504
François Gaffie11d30102018-11-02 16:09:09 +01005505SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5506 const DeviceVector &devices,
5507 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005508{
5509 SortedVector<audio_io_handle_t> outputs;
5510
François Gaffie11d30102018-11-02 16:09:09 +01005511 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005512 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005513 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005514 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005515 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005516 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005517 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005518 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005519 outputs.add(openOutputs.keyAt(i));
5520 }
5521 }
5522 return outputs;
5523}
5524
Mikhail Naganov37977152018-07-11 15:54:44 -07005525void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5526{
5527 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5528 // output is suspended before any tracks are moved to it
5529 checkA2dpSuspend();
5530 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005531 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005532 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005533 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005534 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005535 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5536 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5537 // configuration changes will ultimately be rerouted correctly. We can still avoid
5538 // unnecessary rerouting by caching and reusing the arguments to
5539 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5540 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005541 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005542 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005543 // an event that changed routing likely occurred, inform upper layers
5544 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005545}
5546
François Gaffiec005e562018-11-06 15:04:49 +01005547bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5548 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005549{
François Gaffiec005e562018-11-06 15:04:49 +01005550 return mEngine->getProductStrategyForAttributes(lAttr) ==
5551 mEngine->getProductStrategyForAttributes(rAttr);
5552}
5553
Francois Gaffieff1eb522020-05-06 18:37:04 +02005554void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5555{
5556 for (size_t i = 0; i < mAudioSources.size(); i++) {
5557 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5558 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005559 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5560 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005561 connectAudioSource(sourceDesc);
5562 }
5563 }
5564}
5565
5566void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5567{
5568 for (size_t i = 0; i < mAudioSources.size(); i++) {
5569 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5570 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5571 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5572 disconnectAudioSource(sourceDesc);
5573 }
5574 }
5575}
5576
François Gaffiec005e562018-11-06 15:04:49 +01005577void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5578{
5579 auto psId = mEngine->getProductStrategyForAttributes(attr);
5580
5581 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5582 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005583
François Gaffie11d30102018-11-02 16:09:09 +01005584 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5585 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005586
Eric Laurentc209fe42020-06-05 18:11:23 -07005587 uint32_t maxLatency = 0;
5588 bool invalidate = false;
5589 // take into account dynamic audio policies related changes: if a client is now associated
5590 // to a different policy mix than at creation time, invalidate corresponding stream
5591 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5592 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5593 if (desc->isDuplicated()) {
5594 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005595 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005596 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5597 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5598 continue;
5599 }
5600 sp<AudioPolicyMix> primaryMix;
5601 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5602 client->flags(), primaryMix, nullptr);
5603 if (status != OK) {
5604 continue;
5605 }
yucliuf4de36d2020-09-14 14:57:56 -07005606 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005607 invalidate = true;
5608 if (desc->isStrategyActive(psId)) {
5609 maxLatency = desc->latency();
5610 }
5611 break;
5612 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005613 }
5614 }
5615
Eric Laurentc209fe42020-06-05 18:11:23 -07005616 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005617 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5618 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005619 for (audio_io_handle_t srcOut : srcOutputs) {
5620 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005621 if (desc == nullptr) continue;
5622
5623 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005624 maxLatency = desc->latency();
5625 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005626
5627 if (invalidate) continue;
5628
5629 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005630 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005631 // a client on a non direct outputs has necessarily a linear PCM format
5632 // so we can call selectOutput() safely
5633 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5634 client->flags(),
5635 client->config().format,
5636 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005637 client->config().sample_rate,
5638 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005639 if (newOutput != srcOut) {
5640 invalidate = true;
5641 break;
5642 }
5643 } else {
5644 sp<IOProfile> profile = getProfileForOutput(newDevices,
5645 client->config().sample_rate,
5646 client->config().format,
5647 client->config().channel_mask,
5648 client->flags(),
5649 true /* directOnly */);
5650 if (profile != desc->mProfile) {
5651 invalidate = true;
5652 break;
5653 }
5654 }
5655 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005656 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005657
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005658 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005659 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005660 std::to_string(srcOutputs[0]).c_str(),
5661 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005662 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005663 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005664 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005665 if (desc == nullptr) continue;
5666
5667 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005668 setStrategyMute(psId, true, desc);
5669 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005670 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005671 }
François Gaffiec005e562018-11-06 15:04:49 +01005672 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005673 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005674 connectAudioSource(source);
5675 }
Eric Laurente552edb2014-03-10 17:42:56 -07005676 }
5677
François Gaffiec005e562018-11-06 15:04:49 +01005678 // Move effects associated to this stream from previous output to new output
5679 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005680 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005681 }
François Gaffiec005e562018-11-06 15:04:49 +01005682 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005683 if (invalidate) {
5684 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5685 mpClientInterface->invalidateStream(stream);
5686 }
Eric Laurente552edb2014-03-10 17:42:56 -07005687 }
5688 }
5689}
5690
Eric Laurente0720872014-03-11 09:30:41 -07005691void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005692{
François Gaffiec005e562018-11-06 15:04:49 +01005693 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5694 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5695 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005696 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005697 }
Eric Laurente552edb2014-03-10 17:42:56 -07005698}
5699
Kevin Rocard153f92d2018-12-18 18:33:28 -08005700void AudioPolicyManager::checkSecondaryOutputs() {
5701 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005702 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005703 for (size_t i = 0; i < mOutputs.size(); i++) {
5704 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5705 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005706 sp<AudioPolicyMix> primaryMix;
5707 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005708 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005709 client->flags(), primaryMix, &secondaryMixes);
5710 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5711 for (auto &secondaryMix : secondaryMixes) {
5712 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5713 if (outputDesc != nullptr &&
5714 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5715 secondaryDescs.push_back(outputDesc);
5716 }
5717 }
5718
jiabinf042b9b2021-05-07 23:46:28 +00005719 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005720 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005721 } else if (!std::equal(
5722 client->getSecondaryOutputs().begin(),
5723 client->getSecondaryOutputs().end(),
5724 secondaryDescs.begin(), secondaryDescs.end())) {
5725 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5726 std::vector<audio_io_handle_t> secondaryOutputIds;
5727 for (const auto& secondaryDesc : secondaryDescs) {
5728 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5729 weakSecondaryDescs.push_back(secondaryDesc);
5730 }
5731 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5732 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005733 }
5734 }
5735 }
jiabinf042b9b2021-05-07 23:46:28 +00005736 if (!trackSecondaryOutputs.empty()) {
5737 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5738 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005739 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005740 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005741 mpClientInterface->invalidateStream(stream);
5742 }
5743}
5744
Eric Laurent2517af32020-11-25 15:31:27 +01005745bool AudioPolicyManager::isScoRequestedForComm() const {
5746 AudioDeviceTypeAddrVector devices;
5747 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5748 for (const auto &device : devices) {
5749 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5750 return true;
5751 }
5752 }
5753 return false;
5754}
5755
Eric Laurente0720872014-03-11 09:30:41 -07005756void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005757{
François Gaffie53615e22015-03-19 09:24:12 +01005758 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005759 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005760 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005761 return;
5762 }
5763
Eric Laurent3a4311c2014-03-17 12:00:47 -07005764 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005765 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5766 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005767 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005768
5769 // if suspended, restore A2DP output if:
5770 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005771 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005772 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005773 //
Eric Laurentf732e072016-08-03 19:30:28 -07005774 // if not suspended, suspend A2DP output if:
5775 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005776 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005777 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005778 //
5779 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005780 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005781 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005782 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005783 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005784
5785 mpClientInterface->restoreOutput(a2dpOutput);
5786 mA2dpSuspended = false;
5787 }
5788 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005789 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005790 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005791 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005792 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005793
5794 mpClientInterface->suspendOutput(a2dpOutput);
5795 mA2dpSuspended = true;
5796 }
5797 }
5798}
5799
François Gaffie11d30102018-11-02 16:09:09 +01005800DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5801 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005802{
François Gaffie11d30102018-11-02 16:09:09 +01005803 DeviceVector devices;
5804
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005805 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005806 if (index >= 0) {
5807 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005808 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005809 ALOGV("%s device %s forced by patch %d", __func__,
5810 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5811 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005812 }
5813 }
5814
Dean Wheatley514b4312020-06-17 21:45:00 +10005815 // Do not retrieve engine device for outputs through MSD
5816 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5817 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5818 return outputDesc->devices();
5819 }
5820
Eric Laurent97ac8712018-07-27 18:59:02 -07005821 // Honor explicit routing requests only if no client using default routing is active on this
5822 // input: a specific app can not force routing for other apps by setting a preferred device.
5823 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005824 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005825 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005826 if (device != nullptr) {
5827 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005828 }
5829
François Gaffiea807ef92018-11-05 10:44:33 +01005830 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5831 // of setForceUse / Default Bus device here
5832 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5833 if (device != nullptr) {
5834 return DeviceVector(device);
5835 }
5836
François Gaffiec005e562018-11-06 15:04:49 +01005837 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5838 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5839 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305840 auto hasStreamActive = [&](auto stream) {
5841 return hasStream(streams, stream) && isStreamActive(stream, 0);
5842 };
Eric Laurent484e9272018-06-07 17:29:23 -07005843
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305844 auto doGetOutputDevicesForVoice = [&]() {
5845 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5846 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5847 (isInCall() ||
5848 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
5849 };
5850
5851 // With low-latency playing on speaker, music on WFD, when the first low-latency
5852 // output is stopped, getNewOutputDevices checks for a product strategy
5853 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsuf20f2d42021-06-28 16:53:14 +08005854 // If an ALARM, RING or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305855 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5856 // stream is associated to the output descriptor.
5857 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5858 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
Carter Hsuf20f2d42021-06-28 16:53:14 +08005859 hasStreamActive(AUDIO_STREAM_RING) ||
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305860 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5861 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005862 // Retrieval of devices for voice DL is done on primary output profile, cannot
5863 // check the route (would force modifying configuration file for this profile)
5864 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5865 break;
5866 }
Eric Laurente552edb2014-03-10 17:42:56 -07005867 }
François Gaffiec005e562018-11-06 15:04:49 +01005868 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005869 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005870}
5871
François Gaffie11d30102018-11-02 16:09:09 +01005872sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5873 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005874{
François Gaffie11d30102018-11-02 16:09:09 +01005875 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005876
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005877 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005878 if (index >= 0) {
5879 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005880 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005881 ALOGV("getNewInputDevice() device %s forced by patch %d",
5882 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5883 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005884 }
5885 }
5886
Eric Laurent97ac8712018-07-27 18:59:02 -07005887 // Honor explicit routing requests only if no client using default routing is active on this
5888 // input: a specific app can not force routing for other apps by setting a preferred device.
5889 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005890 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5891 if (device != nullptr) {
5892 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005893 }
5894
Eric Laurentdc95a252018-04-12 12:46:56 -07005895 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005896 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005897 audio_attributes_t attributes;
5898 uid_t uid;
5899 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5900 if (topClient != nullptr) {
5901 attributes = topClient->attributes();
5902 uid = topClient->uid();
5903 } else {
5904 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5905 uid = 0;
5906 }
5907
Francois Gaffie716e1432019-01-14 16:58:59 +01005908 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5909 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005910 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005911 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005912 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005913 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005914
Eric Laurente552edb2014-03-10 17:42:56 -07005915 return device;
5916}
5917
Eric Laurent794fde22016-03-11 09:50:45 -08005918bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5919 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005920 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005921}
5922
Eric Laurente0720872014-03-11 09:30:41 -07005923audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005924 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005925 // getOutputDevicesForStream's behavior for invalid streams.
5926 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5927 // device for music stream), but we want to return the empty set.
5928 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005929 return AUDIO_DEVICE_NONE;
5930 }
François Gaffie11d30102018-11-02 16:09:09 +01005931 DeviceVector activeDevices;
5932 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005933 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5934 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005935 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005936 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005937 }
François Gaffiec005e562018-11-06 15:04:49 +01005938 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005939 devices.merge(curDevices);
5940 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005941 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005942 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005943 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005944 }
5945 }
Eric Laurente552edb2014-03-10 17:42:56 -07005946 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005947
Eric Laurentb0688d62018-08-14 15:49:18 -07005948 // Favor devices selected on active streams if any to report correct device in case of
5949 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005950 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005951 devices = activeDevices;
5952 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005953 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5954 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005955 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005956 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005957 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005958 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005959 }
jiabin9a3361e2019-10-01 09:38:30 -07005960 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5961 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005962}
5963
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005964status_t AudioPolicyManager::getDevicesForAttributes(
5965 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5966 if (devices == nullptr) {
5967 return BAD_VALUE;
5968 }
5969 // check dynamic policies but only for primary descriptors (secondary not used for audible
5970 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005971 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005972 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005973 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005974 if (status != OK) {
5975 return status;
5976 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005977 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5978 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5979 devices->push_back(device);
5980 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005981 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005982 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5983 for (const auto& device : curDevices) {
5984 devices->push_back(device->getDeviceTypeAddr());
5985 }
5986 return NO_ERROR;
5987}
5988
Eric Laurente0720872014-03-11 09:30:41 -07005989void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005990 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005991 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01005992 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005993 updateDevicesAndOutputs();
5994 break;
5995 default:
5996 break;
5997 }
5998}
5999
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006000uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006001
6002 // skip beacon mute management if a dedicated TTS output is available
6003 if (mTtsOutputAvailable) {
6004 return 0;
6005 }
6006
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006007 switch(event) {
6008 case STARTING_OUTPUT:
6009 mBeaconMuteRefCount++;
6010 break;
6011 case STOPPING_OUTPUT:
6012 if (mBeaconMuteRefCount > 0) {
6013 mBeaconMuteRefCount--;
6014 }
6015 break;
6016 case STARTING_BEACON:
6017 mBeaconPlayingRefCount++;
6018 break;
6019 case STOPPING_BEACON:
6020 if (mBeaconPlayingRefCount > 0) {
6021 mBeaconPlayingRefCount--;
6022 }
6023 break;
6024 }
6025
6026 if (mBeaconMuteRefCount > 0) {
6027 // any playback causes beacon to be muted
6028 return setBeaconMute(true);
6029 } else {
6030 // no other playback: unmute when beacon starts playing, mute when it stops
6031 return setBeaconMute(mBeaconPlayingRefCount == 0);
6032 }
6033}
6034
6035uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6036 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6037 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6038 // keep track of muted state to avoid repeating mute/unmute operations
6039 if (mBeaconMuted != mute) {
6040 // mute/unmute AUDIO_STREAM_TTS on all outputs
6041 ALOGV("\t muting %d", mute);
6042 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006043 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006044 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006045 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006046 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006047 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006048 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006049 maxLatency = latency;
6050 }
6051 }
6052 mBeaconMuted = mute;
6053 return maxLatency;
6054 }
6055 return 0;
6056}
6057
Eric Laurente0720872014-03-11 09:30:41 -07006058void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006059{
François Gaffiec005e562018-11-06 15:04:49 +01006060 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006061 mPreviousOutputs = mOutputs;
6062}
6063
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006064uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006065 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006066 uint32_t delayMs)
6067{
6068 // mute/unmute strategies using an incompatible device combination
6069 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6070 // if unmuting, unmute only after the specified delay
6071 if (outputDesc->isDuplicated()) {
6072 return 0;
6073 }
6074
6075 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006076 DeviceVector devices = outputDesc->devices();
6077 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006078
François Gaffiec005e562018-11-06 15:04:49 +01006079 auto productStrategies = mEngine->getOrderedProductStrategies();
6080 for (const auto &productStrategy : productStrategies) {
6081 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6082 DeviceVector curDevices =
6083 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6084 curDevices = curDevices.filter(outputDesc->supportedDevices());
6085 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006086 bool doMute = false;
6087
François Gaffiec005e562018-11-06 15:04:49 +01006088 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006089 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006090 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6091 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006092 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006093 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006094 }
Eric Laurent99401132014-05-07 19:48:15 -07006095 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006096 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006097 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006098 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006099 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006100 continue;
6101 }
François Gaffiec005e562018-11-06 15:04:49 +01006102 ALOGVV("%s() %s (curDevice %s)", __func__,
6103 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6104 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6105 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006106 if (mute) {
6107 // FIXME: should not need to double latency if volume could be applied
6108 // immediately by the audioflinger mixer. We must account for the delay
6109 // between now and the next time the audioflinger thread for this output
6110 // will process a buffer (which corresponds to one buffer size,
6111 // usually 1/2 or 1/4 of the latency).
6112 if (muteWaitMs < desc->latency() * 2) {
6113 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006114 }
6115 }
6116 }
6117 }
6118 }
6119 }
6120
Eric Laurent99401132014-05-07 19:48:15 -07006121 // temporary mute output if device selection changes to avoid volume bursts due to
6122 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006123 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006124 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6125 // temporary mute duration is conservatively set to 4 times the reported latency
6126 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6127 if (muteWaitMs < tempMuteWaitMs) {
6128 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006129 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006130 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6131 // make sure that we do not start the temporary mute period too early in case of
6132 // delayed device change
6133 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6134 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006135 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006136 }
6137 }
6138
Eric Laurente552edb2014-03-10 17:42:56 -07006139 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6140 if (muteWaitMs > delayMs) {
6141 muteWaitMs -= delayMs;
6142 usleep(muteWaitMs * 1000);
6143 return muteWaitMs;
6144 }
6145 return 0;
6146}
6147
François Gaffie11d30102018-11-02 16:09:09 +01006148uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6149 const DeviceVector &devices,
6150 bool force,
6151 int delayMs,
6152 audio_patch_handle_t *patchHandle,
6153 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006154{
François Gaffie11d30102018-11-02 16:09:09 +01006155 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006156 uint32_t muteWaitMs;
6157
6158 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006159 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6160 nullptr /* patchHandle */, requiresMuteCheck);
6161 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6162 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006163 return muteWaitMs;
6164 }
Eric Laurente552edb2014-03-10 17:42:56 -07006165
6166 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006167 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006168 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006169
François Gaffie11d30102018-11-02 16:09:09 +01006170 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6171
6172 if (!filteredDevices.isEmpty()) {
6173 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006174 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006175
6176 // if the outputs are not materially active, there is no need to mute.
6177 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006178 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006179 } else {
6180 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6181 muteWaitMs = 0;
6182 }
Eric Laurente552edb2014-03-10 17:42:56 -07006183
Eric Laurent79ea9582020-06-11 18:49:24 -07006184 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6185 // output profile or if new device is not supported AND previous device(s) is(are) still
6186 // available (otherwise reset device must be done on the output)
6187 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6188 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6189 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6190 // restore previous device after evaluating strategy mute state
6191 outputDesc->setDevices(prevDevices);
6192 return muteWaitMs;
6193 }
6194
Eric Laurente552edb2014-03-10 17:42:56 -07006195 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006196 // the requested device is AUDIO_DEVICE_NONE
6197 // OR the requested device is the same as current device
6198 // AND force is not specified
6199 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006200 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006201 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006202 !force && outputDesc->getPatchHandle() != 0) {
6203 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6204 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006205 return muteWaitMs;
6206 }
6207
François Gaffie11d30102018-11-02 16:09:09 +01006208 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006209
Eric Laurente552edb2014-03-10 17:42:56 -07006210 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006211 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006212 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006213 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006214 PatchBuilder patchBuilder;
6215 patchBuilder.addSource(outputDesc);
6216 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6217 for (const auto &filteredDevice : filteredDevices) {
6218 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006219 }
6220
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006221 // Add half reported latency to delayMs when muteWaitMs is null in order
6222 // to avoid disordered sequence of muting volume and changing devices.
6223 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6224 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006225 }
Eric Laurente552edb2014-03-10 17:42:56 -07006226
6227 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006228 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006229
6230 return muteWaitMs;
6231}
6232
Eric Laurentc75307b2015-03-17 15:29:32 -07006233status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006234 int delayMs,
6235 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006236{
Eric Laurent6a94d692014-05-20 11:18:06 -07006237 ssize_t index;
6238 if (patchHandle) {
6239 index = mAudioPatches.indexOfKey(*patchHandle);
6240 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006241 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006242 }
6243 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006244 return INVALID_OPERATION;
6245 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006246 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006247 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006248 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006249 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006250 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006251 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006252 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006253 return status;
6254}
6255
6256status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006257 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006258 bool force,
6259 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006260{
6261 status_t status = NO_ERROR;
6262
Eric Laurent1f2f2232014-06-02 12:01:23 -07006263 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006264 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6265 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006266
François Gaffie11d30102018-11-02 16:09:09 +01006267 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006268 PatchBuilder patchBuilder;
6269 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006270 // AUDIO_SOURCE_HOTWORD is for internal use only:
6271 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006272 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6273 auto result = usecase;
6274 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6275 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6276 }
6277 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006278 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006279 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006280 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006281 }
6282 }
6283 return status;
6284}
6285
Eric Laurent6a94d692014-05-20 11:18:06 -07006286status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6287 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006288{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006289 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006290 ssize_t index;
6291 if (patchHandle) {
6292 index = mAudioPatches.indexOfKey(*patchHandle);
6293 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006294 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006295 }
6296 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006297 return INVALID_OPERATION;
6298 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006299 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006300 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006301 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006302 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006303 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006304 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006305 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006306 return status;
6307}
6308
François Gaffie11d30102018-11-02 16:09:09 +01006309sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006310 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006311 audio_format_t& format,
6312 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006313 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006314{
6315 // Choose an input profile based on the requested capture parameters: select the first available
6316 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006317 //
6318 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6319 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006320
Glenn Kasten730b9262018-03-29 15:01:26 -07006321 sp<IOProfile> firstInexact;
6322 uint32_t updatedSamplingRate = 0;
6323 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6324 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006325 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006326 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006327 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006328 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006329 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006330 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006331 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006332 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006333 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006334 &channelMask /*updatedChannelMask*/,
6335 // FIXME ugly cast
6336 (audio_output_flags_t) flags,
6337 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006338 return profile;
6339 }
François Gaffie11d30102018-11-02 16:09:09 +01006340 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006341 samplingRate,
6342 &updatedSamplingRate,
6343 format,
6344 &updatedFormat,
6345 channelMask,
6346 &updatedChannelMask,
6347 // FIXME ugly cast
6348 (audio_output_flags_t) flags,
6349 false /*exactMatchRequiredForInputFlags*/)) {
6350 firstInexact = profile;
6351 }
6352
Eric Laurente552edb2014-03-10 17:42:56 -07006353 }
6354 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006355 if (firstInexact != nullptr) {
6356 samplingRate = updatedSamplingRate;
6357 format = updatedFormat;
6358 channelMask = updatedChannelMask;
6359 return firstInexact;
6360 }
Eric Laurente552edb2014-03-10 17:42:56 -07006361 return NULL;
6362}
6363
François Gaffieaaac0fd2018-11-22 17:56:39 +01006364float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6365 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006366 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006367 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006368{
jiabin9a3361e2019-10-01 09:38:30 -07006369 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006370
6371 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6372 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6373 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6374 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006375 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6376 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6377 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6378 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006379 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006380
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006381 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006382 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6383 mOutputs.isActive(ringVolumeSrc, 0)) {
6384 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006385 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006386 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006387 }
6388
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006389 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006390 if ((volumeSource != callVolumeSrc && (isInCall() ||
6391 mOutputs.isActiveLocally(callVolumeSrc))) &&
6392 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6393 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6394 volumeSource == alarmVolumeSrc ||
6395 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6396 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6397 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006398 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006399 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006400 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006401 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006402 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006403 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006404 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6405 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6406 // programmatically muted.
6407 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6408 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6409 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006410 bool exemptFromCapping =
6411 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6412 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006413 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6414 volumeSource, volumeDb);
6415 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006416 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6417 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6418 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006419 }
6420 }
Eric Laurente552edb2014-03-10 17:42:56 -07006421 // if a headset is connected, apply the following rules to ring tones and notifications
6422 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006423 // - always attenuate notifications volume by 6dB
6424 // - attenuate ring tones volume by 6dB unless music is not playing and
6425 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006426 // - if music is playing, always limit the volume to current music volume,
6427 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006428 if (!Intersection(deviceTypes,
6429 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6430 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006431 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6432 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006433 ((volumeSource == alarmVolumeSrc ||
6434 volumeSource == ringVolumeSrc) ||
6435 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6436 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6437 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6438 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6439 curves.canBeMuted()) {
6440
Eric Laurente552edb2014-03-10 17:42:56 -07006441 // when the phone is ringing we must consider that music could have been paused just before
6442 // by the music application and behave as if music was active if the last music track was
6443 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006444 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006445 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006446 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006447 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006448 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6449 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006450 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006451 float musicVolDb = computeVolume(musicCurves,
6452 musicVolumeSrc,
6453 musicCurves.getVolumeIndex(musicDevice),
6454 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006455 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6456 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6457 if (volumeDb > minVolDb) {
6458 volumeDb = minVolDb;
6459 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006460 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006461 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6462 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6463 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006464 // on A2DP, also ensure notification volume is not too low compared to media when
6465 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006466 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006467 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006468 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6469 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006470 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6471 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006472 }
6473 }
jiabin9a3361e2019-10-01 09:38:30 -07006474 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006475 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006476 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006477 }
6478 }
6479
François Gaffie43c73442018-11-08 08:21:55 +01006480 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006481}
6482
Eric Laurent3839bc02018-07-10 18:33:34 -07006483int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006484 VolumeSource fromVolumeSource,
6485 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006486{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006487 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006488 return srcIndex;
6489 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006490 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6491 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006492 float minSrc = (float)srcCurves.getVolumeIndexMin();
6493 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6494 float minDst = (float)dstCurves.getVolumeIndexMin();
6495 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006496
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006497 // preserve mute request or correct range
6498 if (srcIndex < minSrc) {
6499 if (srcIndex == 0) {
6500 return 0;
6501 }
6502 srcIndex = minSrc;
6503 } else if (srcIndex > maxSrc) {
6504 srcIndex = maxSrc;
6505 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006506 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6507}
6508
François Gaffieaaac0fd2018-11-22 17:56:39 +01006509status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6510 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006511 int index,
6512 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006513 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006514 int delayMs,
6515 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006516{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006517 // do not change actual attributes volume if the attributes is muted
6518 if (outputDesc->isMuted(volumeSource)) {
6519 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6520 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006521 return NO_ERROR;
6522 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006523 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6524 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6525 bool isVoiceVolSrc = callVolSrc == volumeSource;
6526 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6527
Eric Laurent2517af32020-11-25 15:31:27 +01006528 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006529 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006530 // if sco and call follow same curves, bypass forceUseForComm
6531 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006532 ((isVoiceVolSrc && isScoRequested) ||
6533 (isBtScoVolSrc && !isScoRequested))) {
6534 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6535 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006536 // Do not return an error here as AudioService will always set both voice call
6537 // and bluetooth SCO volumes due to stream aliasing.
6538 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006539 }
jiabin9a3361e2019-10-01 09:38:30 -07006540 if (deviceTypes.empty()) {
6541 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006542 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006543
jiabin9a3361e2019-10-01 09:38:30 -07006544 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6545 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006546 // Force VoIP volume to max for bluetooth SCO device except if muted
6547 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006548 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006549 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006550 }
jiabin9a3361e2019-10-01 09:38:30 -07006551 outputDesc->setVolume(
6552 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006553
François Gaffieaaac0fd2018-11-22 17:56:39 +01006554 if (isVoiceVolSrc || isBtScoVolSrc) {
Eric Laurente552edb2014-03-10 17:42:56 -07006555 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006556 // 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 +01006557 if (isVoiceVolSrc) {
6558 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006559 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006560 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006561 }
Eric Laurent18fba842016-03-31 14:41:26 -07006562 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006563 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6564 mLastVoiceVolume = voiceVolume;
6565 }
6566 }
Eric Laurente552edb2014-03-10 17:42:56 -07006567 return NO_ERROR;
6568}
6569
Eric Laurentc75307b2015-03-17 15:29:32 -07006570void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006571 const DeviceTypeSet& deviceTypes,
6572 int delayMs,
6573 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006574{
jiabincd510522020-01-22 09:40:55 -08006575 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006576 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6577 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6578 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006579 curves.getVolumeIndex(deviceTypes),
6580 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006581 }
6582}
6583
François Gaffiec005e562018-11-06 15:04:49 +01006584void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6585 bool on,
6586 const sp<AudioOutputDescriptor>& outputDesc,
6587 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006588 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006589{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006590 std::vector<VolumeSource> sourcesToMute;
6591 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6592 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6593 toString(attributes).c_str(), on, outputDesc->getId());
6594 VolumeSource source = toVolumeSource(attributes);
6595 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6596 sourcesToMute.push_back(source);
6597 }
Eric Laurente552edb2014-03-10 17:42:56 -07006598 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006599 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006600 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006601 }
6602
Eric Laurente552edb2014-03-10 17:42:56 -07006603}
6604
François Gaffieaaac0fd2018-11-22 17:56:39 +01006605void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6606 bool on,
6607 const sp<AudioOutputDescriptor>& outputDesc,
6608 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006609 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006610{
jiabin9a3361e2019-10-01 09:38:30 -07006611 if (deviceTypes.empty()) {
6612 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006613 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006614 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006615 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006616 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006617 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006618 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6619 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6620 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006621 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006622 }
6623 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006624 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6625 // ignored
6626 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006627 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006628 if (!outputDesc->isMuted(volumeSource)) {
6629 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006630 return;
6631 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006632 if (outputDesc->decMuteCount(volumeSource) == 0) {
6633 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006634 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006635 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006636 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006637 delayMs);
6638 }
6639 }
6640}
6641
François Gaffie53615e22015-03-19 09:24:12 +01006642bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6643{
François Gaffiec005e562018-11-06 15:04:49 +01006644 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006645 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6646 return true;
6647 }
6648
6649 // has known usage?
6650 switch (paa->usage) {
6651 case AUDIO_USAGE_UNKNOWN:
6652 case AUDIO_USAGE_MEDIA:
6653 case AUDIO_USAGE_VOICE_COMMUNICATION:
6654 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6655 case AUDIO_USAGE_ALARM:
6656 case AUDIO_USAGE_NOTIFICATION:
6657 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6658 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6659 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6660 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6661 case AUDIO_USAGE_NOTIFICATION_EVENT:
6662 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6663 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6664 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6665 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006666 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006667 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006668 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006669 case AUDIO_USAGE_EMERGENCY:
6670 case AUDIO_USAGE_SAFETY:
6671 case AUDIO_USAGE_VEHICLE_STATUS:
6672 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006673 break;
6674 default:
6675 return false;
6676 }
6677 return true;
6678}
6679
François Gaffie2110e042015-03-24 08:41:51 +01006680audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6681{
6682 return mEngine->getForceUse(usage);
6683}
6684
6685bool AudioPolicyManager::isInCall()
6686{
6687 return isStateInCall(mEngine->getPhoneState());
6688}
6689
6690bool AudioPolicyManager::isStateInCall(int state)
6691{
6692 return is_state_in_call(state);
6693}
6694
Eric Laurent74b71512019-11-06 17:21:57 -08006695bool AudioPolicyManager::isCallAudioAccessible()
6696{
6697 audio_mode_t mode = mEngine->getPhoneState();
6698 return (mode == AUDIO_MODE_IN_CALL)
6699 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6700 || (mode == AUDIO_MODE_CALL_SCREEN);
6701}
6702
Eric Laurentd60560a2015-04-10 11:31:20 -07006703void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6704{
6705 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006706 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006707 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006708 sourceDesc->sinkDevice()->equals(deviceDesc))
6709 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006710 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006711 }
6712 }
6713
6714 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6715 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6716 bool release = false;
6717 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6718 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6719 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6720 source->ext.device.type == deviceDesc->type()) {
6721 release = true;
6722 }
6723 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006724 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006725 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6726 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6727 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006728 sink->ext.device.type == deviceDesc->type() &&
6729 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6730 || strncmp(sink->ext.device.address, address,
6731 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006732 release = true;
6733 }
6734 }
6735 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006736 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6737 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006738 }
6739 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006740
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006741 mInputs.clearSessionRoutesForDevice(deviceDesc);
6742
Francois Gaffie716e1432019-01-14 16:58:59 +01006743 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006744}
6745
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006746void AudioPolicyManager::modifySurroundFormats(
6747 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006748 std::unordered_set<audio_format_t> enforcedSurround(
6749 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006750 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6751 for (const auto& pair : mConfig.getSurroundFormats()) {
6752 allSurround.insert(pair.first);
6753 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6754 }
Phil Burk09bc4612016-02-24 15:58:15 -08006755
6756 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6757 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006758 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006759 // This is the resulting set of formats depending on the surround mode:
6760 // 'all surround' = allSurround
6761 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6762 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6763 // 'manual surround' = mManualSurroundFormats
6764 // AUTO: formats v 'enforced surround'
6765 // ALWAYS: formats v 'all surround' v 'enforced surround'
6766 // NEVER: formats ^ 'non-surround'
6767 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006768
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006769 std::unordered_set<audio_format_t> formatSet;
6770 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6771 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006772 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006773 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006774 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006775 formatSet.insert(*formatIter);
6776 }
6777 }
6778 } else {
6779 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6780 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006781 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006782
jiabin81772902018-04-02 17:52:27 -07006783 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006784 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006785 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6786 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6787 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006788 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006789 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6790 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6791 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006792 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006793 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006794 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006795 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006796 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006797 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006798}
6799
jiabin06e4bab2019-07-29 10:13:34 -07006800void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6801 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006802 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6803 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6804
6805 // If NEVER, then remove support for channelMasks > stereo.
6806 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006807 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6808 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006809 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006810 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006811 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006812 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006813 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006814 }
6815 }
jiabin81772902018-04-02 17:52:27 -07006816 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6817 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6818 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006819 bool supports5dot1 = false;
6820 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006821 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006822 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6823 supports5dot1 = true;
6824 break;
6825 }
6826 }
6827 // If not then add 5.1 support.
6828 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006829 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006830 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006831 }
Phil Burk09bc4612016-02-24 15:58:15 -08006832 }
6833}
6834
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006835void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006836 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006837 AudioProfileVector &profiles)
6838{
6839 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006840 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006841
François Gaffie112b0af2015-11-19 16:13:25 +01006842 // Format MUST be checked first to update the list of AudioProfile
6843 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006844 reply = mpClientInterface->getParameters(
6845 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006846 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006847 AudioParameter repliedParameters(reply);
6848 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006849 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006850 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6851 return;
6852 }
Phil Burk09bc4612016-02-24 15:58:15 -08006853 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006854 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006855 if (device == AUDIO_DEVICE_OUT_HDMI
6856 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006857 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006858 }
jiabin3e277cc2019-09-10 14:27:34 -07006859 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006860 }
François Gaffie112b0af2015-11-19 16:13:25 +01006861
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006862 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006863 ChannelMaskSet channelMasks;
6864 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006865 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006866 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006867
6868 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006869 reply = mpClientInterface->getParameters(
6870 ioHandle,
6871 requestedParameters.toString() + ";" +
6872 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006873 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006874 AudioParameter repliedParameters(reply);
6875 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006876 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006877 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006878 }
6879 }
6880 if (profiles.hasDynamicChannelsFor(format)) {
6881 reply = mpClientInterface->getParameters(ioHandle,
6882 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006883 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006884 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006885 AudioParameter repliedParameters(reply);
6886 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006887 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006888 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006889 if (device == AUDIO_DEVICE_OUT_HDMI
6890 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006891 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006892 }
François Gaffie112b0af2015-11-19 16:13:25 +01006893 }
6894 }
jiabin3e277cc2019-09-10 14:27:34 -07006895 addDynamicAudioProfileAndSort(
6896 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006897 }
6898}
Eric Laurentd60560a2015-04-10 11:31:20 -07006899
Mikhail Naganovdc769682018-05-04 15:34:08 -07006900status_t AudioPolicyManager::installPatch(const char *caller,
6901 audio_patch_handle_t *patchHandle,
6902 AudioIODescriptorInterface *ioDescriptor,
6903 const struct audio_patch *patch,
6904 int delayMs)
6905{
6906 ssize_t index = mAudioPatches.indexOfKey(
6907 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6908 *patchHandle : ioDescriptor->getPatchHandle());
6909 sp<AudioPatch> patchDesc;
6910 status_t status = installPatch(
6911 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6912 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006913 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006914 }
6915 return status;
6916}
6917
6918status_t AudioPolicyManager::installPatch(const char *caller,
6919 ssize_t index,
6920 audio_patch_handle_t *patchHandle,
6921 const struct audio_patch *patch,
6922 int delayMs,
6923 uid_t uid,
6924 sp<AudioPatch> *patchDescPtr)
6925{
6926 sp<AudioPatch> patchDesc;
6927 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6928 if (index >= 0) {
6929 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006930 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006931 }
6932
6933 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6934 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6935 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6936 if (status == NO_ERROR) {
6937 if (index < 0) {
6938 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006939 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006940 } else {
6941 patchDesc->mPatch = *patch;
6942 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006943 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006944 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006945 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006946 }
6947 nextAudioPortGeneration();
6948 mpClientInterface->onAudioPatchListUpdate();
6949 }
6950 if (patchDescPtr) *patchDescPtr = patchDesc;
6951 return status;
6952}
6953
jiabinbce0c1d2020-10-05 11:20:18 -07006954bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6955{
6956 const TrackClientVector activeClients = output->getActiveClients();
6957 if (activeClients.empty()) {
6958 return true;
6959 }
6960 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6961 if (index < 0) {
6962 ALOGE("%s, no audio patch found while there are active clients on output %d",
6963 __func__, output->getId());
6964 return false;
6965 }
6966 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6967 DeviceVector routedDevices;
6968 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6969 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6970 patchDesc->mPatch.sinks[i].id);
6971 if (device == nullptr) {
6972 ALOGE("%s, no audio device found with id(%d)",
6973 __func__, patchDesc->mPatch.sinks[i].id);
6974 return false;
6975 }
6976 routedDevices.add(device);
6977 }
6978 for (const auto& client : activeClients) {
6979 // TODO: b/175343099 only travel the valid client
6980 sp<DeviceDescriptor> preferredDevice =
6981 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6982 if (mEngine->getOutputDevicesForAttributes(
6983 client->attributes(), preferredDevice, false) == routedDevices) {
6984 return false;
6985 }
6986 }
6987 return true;
6988}
6989
6990sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
6991 const sp<IOProfile>& profile, const DeviceVector& devices)
6992{
6993 for (const auto& device : devices) {
6994 // TODO: This should be checking if the profile supports the device combo.
6995 if (!profile->supportsDevice(device)) {
6996 return nullptr;
6997 }
6998 }
6999 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7000 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02007001 status_t status = desc->open(nullptr /* halConfig */, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007002 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7003 if (status != NO_ERROR) {
7004 return nullptr;
7005 }
7006
7007 // Here is where the out_set_parameters() for card & device gets called
7008 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7009 const audio_devices_t deviceType = device->type();
7010 const String8 &address = String8(device->address().c_str());
7011 if (!address.isEmpty()) {
7012 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7013 mpClientInterface->setParameters(output, String8(param));
7014 free(param);
7015 }
7016 updateAudioProfiles(device, output, profile->getAudioProfiles());
7017 if (!profile->hasValidAudioProfile()) {
7018 ALOGW("%s() missing param", __func__);
7019 desc->close();
7020 return nullptr;
7021 } else if (profile->hasDynamicAudioProfile()) {
7022 desc->close();
7023 output = AUDIO_IO_HANDLE_NONE;
7024 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7025 profile->pickAudioProfile(
7026 config.sample_rate, config.channel_mask, config.format);
7027 config.offload_info.sample_rate = config.sample_rate;
7028 config.offload_info.channel_mask = config.channel_mask;
7029 config.offload_info.format = config.format;
7030
Eric Laurentf1f22e72021-07-13 14:04:14 +02007031 status = desc->open(&config, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007032 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7033 if (status != NO_ERROR) {
7034 return nullptr;
7035 }
7036 }
7037
7038 addOutput(output, desc);
7039 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7040 sp<AudioPolicyMix> policyMix;
7041 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7042 policyMix->setOutput(desc);
7043 desc->mPolicyMix = policyMix;
7044 } else {
7045 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7046 address.string());
7047 }
7048
7049 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7050 // no duplicated output for direct outputs and
7051 // outputs used by dynamic policy mixes
7052 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7053
7054 //TODO: configure audio effect output stage here
7055
7056 // open a duplicating output thread for the new output and the primary output
7057 sp<SwAudioOutputDescriptor> dupOutputDesc =
7058 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7059 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7060 if (status == NO_ERROR) {
7061 // add duplicated output descriptor
7062 addOutput(duplicatedOutput, dupOutputDesc);
7063 } else {
7064 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7065 mPrimaryOutput->mIoHandle, output);
7066 desc->close();
7067 removeOutput(output);
7068 nextAudioPortGeneration();
7069 return nullptr;
7070 }
7071 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007072 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7073 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7074 mPrimaryOutput = desc;
7075 }
jiabinbce0c1d2020-10-05 11:20:18 -07007076 return desc;
7077}
7078
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007079} // namespace android