blob: 4ce7851e3d30bab5f906fa0729be43a61ad7b797 [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
Pattye4981552021-11-04 21:01:03 +0800528status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
529 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800530{
Pattye4981552021-11-04 21:01:03 +0800531 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
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 }
Pattye4981552021-11-04 21:01:03 +0800540
541 DeviceTypeSet audioDeviceSet;
542
543 switch(device) {
544 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
545 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
546 break;
547 case AUDIO_DEVICE_OUT_BLE_HEADSET:
548 audioDeviceSet = getAudioDeviceOutAllBleSet();
549 break;
550 default:
551 ALOGE("%s() device type 0x%08x not supported", __func__, device);
552 return BAD_VALUE;
553 }
554
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattye4981552021-11-04 21:01:03 +0800556 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800557 for (const auto& device : declaredDevices) {
558 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800559 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800560 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800561 return status;
562}
563
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100564DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
565{
566 DeviceVector rxSinkdevices{};
567 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
568 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
569 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
570 auto rxSinkDevice = rxSinkdevices.itemAt(0);
571 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
572 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
573 // retrieve Rx Source device descriptor
574 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
575 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
576
577 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
578 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
579 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
580 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
581 return DeviceVector(rxSinkDevice);
582 }
583 }
584 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
585 // the device returned is not necessarily reachable via this output
586 // (filter later by setOutputDevices())
587 return getNewOutputDevices(mPrimaryOutput, fromCache);
588}
589
590status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
591{
592 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
593 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
594 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
595 }
596 return INVALID_OPERATION;
597}
598
599status_t AudioPolicyManager::updateCallRoutingInternal(
600 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700601{
602 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100603 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700604 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700605 if(!hasPrimaryOutput() ||
606 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100607 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700608 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100609 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100610
Francois Gaffie716e1432019-01-14 16:58:59 +0100611 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100612 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100614
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100615 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100616 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200618 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 // release TX patch if any
620 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100621 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 mCallTxPatch.clear();
623 }
624
François Gaffie9eb18552018-11-05 10:33:26 +0100625 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700626 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100627 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700628 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100629 // retrieve Rx Source and Tx Sink device descriptors
630 sp<DeviceDescriptor> rxSourceDevice =
631 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
632 String8(),
633 AUDIO_FORMAT_DEFAULT);
634 sp<DeviceDescriptor> txSinkDevice =
635 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
636 String8(),
637 AUDIO_FORMAT_DEFAULT);
638
639 // RX and TX Telephony device are declared by Primary Audio HAL
640 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
641 (telephonyRxModule->getHalVersionMajor() >= 3)) {
642 if (rxSourceDevice == 0 || txSinkDevice == 0) {
643 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100644 ALOGE("%s() no telephony Tx and/or RX device", __func__);
645 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100646 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100647 // createAudioPatchInternal now supports both HW / SW bridging
648 createRxPatch = true;
649 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100650 } else {
651 // If the RX device is on the primary HW module, then use legacy routing method for
652 // voice calls via setOutputDevice() on primary output.
653 // Otherwise, create two audio patches for TX and RX path.
654 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
655 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700656 // If the TX device is also on the primary HW module, setOutputDevice() will take care
657 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100658 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
659 (txSinkDevice != 0);
660 }
661 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
662 // Otherwise, create two audio patches for TX and RX path.
663 if (!createRxPatch) {
664 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700665 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200666 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800667 // If the TX device is on the primary HW module but RX device is
668 // on other HW module, SinkMetaData of telephony input should handle it
669 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700671 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100672 // terminate active capture if on the same HW module as the call TX source device
673 // FIXME: would be better to refine to only inputs whose profile connects to the
674 // call TX device but this information is not in the audio patch and logic here must be
675 // symmetric to the one in startInput()
676 for (const auto& activeDesc : mInputs.getActiveInputs()) {
677 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
678 closeActiveClients(activeDesc);
679 }
680 }
François Gaffie9eb18552018-11-05 10:33:26 +0100681 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800682 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683 if (waitMs != nullptr) {
684 *waitMs = muteWaitMs;
685 }
686 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800687}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700688
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800689sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100690 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700691 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692
François Gaffie11d30102018-11-02 16:09:09 +0100693 if (device == nullptr) {
694 return nullptr;
695 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100696
697 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800698 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100699 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800700 addSource(mAvailableInputDevices.getDevice(
701 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800702 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100703 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800704 addSink(mAvailableOutputDevices.getDevice(
705 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800706 }
707
François Gaffieafd4cea2019-11-18 15:50:22 +0100708 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
709 status_t status =
710 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
711 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
712 if (status != NO_ERROR || index < 0) {
713 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
714 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800715 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100716 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800717}
718
Mikhail Naganov100f0122018-11-29 11:22:16 -0800719bool AudioPolicyManager::isDeviceOfModule(
720 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
721 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
722 if (module != 0) {
723 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
724 .indexOf(devDesc) != NAME_NOT_FOUND
725 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
726 .indexOf(devDesc) != NAME_NOT_FOUND;
727 }
728 return false;
729}
730
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200731void AudioPolicyManager::connectTelephonyRxAudioSource()
732{
733 disconnectTelephonyRxAudioSource();
734 const struct audio_port_config source = {
735 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
736 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
737 };
738 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
739 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
740 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
741}
742
743void AudioPolicyManager::disconnectTelephonyRxAudioSource()
744{
745 stopAudioSource(mCallRxSourceClientPort);
746 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
747}
748
Eric Laurente0720872014-03-11 09:30:41 -0700749void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700750{
751 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100752 // store previous phone state for management of sonification strategy below
753 int oldState = mEngine->getPhoneState();
754
755 if (mEngine->setPhoneState(state) != NO_ERROR) {
756 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 return;
758 }
François Gaffie2110e042015-03-24 08:41:51 +0100759 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700760 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700761 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700762 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800763 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700764 }
765
François Gaffie2110e042015-03-24 08:41:51 +0100766 /**
767 * Switching to or from incall state or switching between telephony and VoIP lead to force
768 * routing command.
769 */
Eric Laurent74b71512019-11-06 17:21:57 -0800770 bool force = ((isStateInCall(oldState) != isStateInCall(state))
771 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700772
773 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700774 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700775
Eric Laurente552edb2014-03-10 17:42:56 -0700776 int delayMs = 0;
777 if (isStateInCall(state)) {
778 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100779 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
780 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700781 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700782 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700783 // mute media and sonification strategies and delay device switch by the largest
784 // latency of any output where either strategy is active.
785 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100786 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
787 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
788 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700789 (delayMs < (int)desc->latency()*2)) {
790 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
François Gaffiec005e562018-11-06 15:04:49 +0100792 setStrategyMute(musicStrategy, true, desc);
793 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
794 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
795 nullptr, true /*fromCache*/).types());
796 setStrategyMute(sonificationStrategy, true, desc);
797 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
798 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
799 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700800 }
801 }
802
Eric Laurent87ffa392015-05-22 10:32:38 -0700803 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700804 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100805 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700806 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100807 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
808 // force routing command to audio hardware when ending call
809 // even if no device change is needed
810 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
811 rxDevices = mPrimaryOutput->devices();
812 }
813 if (oldState == AUDIO_MODE_IN_CALL) {
814 disconnectTelephonyRxAudioSource();
815 if (mCallTxPatch != 0) {
816 releaseAudioPatchInternal(mCallTxPatch->getHandle());
817 mCallTxPatch.clear();
818 }
819 }
François Gaffie11d30102018-11-02 16:09:09 +0100820 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700821 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700822 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700823
824 // reevaluate routing on all outputs in case tracks have been started during the call
825 for (size_t i = 0; i < mOutputs.size(); i++) {
826 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100827 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700828 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100829 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700830 }
831 }
832
Eric Laurente552edb2014-03-10 17:42:56 -0700833 if (isStateInCall(state)) {
834 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700835 // force reevaluating accessibility routing when call starts
836 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700837 }
838
839 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100840 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
841 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700842}
843
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700844audio_mode_t AudioPolicyManager::getPhoneState() {
845 return mEngine->getPhoneState();
846}
847
Eric Laurente0720872014-03-11 09:30:41 -0700848void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100849 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700850{
François Gaffie2110e042015-03-24 08:41:51 +0100851 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700852 if (config == mEngine->getForceUse(usage)) {
853 return;
854 }
Eric Laurente552edb2014-03-10 17:42:56 -0700855
François Gaffie2110e042015-03-24 08:41:51 +0100856 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
857 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
858 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700859 }
François Gaffie2110e042015-03-24 08:41:51 +0100860 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
861 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
862 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700863
864 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700865 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800866
Eric Laurent22fcda22019-05-17 16:28:47 -0700867 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
868 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
869 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
870 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
871 }
872
Eric Laurentdc462862016-07-19 12:29:53 -0700873 //FIXME: workaround for truncated touch sounds
874 // to be removed when the problem is handled by system UI
875 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700876 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
877 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
878 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700879
880 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100881 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700882}
883
Eric Laurente0720872014-03-11 09:30:41 -0700884void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700885{
886 ALOGV("setSystemProperty() property %s, value %s", property, value);
887}
888
Michael Chana94fbb22018-04-24 14:31:19 +1000889// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
890// search to profiles for direct outputs.
891sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100892 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000893 uint32_t samplingRate,
894 audio_format_t format,
895 audio_channel_mask_t channelMask,
896 audio_output_flags_t flags,
897 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700898{
Michael Chana94fbb22018-04-24 14:31:19 +1000899 if (directOnly) {
900 // only retain flags that will drive the direct output profile selection
901 // if explicitly requested
902 static const uint32_t kRelevantFlags =
903 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700904 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000905 flags =
906 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
907 }
Eric Laurent861a6282015-05-18 15:40:16 -0700908
909 sp<IOProfile> profile;
910
Mikhail Naganovd4120142017-12-06 15:49:22 -0800911 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800912 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100913 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700914 samplingRate, NULL /*updatedSamplingRate*/,
915 format, NULL /*updatedFormat*/,
916 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700917 flags)) {
918 continue;
919 }
920 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100921 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700922 continue;
923 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800924 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700925 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800926 continue;
927 }
Michael Chana94fbb22018-04-24 14:31:19 +1000928 if (!directOnly) return curProfile;
929 // when searching for direct outputs, if several profiles are compatible, give priority
930 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100931 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700932 continue;
933 }
934 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100935 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700936 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700937 }
Eric Laurente552edb2014-03-10 17:42:56 -0700938 }
939 }
Eric Laurent861a6282015-05-18 15:40:16 -0700940 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700941}
942
Eric Laurentf4e63452017-11-06 19:31:46 +0000943audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700944{
François Gaffiec005e562018-11-06 15:04:49 +0100945 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800946
947 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
948 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
949 // format, flags, etc. This may result in some discrepancy for functions that utilize
950 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
951 // and AudioSystem::getOutputSamplingRate().
952
François Gaffie11d30102018-11-02 16:09:09 +0100953 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700954 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700955
François Gaffie11d30102018-11-02 16:09:09 +0100956 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
957 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000958 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700959}
960
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700961status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
962 const audio_attributes_t *srcAttr,
963 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700965 if (srcAttr != NULL) {
966 if (!isValidAttributes(srcAttr)) {
967 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
968 __func__,
969 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
970 srcAttr->tags);
971 return BAD_VALUE;
972 }
973 *dstAttr = *srcAttr;
974 } else {
975 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
976 ALOGE("%s: invalid stream type", __func__);
977 return BAD_VALUE;
978 }
François Gaffiec005e562018-11-06 15:04:49 +0100979 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700980 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700981
982 // Only honor audibility enforced when required. The client will be
983 // forced to reconnect if the forced usage changes.
984 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700985 dstAttr->flags = static_cast<audio_flags_mask_t>(
986 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700987 }
988
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700989 return NO_ERROR;
990}
991
Kevin Rocard153f92d2018-12-18 18:33:28 -0800992status_t AudioPolicyManager::getOutputForAttrInt(
993 audio_attributes_t *resultAttr,
994 audio_io_handle_t *output,
995 audio_session_t session,
996 const audio_attributes_t *attr,
997 audio_stream_type_t *stream,
998 uid_t uid,
999 const audio_config_t *config,
1000 audio_output_flags_t *flags,
1001 audio_port_handle_t *selectedDeviceId,
1002 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001003 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001004 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001005{
François Gaffiec005e562018-11-06 15:04:49 +01001006 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001007 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001008 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001009 const sp<DeviceDescriptor> requestedDevice =
1010 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1011
Eric Laurent8a1095a2019-11-08 14:44:16 -08001012 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001013 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1014 if (status != NO_ERROR) {
1015 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001016 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001017 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001018 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001019 }
François Gaffiec005e562018-11-06 15:04:49 +01001020 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001021
François Gaffiec005e562018-11-06 15:04:49 +01001022 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1023 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001024
Kevin Rocard153f92d2018-12-18 18:33:28 -08001025 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1026 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1027 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001028 sp<AudioPolicyMix> primaryMix;
1029 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001030 if (status != OK) {
1031 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001032 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001033
Kevin Rocard153f92d2018-12-18 18:33:28 -08001034 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001035 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001036
1037 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001038 if ((usePrimaryOutputFromPolicyMixes
1039 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001040 && !audio_is_linear_pcm(config->format)) {
1041 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001042 return BAD_VALUE;
1043 }
1044 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001045 sp<DeviceDescriptor> deviceDesc =
1046 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1047 primaryMix->mDeviceAddress,
1048 AUDIO_FORMAT_DEFAULT);
1049 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001050 if (deviceDesc != nullptr
1051 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001052 audio_io_handle_t newOutput;
1053 status = openDirectOutput(
1054 *stream, session, config,
1055 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1056 DeviceVector(deviceDesc), &newOutput);
1057 if (status != NO_ERROR) {
1058 policyDesc = nullptr;
1059 } else {
1060 policyDesc = mOutputs.valueFor(newOutput);
1061 primaryMix->setOutput(policyDesc);
1062 }
1063 }
1064 if (policyDesc != nullptr) {
1065 policyDesc->mPolicyMix = primaryMix;
1066 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001067 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001068
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001069 ALOGV("getOutputForAttr() returns output %d", *output);
1070 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1071 *outputType = API_OUT_MIX_PLAYBACK;
1072 } else {
1073 *outputType = API_OUTPUT_LEGACY;
1074 }
1075 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001076 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001077 }
François Gaffiec005e562018-11-06 15:04:49 +01001078 // Virtual sources must always be dynamicaly or explicitly routed
1079 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1080 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1081 return BAD_VALUE;
1082 }
1083 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1084 // in order to let the choice of the order to future vendor engine
1085 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001086
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001087 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001088 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001089 }
1090
Nadav Barb2f18162018-07-18 13:01:53 +03001091 // Set incall music only if device was explicitly set, and fallback to the device which is
1092 // chosen by the engine if not.
1093 // FIXME: provide a more generic approach which is not device specific and move this back
1094 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001095 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001096 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001097 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001098 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001099 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001100 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001101 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001102 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001103 }
1104 }
1105
François Gaffiec005e562018-11-06 15:04:49 +01001106 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1107 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1108 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001109
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001110 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001111 if (!msdDevices.isEmpty()) {
1112 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001113 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001114 ALOGV("%s() Using MSD devices %s instead of devices %s",
1115 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001116 } else {
1117 *output = AUDIO_IO_HANDLE_NONE;
1118 }
1119 }
1120 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001121 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001122 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001123 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001124 if (*output == AUDIO_IO_HANDLE_NONE) {
1125 return INVALID_OPERATION;
1126 }
Paul McLeanaa981192015-03-21 09:55:15 -07001127
François Gaffiec005e562018-11-06 15:04:49 +01001128 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001129 for (auto &outputDevice : outputDevices) {
1130 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1131 *selectedDeviceId = outputDevice->getId();
1132 break;
1133 }
1134 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001135
Eric Laurent8a1095a2019-11-08 14:44:16 -08001136 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1137 *outputType = API_OUTPUT_TELEPHONY_TX;
1138 } else {
1139 *outputType = API_OUTPUT_LEGACY;
1140 }
1141
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001142 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1143
1144 return NO_ERROR;
1145}
1146
1147status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1148 audio_io_handle_t *output,
1149 audio_session_t session,
1150 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001151 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001152 const audio_config_t *config,
1153 audio_output_flags_t *flags,
1154 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001155 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001156 std::vector<audio_io_handle_t> *secondaryOutputs,
1157 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158{
1159 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1160 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1161 return INVALID_OPERATION;
1162 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001163 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001164 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001165 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001166 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001167 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001168 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001169 const sp<DeviceDescriptor> requestedDevice =
1170 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1171
1172 // Prevent from storing invalid requested device id in clients
1173 const audio_port_handle_t sanitizedRequestedPortId =
1174 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1175 *selectedDeviceId = sanitizedRequestedPortId;
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001178 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001179 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001180 if (status != NO_ERROR) {
1181 return status;
1182 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001183 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 if (secondaryOutputs != nullptr) {
1185 for (auto &secondaryMix : secondaryMixes) {
1186 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1187 if (outputDesc != nullptr &&
1188 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1189 secondaryOutputs->push_back(outputDesc->mIoHandle);
1190 weakSecondaryOutputDescs.push_back(outputDesc);
1191 }
1192 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001193 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001194
Eric Laurent8fc147b2018-07-22 19:13:55 -07001195 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001196 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001197 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001198 };
jiabin4ef93452019-09-10 14:29:54 -07001199 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200
Eric Laurentc209fe42020-06-05 18:11:23 -07001201 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001202 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001203 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001204 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001205 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001206 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001207 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001208 std::move(weakSecondaryOutputDescs),
1209 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001210 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001211
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001212 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1213 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001214
Eric Laurente83b55d2014-11-14 10:06:21 -08001215 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001216}
1217
Eric Laurentc529cf62020-04-17 18:19:10 -07001218status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1219 audio_session_t session,
1220 const audio_config_t *config,
1221 audio_output_flags_t flags,
1222 const DeviceVector &devices,
1223 audio_io_handle_t *output) {
1224
1225 *output = AUDIO_IO_HANDLE_NONE;
1226
1227 // skip direct output selection if the request can obviously be attached to a mixed output
1228 // and not explicitly requested
1229 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1230 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1231 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1232 return NAME_NOT_FOUND;
1233 }
1234
1235 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1236 // This prevents creating an offloaded track and tearing it down immediately after start
1237 // when audioflinger detects there is an active non offloadable effect.
1238 // FIXME: We should check the audio session here but we do not have it in this context.
1239 // This may prevent offloading in rare situations where effects are left active by apps
1240 // in the background.
1241 sp<IOProfile> profile;
1242 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1243 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1244 profile = getProfileForOutput(
1245 devices, config->sample_rate, config->format, config->channel_mask,
1246 flags, true /* directOnly */);
1247 }
1248
1249 if (profile == nullptr) {
1250 return NAME_NOT_FOUND;
1251 }
1252
1253 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1254 for (size_t i = 0; i < mOutputs.size(); i++) {
1255 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1256 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1257 // reuse direct output if currently open by the same client
1258 // and configured with same parameters
1259 if ((config->sample_rate == desc->getSamplingRate()) &&
1260 (config->format == desc->getFormat()) &&
1261 (config->channel_mask == desc->getChannelMask()) &&
1262 (session == desc->mDirectClientSession)) {
1263 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001264 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001265 mOutputs.keyAt(i), session);
1266 *output = mOutputs.keyAt(i);
1267 return NO_ERROR;
1268 }
1269 }
1270 }
1271
1272 if (!profile->canOpenNewIo()) {
1273 return NAME_NOT_FOUND;
1274 }
1275
1276 sp<SwAudioOutputDescriptor> outputDesc =
1277 new SwAudioOutputDescriptor(profile, mpClientInterface);
1278
Michael Chan6fb34492020-12-08 15:44:49 +11001279 // An MSD patch may be using the only output stream that can service this request. Release
1280 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001281 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001282
1283 status_t status = outputDesc->open(config, devices, stream, flags, output);
1284
1285 // only accept an output with the requested parameters
1286 if (status != NO_ERROR ||
1287 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1288 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1289 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1290 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1291 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1292 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1293 config->channel_mask, outputDesc->getChannelMask());
1294 if (*output != AUDIO_IO_HANDLE_NONE) {
1295 outputDesc->close();
1296 }
1297 // fall back to mixer output if possible when the direct output could not be open
1298 if (audio_is_linear_pcm(config->format) &&
1299 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1300 return NAME_NOT_FOUND;
1301 }
1302 *output = AUDIO_IO_HANDLE_NONE;
1303 return BAD_VALUE;
1304 }
1305 outputDesc->mDirectOpenCount = 1;
1306 outputDesc->mDirectClientSession = session;
1307
1308 addOutput(*output, outputDesc);
1309 mPreviousOutputs = mOutputs;
1310 ALOGV("%s returns new direct output %d", __func__, *output);
1311 mpClientInterface->onAudioPortListUpdate();
1312 return NO_ERROR;
1313}
1314
François Gaffie11d30102018-11-02 16:09:09 +01001315audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1316 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001317 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001318 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001319 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001320 audio_output_flags_t *flags,
1321 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001322{
Andy Hungc88b0642018-04-27 15:42:35 -07001323 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001324
jiabine375d412019-02-26 12:54:53 -08001325 // Discard haptic channel mask when forcing muting haptic channels.
1326 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001327 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1328 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001329
Eric Laurente552edb2014-03-10 17:42:56 -07001330 // open a direct output if required by specified parameters
1331 //force direct flag if offload flag is set: offloading implies a direct output stream
1332 // and all common behaviors are driven by checking only the direct flag
1333 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001334 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1335 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001336 }
Nadav Bar766fb022018-01-07 12:18:03 +02001337 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1338 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001339 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001340 // only allow deep buffering for music stream type
1341 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001342 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001343 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001344 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001345 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1346 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001347 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001348 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001349 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001350 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001351 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001352 audio_is_linear_pcm(config->format) &&
1353 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001354 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001355 AUDIO_OUTPUT_FLAG_DIRECT);
1356 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001357 }
Eric Laurente552edb2014-03-10 17:42:56 -07001358
Eric Laurentc529cf62020-04-17 18:19:10 -07001359 audio_config_t directConfig = *config;
1360 directConfig.channel_mask = channelMask;
1361 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1362 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001363 return output;
1364 }
1365
Eric Laurent14cbfca2016-03-17 09:42:16 -07001366 // A request for HW A/V sync cannot fallback to a mixed output because time
1367 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001368 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001369 return AUDIO_IO_HANDLE_NONE;
1370 }
1371
Eric Laurente552edb2014-03-10 17:42:56 -07001372 // ignoring channel mask due to downmix capability in mixer
1373
1374 // open a non direct output
1375
1376 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001377 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001378 // get which output is suitable for the specified stream. The actual
1379 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001380 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001381
Eric Laurent8838a382014-09-08 16:44:28 -07001382 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001383 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001384 output = selectOutput(
1385 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001386 }
François Gaffie11d30102018-11-02 16:09:09 +01001387 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001388 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001389 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001390
Eric Laurente552edb2014-03-10 17:42:56 -07001391 return output;
1392}
1393
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001394sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001395 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1396 mAvailableInputDevices);
1397 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1398}
1399
1400DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1401 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1402 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001403}
1404
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001405const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001406 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001407 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1408 if (msdModule != 0) {
1409 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1410 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1411 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1412 const struct audio_port_config *source = &patch->mPatch.sources[j];
1413 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1414 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001415 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001416 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001417 }
1418 }
1419 }
1420 return msdPatches;
1421}
1422
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001423status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1424 const InputProfileCollection &inputProfiles,
1425 const OutputProfileCollection &outputProfiles,
1426 const sp<DeviceDescriptor> &sourceDevice,
1427 const sp<DeviceDescriptor> &sinkDevice,
1428 AudioProfileVector& sourceProfiles,
1429 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001430 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001431 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001432 return NO_INIT;
1433 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001434 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001435 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001436 return NO_INIT;
1437 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001438 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001439 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1440 inProfile->supportsDevice(sourceDevice)) {
1441 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001442 }
1443 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001444 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001445 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001446 outProfile->supportsDevice(sinkDevice)) {
1447 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001448 }
1449 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001450 return NO_ERROR;
1451}
1452
1453status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1454 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1455 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1456{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001457 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001458 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1459 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1460 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001461 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001462 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1463 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001464 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001465 }
1466 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1467 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1468 sinkConfig->format = bestSinkConfig.format;
1469 // For encoded streams force direct flag to prevent downstream mixing.
1470 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1471 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001472 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1473 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001475 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1476 // raw and IEC61937 framed streams.
1477 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1478 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1479 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001480 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1481 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1482 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1483 sourceConfig->format = bestSinkConfig.format;
1484 // Copy input stream directly without any processing (e.g. resampling).
1485 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1486 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1487 if (hwAvSync) {
1488 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1489 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1490 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1491 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1492 }
1493 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1494 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1495 sinkConfig->config_mask |= config_mask;
1496 sourceConfig->config_mask |= config_mask;
1497 return NO_ERROR;
1498}
1499
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001500PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1501 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001502{
1503 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001504 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1505 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1506 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1507 if (deviceModule == nullptr) {
1508 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1509 return patchBuilder;
1510 }
1511 const InputProfileCollection inputProfiles = msdIsSource ?
1512 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1513 const OutputProfileCollection outputProfiles = msdIsSource ?
1514 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1515
1516 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1517 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1518 device : getMsdAudioOutDevices().itemAt(0);
1519 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1520
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001521 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1522 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001523 AudioProfileVector sourceProfiles;
1524 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001525 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1526 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001527 for (auto hwAvSync : { true, false }) {
1528 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1529 sourceProfiles, sinkProfiles) != NO_ERROR) {
1530 continue;
1531 }
1532 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1533 &sinkConfig) == NO_ERROR) {
1534 // Found a matching config. Re-create PatchBuilder with this config.
1535 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1536 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001538 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001539 " supporting PCM format conversion.", __func__);
1540 return patchBuilder;
1541}
1542
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001543status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001544 DeviceVector devices;
1545 if (outputDevices != nullptr && outputDevices->size() > 0) {
1546 devices.add(*outputDevices);
1547 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001548 // Use media strategy for unspecified output device. This should only
1549 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1550 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001551 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001552 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001553 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001554 }
Michael Chan6fb34492020-12-08 15:44:49 +11001555 std::vector<PatchBuilder> patchesToCreate;
1556 for (auto i = 0u; i < devices.size(); ++i) {
1557 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001558 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001559 }
1560 // Retain only the MSD patches associated with outputDevices request.
1561 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001562 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001563 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1564 auto retainedPatch = false;
1565 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1566 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1567 patchesToRemove.removeItemsAt(i);
1568 retainedPatch = true;
1569 break;
1570 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001571 }
Michael Chan6fb34492020-12-08 15:44:49 +11001572 if (retainedPatch) {
1573 it = patchesToCreate.erase(it);
1574 continue;
1575 }
1576 ++it;
1577 }
1578 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1579 return NO_ERROR;
1580 }
1581 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1582 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001583 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 }
Michael Chan6fb34492020-12-08 15:44:49 +11001585 status_t status = NO_ERROR;
1586 for (const auto &p : patchesToCreate) {
1587 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1588 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1589 char message[256];
1590 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1591 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1592 currStatus == NO_ERROR ? "Success" : "Error",
1593 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1594 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1595 if (currStatus == NO_ERROR) {
1596 ALOGD("%s", message);
1597 } else {
1598 ALOGE("%s", message);
1599 if (status == NO_ERROR) {
1600 status = currStatus;
1601 }
1602 }
1603 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001604 return status;
1605}
1606
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001607void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1608 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001609 for (size_t i = 0; i < msdPatches.size(); i++) {
1610 const auto& patch = msdPatches[i];
1611 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1612 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1613 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1614 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1615 releaseAudioPatch(patch->getHandle(), mUidCached);
1616 break;
1617 }
1618 }
1619 }
1620}
1621
Eric Laurente0720872014-03-11 09:30:41 -07001622audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001623 audio_output_flags_t flags,
1624 audio_format_t format,
1625 audio_channel_mask_t channelMask,
1626 uint32_t samplingRate,
1627 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001628{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001629 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1630 "%s called with format %#x", __func__, format);
1631
jiabinebb6af42020-06-09 17:31:17 -07001632 // Return the output that haptic-generating attached to when 1) session id is specified,
1633 // 2) haptic-generating effect exists for given session id and 3) the output that
1634 // haptic-generating effect attached to is in given outputs.
1635 if (sessionId != AUDIO_SESSION_NONE) {
1636 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1637 sessionId, FX_IID_HAPTICGENERATOR);
1638 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1639 return hapticGeneratingOutput;
1640 }
1641 }
1642
Eric Laurent16c66dd2019-05-01 17:54:10 -07001643 // Flags disqualifying an output: the match must happen before calling selectOutput()
1644 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1645 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1646
1647 // Flags expressing a functional request: must be honored in priority over
1648 // other criteria
1649 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1650 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1651 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1652 // Flags expressing a performance request: have lower priority than serving
1653 // requested sampling rate or channel mask
1654 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1655 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1656 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1657
1658 const audio_output_flags_t functionalFlags =
1659 (audio_output_flags_t)(flags & kFunctionalFlags);
1660 const audio_output_flags_t performanceFlags =
1661 (audio_output_flags_t)(flags & kPerformanceFlags);
1662
1663 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1664
Eric Laurente552edb2014-03-10 17:42:56 -07001665 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001666 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001667 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001668 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001669 // 2: the output with the highest number of requested functional flags
1670 // 3: the output supporting the exact channel mask
1671 // 4: the output with a higher channel count than requested
1672 // 5: the output with a higher sampling rate than requested
1673 // 6: the output with the highest number of requested performance flags
1674 // 7: the output with the bit depth the closest to the requested one
1675 // 8: the primary output
1676 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001677
Eric Laurent16c66dd2019-05-01 17:54:10 -07001678 // matching criteria values in priority order for best matching output so far
1679 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1682 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1683 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001684
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001685 for (audio_io_handle_t output : outputs) {
1686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001687 // matching criteria values in priority order for current output
1688 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001689
Eric Laurent16c66dd2019-05-01 17:54:10 -07001690 if (outputDesc->isDuplicated()) {
1691 continue;
1692 }
1693 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1694 continue;
1695 }
Eric Laurent8838a382014-09-08 16:44:28 -07001696
Eric Laurent16c66dd2019-05-01 17:54:10 -07001697 // If haptic channel is specified, use the haptic output if present.
1698 // When using haptic output, same audio format and sample rate are required.
1699 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001700 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001701 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1702 continue;
1703 }
1704 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001705 && format == outputDesc->getFormat()
1706 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001707 currentMatchCriteria[0] = outputHapticChannelCount;
1708 }
1709
1710 // functional flags match
1711 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1712
1713 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001714 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1715 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1717 channelCount <= outputChannelCount) {
1718 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001719 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1720 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001721 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001722 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001723 currentMatchCriteria[3] = outputChannelCount;
1724 }
1725
1726 // sampling rate match
1727 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001728 samplingRate <= outputDesc->getSamplingRate()) {
1729 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001730 }
1731
1732 // performance flags match
1733 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1734
1735 // format match
1736 if (format != AUDIO_FORMAT_INVALID) {
1737 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001738 PolicyAudioPort::kFormatDistanceMax -
1739 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001740 }
1741
1742 // primary output match
1743 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1744
1745 // compare match criteria by priority then value
1746 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1747 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1748 bestMatchCriteria = currentMatchCriteria;
1749 bestOutput = output;
1750
1751 std::stringstream result;
1752 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1753 std::ostream_iterator<int>(result, " "));
1754 ALOGV("%s new bestOutput %d criteria %s",
1755 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001756 }
1757 }
1758
Eric Laurent16c66dd2019-05-01 17:54:10 -07001759 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001760}
1761
Eric Laurent8fc147b2018-07-22 19:13:55 -07001762status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001763{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001764 ALOGV("%s portId %d", __FUNCTION__, portId);
1765
1766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1767 if (outputDesc == 0) {
1768 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001769 return BAD_VALUE;
1770 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001771 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001772
Eric Laurent8fc147b2018-07-22 19:13:55 -07001773 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001774 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001775
Eric Laurent733ce942017-12-07 12:18:25 -08001776 status_t status = outputDesc->start();
1777 if (status != NO_ERROR) {
1778 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001779 }
1780
Eric Laurent97ac8712018-07-27 18:59:02 -07001781 uint32_t delayMs;
1782 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001783
1784 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001785 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001786 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001787 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001788 if (delayMs != 0) {
1789 usleep(delayMs * 1000);
1790 }
1791
1792 return status;
1793}
1794
Eric Laurent97ac8712018-07-27 18:59:02 -07001795status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1796 const sp<TrackClientDescriptor>& client,
1797 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001798{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001799 // cannot start playback of STREAM_TTS if any other output is being used
1800 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001801
1802 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001803 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001804 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001805 auto clientStrategy = client->strategy();
1806 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001807 if (stream == AUDIO_STREAM_TTS) {
1808 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001809 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001810 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001811 return INVALID_OPERATION;
1812 } else {
1813 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1814 }
1815 } else {
1816 // some playback other than beacon starts
1817 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1818 }
1819
Eric Laurent77305a62016-07-25 16:39:22 -07001820 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001821 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001822 bool force = !outputDesc->isActive() &&
1823 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001824
François Gaffie11d30102018-11-02 16:09:09 +01001825 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001826 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001827 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001828 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001829 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001830 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001831 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001832 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001833 } else {
1834 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001835 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001836 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1837 AUDIO_FORMAT_DEFAULT);
1838 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1839 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001840 }
1841
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001842 // requiresMuteCheck is false when we can bypass mute strategy.
1843 // It covers a common case when there is no materially active audio
1844 // and muting would result in unnecessary delay and dropped audio.
1845 const uint32_t outputLatencyMs = outputDesc->latency();
1846 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1847
Eric Laurente552edb2014-03-10 17:42:56 -07001848 // increment usage count for this stream on the requested output:
1849 // NOTE that the usage count is the same for duplicated output and hardware output which is
1850 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001851 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001852
1853 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001854 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1855 client->isPreferredDeviceForExclusiveUse()) {
1856 // Preferred device may be exclusive, use only if no other active clients on this output
1857 devices = DeviceVector(
1858 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1859 } else {
1860 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1861 }
François Gaffie11d30102018-11-02 16:09:09 +01001862 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001863 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001864 }
1865 }
Eric Laurente552edb2014-03-10 17:42:56 -07001866
François Gaffiec005e562018-11-06 15:04:49 +01001867 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001868 selectOutputForMusicEffects();
1869 }
1870
François Gaffie1c878552018-11-22 16:53:21 +01001871 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001872 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001873 if (devices.isEmpty()) {
1874 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001875 }
François Gaffiec005e562018-11-06 15:04:49 +01001876 bool shouldWait =
1877 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1878 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1879 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001880 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001881 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001882 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001883 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001884 // An output has a shared device if
1885 // - managed by the same hw module
1886 // - supports the currently selected device
1887 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001888 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001889
Eric Laurent77305a62016-07-25 16:39:22 -07001890 // force a device change if any other output is:
1891 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001892 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001893 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001894 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001895 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001896 // change the device currently selected by the other output.
1897 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001898 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001899 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001900 force = true;
1901 }
1902 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001903 // a notification so that audio focus effect can propagate, or that a mute/unmute
1904 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001905 const uint32_t latencyMs = desc->latency();
1906 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1907
1908 if (shouldWait && isActive && (waitMs < latencyMs)) {
1909 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001910 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001911
1912 // Require mute check if another output is on a shared device
1913 // and currently active to have proper drain and avoid pops.
1914 // Note restoring AudioTracks onto this output needs to invoke
1915 // a volume ramp if there is no mute.
1916 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001917 }
1918 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001919
1920 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001921 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001922
Eric Laurente552edb2014-03-10 17:42:56 -07001923 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001924 auto &curves = getVolumeCurves(client->attributes());
1925 checkAndSetVolume(curves, client->volumeSource(),
1926 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001927 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001928 outputDesc->devices().types(), 0 /*delay*/,
1929 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001930
1931 // update the outputs if starting an output with a stream that can affect notification
1932 // routing
1933 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001934
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001935 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001936 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001937 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1938 }
Eric Laurentdc462862016-07-19 12:29:53 -07001939
1940 if (waitMs > muteWaitMs) {
1941 *delayMs = waitMs - muteWaitMs;
1942 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001943
1944 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1945 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1946 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1947 // change occurs after the MixerThread starts and causes a stream volume
1948 // glitch.
1949 //
1950 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001951 }
Eric Laurentdc462862016-07-19 12:29:53 -07001952
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001953 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001954 mEngine->getForceUse(
1955 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001956 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001957 }
1958
Eric Laurent97ac8712018-07-27 18:59:02 -07001959 // Automatically enable the remote submix input when output is started on a re routing mix
1960 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001961 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1962 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001963 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1964 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1965 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001966 "remote-submix",
1967 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001968 }
1969
Eric Laurente552edb2014-03-10 17:42:56 -07001970 return NO_ERROR;
1971}
1972
Eric Laurent8fc147b2018-07-22 19:13:55 -07001973status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001974{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001975 ALOGV("%s portId %d", __FUNCTION__, portId);
1976
1977 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1978 if (outputDesc == 0) {
1979 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001980 return BAD_VALUE;
1981 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001982 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001983
Eric Laurent97ac8712018-07-27 18:59:02 -07001984 ALOGV("stopOutput() output %d, stream %d, session %d",
1985 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001986
Eric Laurent97ac8712018-07-27 18:59:02 -07001987 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001988
Eric Laurent733ce942017-12-07 12:18:25 -08001989 if (status == NO_ERROR ) {
1990 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001991 }
1992 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001993}
1994
Eric Laurent97ac8712018-07-27 18:59:02 -07001995status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1996 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07001997{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001998 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07001999 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002000 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002001
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002002 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2003
François Gaffie1c878552018-11-22 16:53:21 +01002004 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2005 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002006 // Automatically disable the remote submix input when output is stopped on a
2007 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002008 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002009 if (isSingleDeviceType(
2010 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002011 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002012 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002013 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2014 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002015 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002016 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002017 }
2018 }
2019 bool forceDeviceUpdate = false;
2020 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002021 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002022 forceDeviceUpdate = true;
2023 }
2024
Eric Laurente552edb2014-03-10 17:42:56 -07002025 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002026 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002027
Eric Laurente552edb2014-03-10 17:42:56 -07002028 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002029 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002030 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002031 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002032 // delay the device switch by twice the latency because stopOutput() is executed when
2033 // the track stop() command is received and at that time the audio track buffer can
2034 // still contain data that needs to be drained. The latency only covers the audio HAL
2035 // and kernel buffers. Also the latency does not always include additional delay in the
2036 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002037 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002038
2039 // force restoring the device selection on other active outputs if it differs from the
2040 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002041 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002042 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002043 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002044 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002045 desc->isActive() &&
2046 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002047 (newDevices != desc->devices())) {
2048 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2049 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002050
François Gaffie11d30102018-11-02 16:09:09 +01002051 setOutputDevices(desc, newDevices2, force, delayMs);
2052
Eric Laurent57de36c2016-09-28 16:59:11 -07002053 // re-apply device specific volume if not done by setOutputDevice()
2054 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002055 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002056 }
Eric Laurente552edb2014-03-10 17:42:56 -07002057 }
2058 }
2059 // update the outputs if stopping one with a stream that can affect notification routing
2060 handleNotificationRoutingForStream(stream);
2061 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002062
2063 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2064 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002065 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002066 }
2067
François Gaffiec005e562018-11-06 15:04:49 +01002068 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002069 selectOutputForMusicEffects();
2070 }
Eric Laurente552edb2014-03-10 17:42:56 -07002071 return NO_ERROR;
2072 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002073 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002074 return INVALID_OPERATION;
2075 }
2076}
2077
jiabinbce0c1d2020-10-05 11:20:18 -07002078bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002079{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002080 ALOGV("%s portId %d", __FUNCTION__, portId);
2081
2082 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2083 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002084 // If an output descriptor is closed due to a device routing change,
2085 // then there are race conditions with releaseOutput from tracks
2086 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2087 // destroyed shortly thereafter.
2088 //
2089 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002090 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002091 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002092 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002093
2094 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002095
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302096 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2097 if (outputDesc->isClientActive(client)) {
2098 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2099 stopOutput(portId);
2100 }
2101
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2103 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002104 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002105 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002106 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002107 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002108 if (--outputDesc->mDirectOpenCount == 0) {
2109 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002110 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002111 }
2112 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302113
Andy Hung39efb7a2018-09-26 15:39:28 -07002114 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002115 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2116 // The output is pending reopened to query dynamic profiles and
2117 // there is no active clients
2118 closeOutput(outputDesc->mIoHandle);
2119 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2120 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2121 if (newOutputDesc == nullptr) {
2122 ALOGE("%s failed to open output", __func__);
2123 }
2124 return true;
2125 }
2126 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002127}
2128
Eric Laurentcaf7f482014-11-25 17:50:47 -08002129status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2130 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002131 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002132 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002133 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002134 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002135 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002136 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002137 input_type_t *inputType,
2138 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002139{
François Gaffiec005e562018-11-06 15:04:49 +01002140 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2141 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2142 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002143
Eric Laurentad2e7b92017-09-14 20:06:42 -07002144 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002145 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002146 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002147 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002148 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002149 sp<AudioInputDescriptor> inputDesc;
2150 sp<RecordClientDescriptor> clientDesc;
2151 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002152 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002153 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002154
2155 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2156 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2157 return INVALID_OPERATION;
2158 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002159
Francois Gaffie716e1432019-01-14 16:58:59 +01002160 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2161 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002162 }
2163
Paul McLean466dc8e2015-04-17 13:15:36 -06002164 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002165 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002166 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002167
Eric Laurentad2e7b92017-09-14 20:06:42 -07002168 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2169 // possible
2170 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2171 *input != AUDIO_IO_HANDLE_NONE) {
2172 ssize_t index = mInputs.indexOfKey(*input);
2173 if (index < 0) {
2174 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2175 status = BAD_VALUE;
2176 goto error;
2177 }
2178 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002179 RecordClientVector clients = inputDesc->getClientsForSession(session);
2180 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002181 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2182 status = BAD_VALUE;
2183 goto error;
2184 }
2185 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2186 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002187 // corresponds to a new client and is only permitted from the same UID.
2188 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002189 if (clients.size() > 1) {
2190 for (const auto& client : clients) {
2191 // The client map is ordered by key values (portId) and portIds are allocated
2192 // incrementaly. So the first client in this list is the one opened by audio flinger
2193 // when the mmap stream is created and should be ignored as it does not correspond
2194 // to an actual client
2195 if (client == *clients.cbegin()) {
2196 continue;
2197 }
2198 if (uid != client->uid() && !client->isSilenced()) {
2199 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2200 uid, client->portId(), client->uid());
2201 status = INVALID_OPERATION;
2202 goto error;
2203 }
Eric Laurent331679c2018-04-16 17:03:16 -07002204 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002205 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002206 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002207 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002208
Eric Laurentfecbceb2021-02-09 14:46:43 +01002209 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002210 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002211 }
2212
2213 *input = AUDIO_IO_HANDLE_NONE;
2214 *inputType = API_INPUT_INVALID;
2215
Francois Gaffie716e1432019-01-14 16:58:59 +01002216 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002217
Francois Gaffie716e1432019-01-14 16:58:59 +01002218 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2219 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2220 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002221 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002222 ALOGW("%s could not find input mix for attr %s",
2223 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002224 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002225 }
jiabinc1de2df2019-05-07 14:26:40 -07002226 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2227 String8(attr->tags + strlen("addr=")),
2228 AUDIO_FORMAT_DEFAULT);
2229 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002230 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002231 __func__, attributes.source, attributes.tags);
2232 status = BAD_VALUE;
2233 goto error;
2234 }
2235
Kevin Rocard25f9b052019-02-27 15:08:54 -08002236 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2237 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2238 } else {
2239 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2240 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002241 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002242 if (explicitRoutingDevice != nullptr) {
2243 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002244 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002245 // Prevent from storing invalid requested device id in clients
2246 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002247 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002248 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2249 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002250 }
François Gaffie11d30102018-11-02 16:09:09 +01002251 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002252 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002253 status = BAD_VALUE;
2254 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002255 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002256 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2257 *inputType = API_INPUT_MIX_CAPTURE;
2258 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002259 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2260 // there is an external policy, but this input is attached to a mix of recorders,
2261 // meaning it receives audio injected into the framework, so the recorder doesn't
2262 // know about it and is therefore considered "legacy"
2263 *inputType = API_INPUT_LEGACY;
2264 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002265 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002266 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002267 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002268 } else {
2269 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002270 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002271
Eric Laurent599c7582015-12-07 18:05:55 -08002272 }
2273
François Gaffiec005e562018-11-06 15:04:49 +01002274 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002275 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002276 status = INVALID_OPERATION;
2277 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002278 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002279
Eric Laurent8f42ea12018-08-08 09:08:25 -07002280exit:
2281
François Gaffiec005e562018-11-06 15:04:49 +01002282 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2283 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002284
Francois Gaffie716e1432019-01-14 16:58:59 +01002285 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002286 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002287 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002288
Mikhail Naganov2996f672019-04-18 12:29:59 -07002289 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002290 requestedDeviceId, attributes.source, flags,
2291 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002292 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002293 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294
2295 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2296 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002297
Eric Laurent599c7582015-12-07 18:05:55 -08002298 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002299
2300error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002301 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002302}
2303
2304
François Gaffie11d30102018-11-02 16:09:09 +01002305audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002306 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002307 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002308 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002309 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002310 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002311{
2312 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002313 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002314 bool isSoundTrigger = false;
2315
François Gaffiec005e562018-11-06 15:04:49 +01002316 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002317 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2318 if (index >= 0) {
2319 input = mSoundTriggerSessions.valueFor(session);
2320 isSoundTrigger = true;
2321 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2322 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2323 } else {
2324 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002325 }
François Gaffiec005e562018-11-06 15:04:49 +01002326 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002327 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002328 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002329 }
2330
Andy Hungf129b032015-04-07 13:45:50 -07002331 // find a compatible input profile (not necessarily identical in parameters)
2332 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002333 // sampling rate and flags may be updated by getInputProfile
2334 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2335 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002336 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002337 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002338 audio_input_flags_t profileFlags = flags;
2339 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002340 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002341 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002342 profileFlags);
2343 if (profile != 0) {
2344 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002345 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2346 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002347 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2348 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2349 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002350 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002351 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002352 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002353 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002354 }
Eric Laurente552edb2014-03-10 17:42:56 -07002355 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002356 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002357 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002358 if (samplingRate == 0) {
2359 samplingRate = profileSamplingRate;
2360 }
Eric Laurente552edb2014-03-10 17:42:56 -07002361
Eric Laurent322b4d22015-04-03 15:57:54 -07002362 if (profile->getModuleHandle() == 0) {
2363 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002364 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002365 }
2366
Eric Laurentec376dc2021-04-08 20:41:22 +02002367 // Reuse an already opened input if a client with the same session ID already exists
2368 // on that input
2369 for (size_t i = 0; i < mInputs.size(); i++) {
2370 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2371 if (desc->mProfile != profile) {
2372 continue;
2373 }
2374 RecordClientVector clients = desc->clientsList();
2375 for (const auto &client : clients) {
2376 if (session == client->session()) {
2377 return desc->mIoHandle;
2378 }
2379 }
2380 }
2381
Eric Laurent3974e3b2017-12-07 17:58:43 -08002382 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002383 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002384 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002385 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002386 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002387 continue;
2388 }
2389 // if sound trigger, reuse input if used by other sound trigger on same session
2390 // else
2391 // reuse input if active client app is not in IDLE state
2392 //
2393 RecordClientVector clients = desc->clientsList();
2394 bool doClose = false;
2395 for (const auto& client : clients) {
2396 if (isSoundTrigger != client->isSoundTrigger()) {
2397 continue;
2398 }
2399 if (client->isSoundTrigger()) {
2400 if (session == client->session()) {
2401 return desc->mIoHandle;
2402 }
2403 continue;
2404 }
2405 if (client->active() && client->appState() != APP_STATE_IDLE) {
2406 return desc->mIoHandle;
2407 }
2408 doClose = true;
2409 }
2410 if (doClose) {
2411 closeInput(desc->mIoHandle);
2412 } else {
2413 i++;
2414 }
2415 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002416 }
2417
Eric Laurentfe231122017-11-17 17:48:06 -08002418 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002419
Eric Laurentfe231122017-11-17 17:48:06 -08002420 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2421 lConfig.sample_rate = profileSamplingRate;
2422 lConfig.channel_mask = profileChannelMask;
2423 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002424
François Gaffie11d30102018-11-02 16:09:09 +01002425 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002426
2427 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002428 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002429 (profileSamplingRate != lConfig.sample_rate) ||
2430 !audio_formats_match(profileFormat, lConfig.format) ||
2431 (profileChannelMask != lConfig.channel_mask)) {
2432 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002433 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002434 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002435 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002436 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002437 }
Eric Laurent599c7582015-12-07 18:05:55 -08002438 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002439 }
2440
Eric Laurentc722f302014-12-10 11:21:49 -08002441 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002442
Eric Laurent599c7582015-12-07 18:05:55 -08002443 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002444 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002445
Eric Laurent599c7582015-12-07 18:05:55 -08002446 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002447}
2448
Eric Laurent4eb58f12018-12-07 16:41:02 -08002449status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002450{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002451 ALOGV("%s portId %d", __FUNCTION__, portId);
2452
2453 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2454 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002456 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002458 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002459 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002460 if (client->active()) {
2461 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2462 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002463 }
2464
Eric Laurent8f42ea12018-08-08 09:08:25 -07002465 audio_session_t session = client->session();
2466
Eric Laurent4eb58f12018-12-07 16:41:02 -08002467 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002468
Eric Laurent4eb58f12018-12-07 16:41:02 -08002469 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002470
Eric Laurent4eb58f12018-12-07 16:41:02 -08002471 status_t status = inputDesc->start();
2472 if (status != NO_ERROR) {
2473 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002474 }
Eric Laurente552edb2014-03-10 17:42:56 -07002475
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002476 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002477 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002478 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002479
Eric Laurent8f42ea12018-08-08 09:08:25 -07002480 // indicate active capture to sound trigger service if starting capture from a mic on
2481 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002482 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002483 if (device != nullptr) {
2484 status = setInputDevice(input, device, true /* force */);
2485 } else {
2486 ALOGW("%s no new input device can be found for descriptor %d",
2487 __FUNCTION__, inputDesc->getId());
2488 status = BAD_VALUE;
2489 }
Eric Laurente552edb2014-03-10 17:42:56 -07002490
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002491 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002492 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002493 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002494 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002495 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2496 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002497 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002498 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002499
François Gaffie11d30102018-11-02 16:09:09 +01002500 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2501 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002502 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002503 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002504 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002505
Eric Laurent8f42ea12018-08-08 09:08:25 -07002506 // automatically enable the remote submix output when input is started if not
2507 // used by a policy mix of type MIX_TYPE_RECORDERS
2508 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002509 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002510 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002511 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002512 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002513 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2514 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002515 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002516 if (address != "") {
2517 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002519 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002520 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002521 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002522 } else if (status != NO_ERROR) {
2523 // Restore client activity state.
2524 inputDesc->setClientActive(client, false);
2525 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002526 }
2527
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002528 ALOGV("%s input %d source = %d status = %d exit",
2529 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002530
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002531 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002532}
2533
Eric Laurent8fc147b2018-07-22 19:13:55 -07002534status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002535{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002536 ALOGV("%s portId %d", __FUNCTION__, portId);
2537
2538 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2539 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002540 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002541 return BAD_VALUE;
2542 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002543 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002544 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002545 if (!client->active()) {
2546 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002547 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002548 }
Carter Hsue6139d52021-07-08 10:30:20 +08002549 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002550 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002551
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552 inputDesc->stop();
2553 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002554 auto current_source = inputDesc->source();
2555 setInputDevice(input, getNewInputDevice(inputDesc),
2556 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002557 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002558 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002559 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002560 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002561 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2562 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002564 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002565
2566 // automatically disable the remote submix output when input is stopped if not
2567 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002568 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002569 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002570 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002572 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2573 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002574 }
2575 if (address != "") {
2576 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2577 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002578 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002579 }
2580 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002581 resetInputDevice(input);
2582
2583 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2584 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002585 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2586 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002587 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002588 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002589 }
2590 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002591 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002592 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002593}
2594
Eric Laurent8fc147b2018-07-22 19:13:55 -07002595void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002596{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002597 ALOGV("%s portId %d", __FUNCTION__, portId);
2598
2599 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2600 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002602 return;
2603 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002604 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002605 audio_io_handle_t input = inputDesc->mIoHandle;
2606
Eric Laurent8f42ea12018-08-08 09:08:25 -07002607 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002608
Andy Hung39efb7a2018-09-26 15:39:28 -07002609 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002610
Andy Hung39efb7a2018-09-26 15:39:28 -07002611 if (inputDesc->getClientCount() > 0) {
2612 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002613 return;
2614 }
2615
Eric Laurent05b90f82014-08-27 15:32:29 -07002616 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002617 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002619}
2620
Eric Laurent8f42ea12018-08-08 09:08:25 -07002621void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002622{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002623 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002624
2625 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002626 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002627 }
2628}
2629
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2631{
2632 stopInput(portId);
2633 releaseInput(portId);
2634}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002635
Eric Laurent0dd51852019-04-19 18:18:58 -07002636void AudioPolicyManager::checkCloseInputs() {
2637 // After connecting or disconnecting an input device, close input if:
2638 // - it has no client (was just opened to check profile) OR
2639 // - none of its supported devices are connected anymore OR
2640 // - one of its clients cannot be routed to one of its supported
2641 // devices anymore. Otherwise update device selection
2642 std::vector<audio_io_handle_t> inputsToClose;
2643 for (size_t i = 0; i < mInputs.size(); i++) {
2644 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2645 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002646 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002647 inputsToClose.push_back(mInputs.keyAt(i));
2648 } else {
2649 bool close = false;
2650 for (const auto& client : input->clientsList()) {
2651 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002652 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002653 if (!input->supportedDevices().contains(device)) {
2654 close = true;
2655 break;
2656 }
2657 }
2658 if (close) {
2659 inputsToClose.push_back(mInputs.keyAt(i));
2660 } else {
2661 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2662 }
2663 }
2664 }
2665
2666 for (const audio_io_handle_t handle : inputsToClose) {
2667 ALOGV("%s closing input %d", __func__, handle);
2668 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002669 }
Eric Laurentd4692962014-05-05 18:13:44 -07002670}
2671
François Gaffie251c7f02018-11-07 10:41:08 +01002672void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
2674 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002675 if (indexMin < 0 || indexMax < 0) {
2676 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2677 return;
2678 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002679 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002680
2681 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002682 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2683 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002684 continue;
2685 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002686 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002687 }
Eric Laurente552edb2014-03-10 17:42:56 -07002688}
2689
Eric Laurente0720872014-03-11 09:30:41 -07002690status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002691 int index,
2692 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002693{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002694 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002695 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2696 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2697 return NO_ERROR;
2698 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002699 ALOGV("%s: stream %s attributes=%s", __func__,
2700 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002701 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002702}
2703
Eric Laurente0720872014-03-11 09:30:41 -07002704status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002705 int *index,
2706 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002707{
François Gaffiec005e562018-11-06 15:04:49 +01002708 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2709 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002710 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002711 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002712 deviceTypes = mEngine->getOutputDevicesForStream(
2713 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002714 }
jiabin9a3361e2019-10-01 09:38:30 -07002715 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002716}
2717
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002718status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002719 int index,
2720 audio_devices_t device)
2721{
2722 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002723 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2724 if (group == VOLUME_GROUP_NONE) {
2725 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002726 return BAD_VALUE;
2727 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002728 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002729 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002730 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002731 VolumeSource vs = toVolumeSource(group);
2732 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2733
2734 status = setVolumeCurveIndex(index, device, curves);
2735 if (status != NO_ERROR) {
2736 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2737 return status;
2738 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002739
jiabin9a3361e2019-10-01 09:38:30 -07002740 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002741 auto curCurvAttrs = curves.getAttributes();
2742 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2743 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002744 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002745 } else if (!curves.getStreamTypes().empty()) {
2746 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002747 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002748 } else {
2749 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2750 return BAD_VALUE;
2751 }
jiabin9a3361e2019-10-01 09:38:30 -07002752 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2753 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002754
François Gaffiecfe17322018-11-07 13:41:29 +01002755 // update volume on all outputs and streams matching the following:
2756 // - The requested stream (or a stream matching for volume control) is active on the output
2757 // - The device (or devices) selected by the engine for this stream includes
2758 // the requested device
2759 // - For non default requested device, currently selected device on the output is either the
2760 // requested device or one of the devices selected by the engine for this stream
2761 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2762 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002763 for (size_t i = 0; i < mOutputs.size(); i++) {
2764 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002765 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002766
jiabin9a3361e2019-10-01 09:38:30 -07002767 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2768 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002769 }
François Gaffieed91f582020-01-31 10:35:37 +01002770 if (!(desc->isActive(vs) || isInCall())) {
2771 continue;
2772 }
2773 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2774 curDevices.find(device) == curDevices.end()) {
2775 continue;
2776 }
2777 bool applyVolume = false;
2778 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2779 curSrcDevices.insert(device);
2780 applyVolume = (curSrcDevices.find(
2781 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2782 } else {
2783 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2784 }
2785 if (!applyVolume) {
2786 continue; // next output
2787 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002788 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2789 // If a higher priority strategy is active, and the output is routed to a device with a
2790 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002791 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002792 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002793 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2794 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2795 false /*preferredDevice*/);
2796 if (activeClients.empty()) {
2797 continue;
2798 }
2799 bool isPreempted = false;
2800 bool isHigherPriority = productStrategy < strategy;
2801 for (const auto &client : activeClients) {
2802 if (isHigherPriority && (client->volumeSource() != vs)) {
2803 ALOGV("%s: Strategy=%d (\nrequester:\n"
2804 " group %d, volumeGroup=%d attributes=%s)\n"
2805 " higher priority source active:\n"
2806 " volumeGroup=%d attributes=%s) \n"
2807 " on output %zu, bailing out", __func__, productStrategy,
2808 group, group, toString(attributes).c_str(),
2809 client->volumeSource(), toString(client->attributes()).c_str(), i);
2810 applyVolume = false;
2811 isPreempted = true;
2812 break;
2813 }
2814 // However, continue for loop to ensure no higher prio clients running on output
2815 if (client->volumeSource() == vs) {
2816 applyVolume = true;
2817 }
2818 }
2819 if (isPreempted || applyVolume) {
2820 break;
2821 }
2822 }
2823 if (!applyVolume) {
2824 continue; // next output
2825 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002826 }
François Gaffieed91f582020-01-31 10:35:37 +01002827 //FIXME: workaround for truncated touch sounds
2828 // delayed volume change for system stream to be removed when the problem is
2829 // handled by system UI
2830 status_t volStatus = checkAndSetVolume(
2831 curves, vs, index, desc, curDevices,
2832 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2833 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2834 if (volStatus != NO_ERROR) {
2835 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002836 }
2837 }
François Gaffiecfe17322018-11-07 13:41:29 +01002838 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2839 return status;
2840}
2841
François Gaffieaaac0fd2018-11-22 17:56:39 +01002842status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002843 audio_devices_t device,
2844 IVolumeCurves &volumeCurves)
2845{
2846 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2847 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002848 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2849 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002850 (index > volumeCurves.getVolumeIndexMax())) {
2851 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2852 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2853 return BAD_VALUE;
2854 }
2855 if (!audio_is_output_device(device)) {
2856 return BAD_VALUE;
2857 }
2858
2859 // Force max volume if stream cannot be muted
2860 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2861
François Gaffieaaac0fd2018-11-22 17:56:39 +01002862 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002863 volumeCurves.addCurrentVolumeIndex(device, index);
2864 return NO_ERROR;
2865}
2866
2867status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2868 int &index,
2869 audio_devices_t device)
2870{
2871 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2872 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002873 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002874 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002875 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2876 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002877 }
jiabin9a3361e2019-10-01 09:38:30 -07002878 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002879}
2880
2881status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2882 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002883 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002884{
jiabin9a3361e2019-10-01 09:38:30 -07002885 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002886 return BAD_VALUE;
2887 }
jiabin9a3361e2019-10-01 09:38:30 -07002888 index = curves.getVolumeIndex(deviceTypes);
2889 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002890 return NO_ERROR;
2891}
2892
2893status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2894 int &index)
2895{
2896 index = getVolumeCurves(attr).getVolumeIndexMin();
2897 return NO_ERROR;
2898}
2899
2900status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2901 int &index)
2902{
2903 index = getVolumeCurves(attr).getVolumeIndexMax();
2904 return NO_ERROR;
2905}
2906
Eric Laurent36829f92017-04-07 19:04:42 -07002907audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002908{
2909 // select one output among several suitable for global effects.
2910 // The priority is as follows:
2911 // 1: An offloaded output. If the effect ends up not being offloadable,
2912 // AudioFlinger will invalidate the track and the offloaded output
2913 // will be closed causing the effect to be moved to a PCM output.
2914 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002915 // 3: The primary output
2916 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002917
François Gaffiec005e562018-11-06 15:04:49 +01002918 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2919 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002920 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002921
Eric Laurent36829f92017-04-07 19:04:42 -07002922 if (outputs.size() == 0) {
2923 return AUDIO_IO_HANDLE_NONE;
2924 }
Eric Laurente552edb2014-03-10 17:42:56 -07002925
Eric Laurent36829f92017-04-07 19:04:42 -07002926 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2927 bool activeOnly = true;
2928
2929 while (output == AUDIO_IO_HANDLE_NONE) {
2930 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2931 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2932 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2933
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002934 for (audio_io_handle_t output : outputs) {
2935 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002936 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002937 continue;
2938 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002939 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2940 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002941 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002942 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002943 }
2944 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002945 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002946 }
2947 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002948 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002949 }
2950 }
2951 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2952 output = outputOffloaded;
2953 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2954 output = outputDeepBuffer;
2955 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2956 output = outputPrimary;
2957 } else {
2958 output = outputs[0];
2959 }
2960 activeOnly = false;
2961 }
2962
2963 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002964 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002965 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2966 mMusicEffectOutput = output;
2967 }
2968
2969 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002970 return output;
2971}
2972
Eric Laurent36829f92017-04-07 19:04:42 -07002973audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2974{
2975 return selectOutputForMusicEffects();
2976}
2977
Eric Laurente0720872014-03-11 09:30:41 -07002978status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002979 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002980 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002981 int session,
2982 int id)
2983{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002984 if (session != AUDIO_SESSION_DEVICE) {
2985 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002986 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002987 index = mInputs.indexOfKey(io);
2988 if (index < 0) {
2989 ALOGW("registerEffect() unknown io %d", io);
2990 return INVALID_OPERATION;
2991 }
Eric Laurente552edb2014-03-10 17:42:56 -07002992 }
2993 }
François Gaffiec005e562018-11-06 15:04:49 +01002994 return mEffects.registerEffect(desc, io, session, id,
2995 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2996 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07002997}
2998
Eric Laurentc241b0d2018-11-28 09:08:49 -08002999status_t AudioPolicyManager::unregisterEffect(int id)
3000{
3001 if (mEffects.getEffect(id) == nullptr) {
3002 return INVALID_OPERATION;
3003 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003004 if (mEffects.isEffectEnabled(id)) {
3005 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3006 setEffectEnabled(id, false);
3007 }
3008 return mEffects.unregisterEffect(id);
3009}
3010
3011status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3012{
3013 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3014 if (effect == nullptr) {
3015 return INVALID_OPERATION;
3016 }
3017
3018 status_t status = mEffects.setEffectEnabled(id, enabled);
3019 if (status == NO_ERROR) {
3020 mInputs.trackEffectEnabled(effect, enabled);
3021 }
3022 return status;
3023}
3024
Eric Laurent6c796322019-04-09 14:13:17 -07003025
3026status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3027{
3028 mEffects.moveEffects(ids, io);
3029 return NO_ERROR;
3030}
3031
Eric Laurentc75307b2015-03-17 15:29:32 -07003032bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3033{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003035}
3036
3037bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3038{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003039 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003040}
3041
Eric Laurente0720872014-03-11 09:30:41 -07003042bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003043{
3044 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003045 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003046 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003047 return true;
3048 }
3049 }
3050 return false;
3051}
3052
Eric Laurent275e8e92014-11-30 15:14:47 -08003053// Register a list of custom mixes with their attributes and format.
3054// When a mix is registered, corresponding input and output profiles are
3055// added to the remote submix hw module. The profile contains only the
3056// parameters (sampling rate, format...) specified by the mix.
3057// The corresponding input remote submix device is also connected.
3058//
3059// When a remote submix device is connected, the address is checked to select the
3060// appropriate profile and the corresponding input or output stream is opened.
3061//
3062// When capture starts, getInputForAttr() will:
3063// - 1 look for a mix matching the address passed in attribtutes tags if any
3064// - 2 if none found, getDeviceForInputSource() will:
3065// - 2.1 look for a mix matching the attributes source
3066// - 2.2 if none found, default to device selection by policy rules
3067// At this time, the corresponding output remote submix device is also connected
3068// and active playback use cases can be transferred to this mix if needed when reconnecting
3069// after AudioTracks are invalidated
3070//
3071// When playback starts, getOutputForAttr() will:
3072// - 1 look for a mix matching the address passed in attribtutes tags if any
3073// - 2 if none found, look for a mix matching the attributes usage
3074// - 3 if none found, default to device and output selection by policy rules.
3075
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003076status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003077{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003078 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3079 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003080 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003081 sp<HwModule> rSubmixModule;
3082 // examine each mix's route type
3083 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003084 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003085 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3086 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3087 ALOGE("Unsupported Policy Mix %zu of %zu: "
3088 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3089 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003090 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003091 break;
3092 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003093 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3094 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003095 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003096 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3097 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003098 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003099 rSubmixModule = mHwModules.getModuleFromName(
3100 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3101 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003102 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003103 i);
3104 res = INVALID_OPERATION;
3105 break;
3106 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003107 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003108
Eric Laurent97ac8712018-07-27 18:59:02 -07003109 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003110 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003111 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003112 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003113 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3114 } else {
3115 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3116 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003117 }
François Gaffie036e1e92015-03-19 10:16:24 +01003118
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003119 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003120 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003121 res = INVALID_OPERATION;
3122 break;
3123 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003124 audio_config_t outputConfig = mix.mFormat;
3125 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003126 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3127 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003128 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3129 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003130 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003131 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003132 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003133 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003134
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003135 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003136 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3137 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3138 ALOGE("Failed to set remote submix device available, type %u, address %s",
3139 mix.mDeviceType, address.string());
3140 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003141 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003142 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3143 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003144 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003145 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003146 i, mixes.size(), type, address.string());
3147
3148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3149 mix.mDeviceType, mix.mDeviceAddress,
3150 String8(), AUDIO_FORMAT_DEFAULT);
3151 if (device == nullptr) {
3152 res = INVALID_OPERATION;
3153 break;
3154 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003155
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003156 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003157 // First try to find an already opened output supporting the device
3158 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003159 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003160
Eric Laurentc529cf62020-04-17 18:19:10 -07003161 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003162 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003163 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3164 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003165 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003166 } else {
3167 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003168 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003169 }
3170 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003171 // If no output found, try to find a direct output profile supporting the device
3172 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3173 sp<HwModule> module = mHwModules[i];
3174 for (size_t j = 0;
3175 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3176 j++) {
3177 sp<IOProfile> profile = module->getOutputProfiles()[j];
3178 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3179 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3180 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3181 address.string());
3182 res = INVALID_OPERATION;
3183 } else {
3184 foundOutput = true;
3185 }
3186 }
3187 }
3188 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003189 if (res != NO_ERROR) {
3190 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003191 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003192 res = INVALID_OPERATION;
3193 break;
3194 } else if (!foundOutput) {
3195 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003196 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003197 res = INVALID_OPERATION;
3198 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003199 } else {
3200 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003201 }
Eric Laurentc722f302014-12-10 11:21:49 -08003202 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003203 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003204 if (res != NO_ERROR) {
3205 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003206 } else if (checkOutputs) {
3207 checkForDeviceAndOutputChanges();
3208 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003209 }
3210 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003211}
3212
3213status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3214{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003215 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003216 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003217 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003218 sp<HwModule> rSubmixModule;
3219 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003220 for (const auto& mix : mixes) {
3221 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003222
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003223 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003224 rSubmixModule = mHwModules.getModuleFromName(
3225 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3226 if (rSubmixModule == 0) {
3227 res = INVALID_OPERATION;
3228 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003229 }
3230 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003231
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003232 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003233
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003234 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235 res = INVALID_OPERATION;
3236 continue;
3237 }
3238
Kevin Rocard04ed0462019-05-02 17:53:24 -07003239 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3240 if (getDeviceConnectionState(device, address.string()) ==
3241 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3242 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3243 address.string(), "remote-submix",
3244 AUDIO_FORMAT_DEFAULT);
3245 if (res != OK) {
3246 ALOGE("Error making RemoteSubmix device unavailable for mix "
3247 "with type %d, address %s", device, address.string());
3248 }
3249 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003250 }
jiabin5740f082019-08-19 15:08:30 -07003251 rSubmixModule->removeOutputProfile(address.c_str());
3252 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003253
Kevin Rocard153f92d2018-12-18 18:33:28 -08003254 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003255 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003256 res = INVALID_OPERATION;
3257 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003258 } else {
3259 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003260 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003261 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003262 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003263 if (res == NO_ERROR && checkOutputs) {
3264 checkForDeviceAndOutputChanges();
3265 updateCallAndOutputRouting();
3266 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003267 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003268}
3269
Mikhail Naganov100f0122018-11-29 11:22:16 -08003270void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3271{
3272 size_t i = 0;
3273 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3274 for (const auto& fmt : mManualSurroundFormats) {
3275 if (i++ != 0) dst->append(", ");
3276 std::string sfmt;
3277 FormatConverter::toString(fmt, sfmt);
3278 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3279 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3280 }
3281}
3282
Eric Laurentc529cf62020-04-17 18:19:10 -07003283// Returns true if all devices types match the predicate and are supported by one HW module
3284bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003285 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003286 std::function<bool(audio_devices_t)> predicate,
3287 const char *context) {
3288 for (size_t i = 0; i < devices.size(); i++) {
3289 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003290 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003291 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003292 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003293 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003294 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003295 return false;
3296 }
3297 }
3298 return true;
3299}
3300
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003301status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003302 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003303 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003304 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3305 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003306 }
3307 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003308 if (res != NO_ERROR) {
3309 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3310 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003311 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003312
3313 checkForDeviceAndOutputChanges();
3314 updateCallAndOutputRouting();
3315
3316 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003317}
3318
3319status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3320 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003321 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3322 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003323 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003324 __FUNCTION__, uid);
3325 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003326 }
3327
Eric Laurentc529cf62020-04-17 18:19:10 -07003328 checkForDeviceAndOutputChanges();
3329 updateCallAndOutputRouting();
3330
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003331 return res;
3332}
3333
Eric Laurent2517af32020-11-25 15:31:27 +01003334
jiabin0a488932020-08-07 17:32:40 -07003335status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3336 device_role_t role,
3337 const AudioDeviceTypeAddrVector &devices) {
3338 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3339 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003340
Eric Laurentc529cf62020-04-17 18:19:10 -07003341 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003342 return BAD_VALUE;
3343 }
jiabin0a488932020-08-07 17:32:40 -07003344 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003345 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003346 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3347 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003348 return status;
3349 }
3350
3351 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003352
3353 bool forceVolumeReeval = false;
3354 // FIXME: workaround for truncated touch sounds
3355 // to be removed when the problem is handled by system UI
3356 uint32_t delayMs = 0;
3357 if (strategy == mCommunnicationStrategy) {
3358 forceVolumeReeval = true;
3359 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3360 updateInputRouting();
3361 }
3362 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003363
3364 return NO_ERROR;
3365}
3366
3367void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3368{
3369 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003370 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003371 // Only apply special touch sound delay once
3372 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003373 }
3374 for (size_t i = 0; i < mOutputs.size(); i++) {
3375 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3376 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3377 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3378 // As done in setDeviceConnectionState, we could also fix default device issue by
3379 // preventing the force re-routing in case of default dev that distinguishes on address.
3380 // Let's give back to engine full device choice decision however.
3381 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003382 // Only apply special touch sound delay once
3383 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003384 }
3385 if (forceVolumeReeval && !newDevices.isEmpty()) {
3386 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3387 }
3388 }
3389}
3390
Eric Laurent2517af32020-11-25 15:31:27 +01003391void AudioPolicyManager::updateInputRouting() {
3392 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303393 // Skip for hotword recording as the input device switch
3394 // is handled within sound trigger HAL
3395 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3396 continue;
3397 }
Eric Laurent2517af32020-11-25 15:31:27 +01003398 auto newDevice = getNewInputDevice(activeDesc);
3399 // Force new input selection if the new device can not be reached via current input
3400 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3401 setInputDevice(activeDesc->mIoHandle, newDevice);
3402 } else {
3403 closeInput(activeDesc->mIoHandle);
3404 }
3405 }
3406}
3407
jiabin0a488932020-08-07 17:32:40 -07003408status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3409 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003410{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003411 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003412
jiabin0a488932020-08-07 17:32:40 -07003413 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003414 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003415 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3416 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003417 return status;
3418 }
3419
3420 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003421
3422 bool forceVolumeReeval = false;
3423 // FIXME: workaround for truncated touch sounds
3424 // to be removed when the problem is handled by system UI
3425 uint32_t delayMs = 0;
3426 if (strategy == mCommunnicationStrategy) {
3427 forceVolumeReeval = true;
3428 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3429 updateInputRouting();
3430 }
3431 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003432
3433 return NO_ERROR;
3434}
3435
jiabin0a488932020-08-07 17:32:40 -07003436status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3437 device_role_t role,
3438 AudioDeviceTypeAddrVector &devices) {
3439 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003440}
3441
Jiabin Huang3b98d322020-09-03 17:54:16 +00003442status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3443 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3444 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3445 dumpAudioDeviceTypeAddrVector(devices).c_str());
3446
Mikhail Naganov55773032020-10-01 15:08:13 -07003447 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003448 return BAD_VALUE;
3449 }
3450 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3451 ALOGW_IF(status != NO_ERROR,
3452 "Engine could not set preferred devices %s for audio source %d role %d",
3453 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3454
3455 return status;
3456}
3457
3458status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3459 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3460 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3461 dumpAudioDeviceTypeAddrVector(devices).c_str());
3462
Mikhail Naganov55773032020-10-01 15:08:13 -07003463 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003464 return BAD_VALUE;
3465 }
3466 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3467 ALOGW_IF(status != NO_ERROR,
3468 "Engine could not add preferred devices %s for audio source %d role %d",
3469 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3470
Eric Laurent2517af32020-11-25 15:31:27 +01003471 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003472 return status;
3473}
3474
3475status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3476 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3477{
3478 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3479 dumpAudioDeviceTypeAddrVector(devices).c_str());
3480
Mikhail Naganov55773032020-10-01 15:08:13 -07003481 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003482 return BAD_VALUE;
3483 }
3484
3485 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3486 audioSource, role, devices);
3487 ALOGW_IF(status != NO_ERROR,
3488 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3489
Eric Laurent2517af32020-11-25 15:31:27 +01003490 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003491 return status;
3492}
3493
3494status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3495 device_role_t role) {
3496 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3497
3498 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3499 ALOGW_IF(status != NO_ERROR,
3500 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3501
Eric Laurent2517af32020-11-25 15:31:27 +01003502 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003503 return status;
3504}
3505
3506status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3507 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3508 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3509}
3510
Oscar Azucena90e77632019-11-27 17:12:28 -08003511status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003512 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003513 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003514 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3515 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003516 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003517 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3518 if (status != NO_ERROR) {
3519 ALOGE("%s() could not set device affinity for userId %d",
3520 __FUNCTION__, userId);
3521 return status;
3522 }
3523
3524 // reevaluate outputs for all devices
3525 checkForDeviceAndOutputChanges();
3526 updateCallAndOutputRouting();
3527
3528 return NO_ERROR;
3529}
3530
3531status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003532 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003533 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3534 if (status != NO_ERROR) {
3535 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3536 __FUNCTION__, userId);
3537 return status;
3538 }
3539
3540 // reevaluate outputs for all devices
3541 checkForDeviceAndOutputChanges();
3542 updateCallAndOutputRouting();
3543
3544 return NO_ERROR;
3545}
3546
Andy Hungc29d82b2018-10-05 12:23:17 -07003547void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003548{
Andy Hungc29d82b2018-10-05 12:23:17 -07003549 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3550 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003551 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003552 std::string stateLiteral;
3553 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003554 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003555 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3556 "communications", "media", "record", "dock", "system",
3557 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3558 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3559 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003560 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3561 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3562 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3563 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3564 dst->append(" (MANUAL: ");
3565 dumpManualSurroundFormats(dst);
3566 dst->append(")");
3567 }
3568 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003569 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003570 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3571 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003572 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003573 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003574
Andy Hungc29d82b2018-10-05 12:23:17 -07003575 mAvailableOutputDevices.dump(dst, String8("Available output"));
3576 mAvailableInputDevices.dump(dst, String8("Available input"));
3577 mHwModulesAll.dump(dst);
3578 mOutputs.dump(dst);
3579 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003580 mEffects.dump(dst);
3581 mAudioPatches.dump(dst);
3582 mPolicyMixes.dump(dst);
3583 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003584
Kevin Rocardb99cc752019-03-21 20:52:24 -07003585 dst->appendFormat(" AllowedCapturePolicies:\n");
3586 for (auto& policy : mAllowedCapturePolicies) {
3587 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3588 }
3589
François Gaffiec005e562018-11-06 15:04:49 +01003590 dst->appendFormat("\nPolicy Engine dump:\n");
3591 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003592}
3593
3594status_t AudioPolicyManager::dump(int fd)
3595{
3596 String8 result;
3597 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003598 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003599 return NO_ERROR;
3600}
3601
Kevin Rocardb99cc752019-03-21 20:52:24 -07003602status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3603{
3604 mAllowedCapturePolicies[uid] = capturePolicy;
3605 return NO_ERROR;
3606}
3607
Eric Laurente552edb2014-03-10 17:42:56 -07003608// This function checks for the parameters which can be offloaded.
3609// This can be enhanced depending on the capability of the DSP and policy
3610// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003611audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003612{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003613 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003614 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003615 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003616 offloadInfo.format,
3617 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3618 offloadInfo.has_video);
3619
Andy Hung2ddee192015-12-18 17:34:44 -08003620 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003621 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003622 }
3623
Eric Laurente552edb2014-03-10 17:42:56 -07003624 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003625 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003626 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3627 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003628 }
3629
3630 // Check if stream type is music, then only allow offload as of now.
3631 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3632 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003633 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3634 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003635 }
3636
3637 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003638 const bool allowOffloadWithVideo =
3639 property_get_bool("audio.offload.video", false /* default_value */);
3640 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003641 ALOGV("%s: has_video == true, returning false", __func__);
3642 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003643 }
3644
3645 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003646 const int min_duration_secs = property_get_int32(
3647 "audio.offload.min.duration.secs", -1 /* default_value */);
3648 if (min_duration_secs >= 0) {
3649 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003650 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3651 __func__, min_duration_secs);
3652 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003653 }
3654 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003655 ALOGV("%s: Offload denied by duration < default min(=%u)",
3656 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3657 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003658 }
3659
3660 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3661 // creating an offloaded track and tearing it down immediately after start when audioflinger
3662 // detects there is an active non offloadable effect.
3663 // FIXME: We should check the audio session here but we do not have it in this context.
3664 // This may prevent offloading in rare situations where effects are left active by apps
3665 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003666 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003667 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003668 }
3669
3670 // See if there is a profile to support this.
3671 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003672 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003673 offloadInfo.sample_rate,
3674 offloadInfo.format,
3675 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003676 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3677 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003678 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3679 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3680 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003681 if (profile == nullptr) {
3682 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3683 }
3684 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3685 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3686 }
3687 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003688}
3689
Michael Chana94fbb22018-04-24 14:31:19 +10003690bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3691 const audio_attributes_t& attributes) {
3692 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003693 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003694 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003695 config.sample_rate,
3696 config.format,
3697 config.channel_mask,
3698 output_flags,
3699 true /* directOnly */);
3700 ALOGV("%s() profile %sfound with name: %s, "
3701 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3702 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003703 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003704 config.sample_rate, config.format, config.channel_mask, output_flags);
3705 return (profile != 0);
3706}
3707
Eric Laurent6a94d692014-05-20 11:18:06 -07003708status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3709 audio_port_type_t type,
3710 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003711 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003712 unsigned int *generation)
3713{
jiabin19cdba52020-11-24 11:28:58 -08003714 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3715 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003716 return BAD_VALUE;
3717 }
3718 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003719 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 *num_ports = 0;
3721 }
3722
3723 size_t portsWritten = 0;
3724 size_t portsMax = *num_ports;
3725 *num_ports = 0;
3726 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003727 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3728 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003729 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003730 for (const auto& dev : mAvailableOutputDevices) {
3731 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003732 continue;
3733 }
3734 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003735 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003736 }
3737 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003738 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003739 }
3740 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003741 for (const auto& dev : mAvailableInputDevices) {
3742 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003743 continue;
3744 }
3745 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003746 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003747 }
3748 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003749 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 }
3751 }
3752 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3753 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3754 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3755 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3756 }
3757 *num_ports += mInputs.size();
3758 }
3759 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003760 size_t numOutputs = 0;
3761 for (size_t i = 0; i < mOutputs.size(); i++) {
3762 if (!mOutputs[i]->isDuplicated()) {
3763 numOutputs++;
3764 if (portsWritten < portsMax) {
3765 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3766 }
3767 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003768 }
Eric Laurent84c70242014-06-23 08:46:27 -07003769 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003770 }
3771 }
3772 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003773 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003774 return NO_ERROR;
3775}
3776
jiabin19cdba52020-11-24 11:28:58 -08003777status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003778{
Eric Laurent99fcae42018-05-17 16:59:18 -07003779 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3780 return BAD_VALUE;
3781 }
3782 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3783 if (dev != 0) {
3784 dev->toAudioPort(port);
3785 return NO_ERROR;
3786 }
3787 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3788 if (dev != 0) {
3789 dev->toAudioPort(port);
3790 return NO_ERROR;
3791 }
3792 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3793 if (out != 0) {
3794 out->toAudioPort(port);
3795 return NO_ERROR;
3796 }
3797 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3798 if (in != 0) {
3799 in->toAudioPort(port);
3800 return NO_ERROR;
3801 }
3802 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003803}
3804
François Gaffieafd4cea2019-11-18 15:50:22 +01003805status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3806 audio_patch_handle_t *handle,
3807 uid_t uid, uint32_t delayMs,
3808 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003809{
François Gaffieafd4cea2019-11-18 15:50:22 +01003810 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003811 if (handle == NULL || patch == NULL) {
3812 return BAD_VALUE;
3813 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003814 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003815
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003816 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003817 return BAD_VALUE;
3818 }
3819 // only one source per audio patch supported for now
3820 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003821 return INVALID_OPERATION;
3822 }
Eric Laurent874c42872014-08-08 15:13:39 -07003823
3824 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003825 return INVALID_OPERATION;
3826 }
Eric Laurent874c42872014-08-08 15:13:39 -07003827 for (size_t i = 0; i < patch->num_sinks; i++) {
3828 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3829 return INVALID_OPERATION;
3830 }
3831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003832
3833 sp<AudioPatch> patchDesc;
3834 ssize_t index = mAudioPatches.indexOfKey(*handle);
3835
François Gaffieafd4cea2019-11-18 15:50:22 +01003836 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3837 patch->sources[0].role,
3838 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003839#if LOG_NDEBUG == 0
3840 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003841 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3842 patch->sinks[i].role,
3843 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003844 }
3845#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003846
3847 if (index >= 0) {
3848 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003849 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3850 __func__, mUidCached, patchDesc->getUid(), uid);
3851 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003852 return INVALID_OPERATION;
3853 }
3854 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003855 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003856 }
3857
3858 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003859 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003860 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003861 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003862 return BAD_VALUE;
3863 }
Eric Laurent84c70242014-06-23 08:46:27 -07003864 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3865 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003866 if (patchDesc != 0) {
3867 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003868 ALOGV("%s source id differs for patch current id %d new id %d",
3869 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 return BAD_VALUE;
3871 }
3872 }
Eric Laurent874c42872014-08-08 15:13:39 -07003873 DeviceVector devices;
3874 for (size_t i = 0; i < patch->num_sinks; i++) {
3875 // Only support mix to devices connection
3876 // TODO add support for mix to mix connection
3877 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003878 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003879 return INVALID_OPERATION;
3880 }
3881 sp<DeviceDescriptor> devDesc =
3882 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3883 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003884 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003885 return BAD_VALUE;
3886 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003887
François Gaffie11d30102018-11-02 16:09:09 +01003888 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003889 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003890 NULL, // updatedSamplingRate
3891 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003892 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003893 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003894 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003895 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003896 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003897 return INVALID_OPERATION;
3898 }
3899 devices.add(devDesc);
3900 }
3901 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003902 return INVALID_OPERATION;
3903 }
Eric Laurent874c42872014-08-08 15:13:39 -07003904
Eric Laurent6a94d692014-05-20 11:18:06 -07003905 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003906 ALOGV("%s setting device %s on output %d",
3907 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003908 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003909 index = mAudioPatches.indexOfKey(*handle);
3910 if (index >= 0) {
3911 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003912 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003913 }
3914 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003915 patchDesc->setUid(uid);
3916 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003917 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003918 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003919 return INVALID_OPERATION;
3920 }
3921 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3922 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3923 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003924 // only one sink supported when connecting an input device to a mix
3925 if (patch->num_sinks > 1) {
3926 return INVALID_OPERATION;
3927 }
François Gaffie53615e22015-03-19 09:24:12 +01003928 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003929 if (inputDesc == NULL) {
3930 return BAD_VALUE;
3931 }
3932 if (patchDesc != 0) {
3933 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3934 return BAD_VALUE;
3935 }
3936 }
François Gaffie11d30102018-11-02 16:09:09 +01003937 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003938 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003939 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 return BAD_VALUE;
3941 }
3942
François Gaffie11d30102018-11-02 16:09:09 +01003943 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003944 patch->sinks[0].sample_rate,
3945 NULL, /*updatedSampleRate*/
3946 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003947 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003948 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003949 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003950 // FIXME for the parameter type,
3951 // and the NONE
3952 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003953 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003954 return INVALID_OPERATION;
3955 }
3956 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003957 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003958 device->toString().c_str(), inputDesc->mIoHandle);
3959 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003960 index = mAudioPatches.indexOfKey(*handle);
3961 if (index >= 0) {
3962 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003963 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003964 }
3965 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003966 patchDesc->setUid(uid);
3967 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003968 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003969 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003970 return INVALID_OPERATION;
3971 }
3972 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3973 // device to device connection
3974 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003975 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 return BAD_VALUE;
3977 }
3978 }
François Gaffie11d30102018-11-02 16:09:09 +01003979 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003981 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003982 return BAD_VALUE;
3983 }
Eric Laurent874c42872014-08-08 15:13:39 -07003984
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 //update source and sink with our own data as the data passed in the patch may
3986 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003987 PatchBuilder patchBuilder;
3988 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003989
3990 // if first sink is to MSD, establish single MSD patch
3991 if (getMsdAudioOutDevices().contains(
3992 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3993 ALOGV("%s patching to MSD", __FUNCTION__);
3994 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3995 goto installPatch;
3996 }
3997
François Gaffieafd4cea2019-11-18 15:50:22 +01003998 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
3999 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004000
Eric Laurent874c42872014-08-08 15:13:39 -07004001 for (size_t i = 0; i < patch->num_sinks; i++) {
4002 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004003 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004004 return INVALID_OPERATION;
4005 }
François Gaffie11d30102018-11-02 16:09:09 +01004006 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004007 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004008 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004009 return BAD_VALUE;
4010 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004011 audio_port_config sinkPortConfig = {};
4012 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4013 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004014
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004015 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4016 // volume management purpose (tracking activity)
4017 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4018 // in config XML to reach the sink so that is can be declared as available.
4019 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4020 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4021 if (sourceDesc != nullptr) {
4022 // take care of dynamic routing for SwOutput selection,
4023 audio_attributes_t attributes = sourceDesc->attributes();
4024 audio_stream_type_t stream = sourceDesc->stream();
4025 audio_attributes_t resultAttr;
4026 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4027 config.sample_rate = sourceDesc->config().sample_rate;
4028 config.channel_mask = sourceDesc->config().channel_mask;
4029 config.format = sourceDesc->config().format;
4030 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4031 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4032 bool isRequestedDeviceForExclusiveUse = false;
4033 output_type_t outputType;
4034 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4035 &stream, sourceDesc->uid(), &config, &flags,
4036 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4037 nullptr, &outputType);
4038 if (output == AUDIO_IO_HANDLE_NONE) {
4039 ALOGV("%s no output for device %s",
4040 __FUNCTION__, sinkDevice->toString().c_str());
4041 return INVALID_OPERATION;
4042 }
4043 outputDesc = mOutputs.valueFor(output);
4044 if (outputDesc->isDuplicated()) {
4045 ALOGE("%s output is duplicated", __func__);
4046 return INVALID_OPERATION;
4047 }
4048 sourceDesc->setSwOutput(outputDesc);
4049 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004050 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004051 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004052 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004053 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004054 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4055 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004056 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4057 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004058 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4059 (sourceDesc != nullptr &&
4060 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004061 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004062 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004063 return INVALID_OPERATION;
4064 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004065 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004066 SortedVector<audio_io_handle_t> outputs =
4067 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4068 // if the sink device is reachable via an opened output stream, request to
4069 // go via this output stream by adding a second source to the patch
4070 // description
4071 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004072 if (output != AUDIO_IO_HANDLE_NONE) {
4073 outputDesc = mOutputs.valueFor(output);
4074 if (outputDesc->isDuplicated()) {
4075 ALOGV("%s output for device %s is duplicated",
4076 __FUNCTION__, sinkDevice->toString().c_str());
4077 return INVALID_OPERATION;
4078 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004079 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004080 }
4081 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004082 audio_port_config srcMixPortConfig = {};
4083 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004084 // for volume control, we may need a valid stream
4085 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4086 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4087 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004088 }
Eric Laurent83b88082014-06-20 18:31:16 -07004089 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004090 }
4091 // TODO: check from routing capabilities in config file and other conflicting patches
4092
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004093installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004094 status_t status = installPatch(
4095 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004096 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004097 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004098 return INVALID_OPERATION;
4099 }
4100 } else {
4101 return BAD_VALUE;
4102 }
4103 } else {
4104 return BAD_VALUE;
4105 }
4106 return NO_ERROR;
4107}
4108
4109status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4110 uid_t uid)
4111{
4112 ALOGV("releaseAudioPatch() patch %d", handle);
4113
4114 ssize_t index = mAudioPatches.indexOfKey(handle);
4115
4116 if (index < 0) {
4117 return BAD_VALUE;
4118 }
4119 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004120 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4121 __func__, mUidCached, patchDesc->getUid(), uid);
4122 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 return INVALID_OPERATION;
4124 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004125 return releaseAudioPatchInternal(handle);
4126}
Eric Laurent6a94d692014-05-20 11:18:06 -07004127
François Gaffieafd4cea2019-11-18 15:50:22 +01004128status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4129 uint32_t delayMs)
4130{
4131 ALOGV("%s patch %d", __func__, handle);
4132 if (mAudioPatches.indexOfKey(handle) < 0) {
4133 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4134 return BAD_VALUE;
4135 }
4136 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004138 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004139 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004140 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004141 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004142 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004143 return BAD_VALUE;
4144 }
4145
François Gaffie11d30102018-11-02 16:09:09 +01004146 setOutputDevices(outputDesc,
4147 getNewOutputDevices(outputDesc, true /*fromCache*/),
4148 true,
4149 0,
4150 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004151 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4152 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004153 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004155 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004156 return BAD_VALUE;
4157 }
4158 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004159 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004160 true,
4161 NULL);
4162 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004163 status_t status =
4164 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4165 ALOGV("%s patch panel returned %d patchHandle %d",
4166 __func__, status, patchDesc->getAfHandle());
4167 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004168 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004169 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004170 // SW Bridge
4171 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4172 sp<SwAudioOutputDescriptor> outputDesc =
4173 mOutputs.getOutputFromId(patch->sources[1].id);
4174 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004175 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4176 // releaseOutput has already called closeOuput in case of direct output
4177 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004178 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004179 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4180 // force SwOutput patch removal as AF counter part patch has already gone.
4181 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4182 removeAudioPatch(outputDesc->getPatchHandle());
4183 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004184 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4185 setOutputDevices(outputDesc,
4186 getNewOutputDevices(outputDesc, true /*fromCache*/),
4187 true, /*force*/
4188 0,
4189 NULL);
4190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 } else {
4192 return BAD_VALUE;
4193 }
4194 } else {
4195 return BAD_VALUE;
4196 }
4197 return NO_ERROR;
4198}
4199
4200status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4201 struct audio_patch *patches,
4202 unsigned int *generation)
4203{
François Gaffie53615e22015-03-19 09:24:12 +01004204 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004205 return BAD_VALUE;
4206 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004208 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004209}
4210
Eric Laurente1715a42014-05-20 11:30:42 -07004211status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004212{
Eric Laurente1715a42014-05-20 11:30:42 -07004213 ALOGV("setAudioPortConfig()");
4214
4215 if (config == NULL) {
4216 return BAD_VALUE;
4217 }
4218 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4219 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004220 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4221 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004222 }
4223
Eric Laurenta121f902014-06-03 13:32:54 -07004224 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004225 if (config->type == AUDIO_PORT_TYPE_MIX) {
4226 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004227 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004228 if (outputDesc == NULL) {
4229 return BAD_VALUE;
4230 }
Eric Laurent84c70242014-06-23 08:46:27 -07004231 ALOG_ASSERT(!outputDesc->isDuplicated(),
4232 "setAudioPortConfig() called on duplicated output %d",
4233 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004234 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004235 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004236 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004237 if (inputDesc == NULL) {
4238 return BAD_VALUE;
4239 }
Eric Laurenta121f902014-06-03 13:32:54 -07004240 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004241 } else {
4242 return BAD_VALUE;
4243 }
4244 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4245 sp<DeviceDescriptor> deviceDesc;
4246 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4247 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4248 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4249 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4250 } else {
4251 return BAD_VALUE;
4252 }
4253 if (deviceDesc == NULL) {
4254 return BAD_VALUE;
4255 }
Eric Laurenta121f902014-06-03 13:32:54 -07004256 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004257 } else {
4258 return BAD_VALUE;
4259 }
4260
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004261 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004262 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4263 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004264 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004265 audioPortConfig->toAudioPortConfig(&newConfig, config);
4266 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004267 }
Eric Laurenta121f902014-06-03 13:32:54 -07004268 if (status != NO_ERROR) {
4269 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004270 }
Eric Laurente1715a42014-05-20 11:30:42 -07004271
4272 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004273}
4274
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004275void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4276{
Eric Laurentd60560a2015-04-10 11:31:20 -07004277 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004278 clearAudioPatches(uid);
4279 clearSessionRoutes(uid);
4280}
4281
Eric Laurent6a94d692014-05-20 11:18:06 -07004282void AudioPolicyManager::clearAudioPatches(uid_t uid)
4283{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004284 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004285 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004286 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004287 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004288 }
4289 }
4290}
4291
François Gaffiec005e562018-11-06 15:04:49 +01004292void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004293{
François Gaffiec005e562018-11-06 15:04:49 +01004294 // Take the first attributes following the product strategy as it is used to retrieve the routed
4295 // device. All attributes wihin a strategy follows the same "routing strategy"
4296 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4297 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004298 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004299 for (size_t j = 0; j < mOutputs.size(); j++) {
4300 if (mOutputs.keyAt(j) == ouptutToSkip) {
4301 continue;
4302 }
4303 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004304 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004305 continue;
4306 }
4307 // If the default device for this strategy is on another output mix,
4308 // invalidate all tracks in this strategy to force re connection.
4309 // Otherwise select new device on the output mix.
4310 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004311 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4312 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004313 }
4314 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004315 setOutputDevices(
4316 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004317 }
4318 }
4319}
4320
4321void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4322{
4323 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004324 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004325 for (size_t i = 0; i < mOutputs.size(); i++) {
4326 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004327 for (const auto& client : outputDesc->getClientIterable()) {
4328 if (client->hasPreferredDevice() && client->uid() == uid) {
4329 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004330 auto clientStrategy = client->strategy();
4331 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4332 end(affectedStrategies)) {
4333 continue;
4334 }
4335 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004336 }
4337 }
4338 }
4339 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004340 for (const auto& strategy : affectedStrategies) {
4341 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004342 }
4343
4344 // remove input routes associated with this uid
4345 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004346 for (size_t i = 0; i < mInputs.size(); i++) {
4347 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004348 for (const auto& client : inputDesc->getClientIterable()) {
4349 if (client->hasPreferredDevice() && client->uid() == uid) {
4350 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4351 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004352 }
4353 }
4354 }
4355 // reroute inputs if necessary
4356 SortedVector<audio_io_handle_t> inputsToClose;
4357 for (size_t i = 0; i < mInputs.size(); i++) {
4358 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004359 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004360 inputsToClose.add(inputDesc->mIoHandle);
4361 }
4362 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004363 for (const auto& input : inputsToClose) {
4364 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004365 }
4366}
4367
Eric Laurentd60560a2015-04-10 11:31:20 -07004368void AudioPolicyManager::clearAudioSources(uid_t uid)
4369{
4370 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004371 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4372 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004373 stopAudioSource(mAudioSources.keyAt(i));
4374 }
4375 }
4376}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004377
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004378status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4379 audio_io_handle_t *ioHandle,
4380 audio_devices_t *device)
4381{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004382 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4383 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004384 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004385 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004386
François Gaffiedf372692015-03-19 10:43:27 +01004387 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004388}
4389
Eric Laurentd60560a2015-04-10 11:31:20 -07004390status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004391 const audio_attributes_t *attributes,
4392 audio_port_handle_t *portId,
4393 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004394{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004395 ALOGV("%s", __FUNCTION__);
4396 *portId = AUDIO_PORT_HANDLE_NONE;
4397
4398 if (source == NULL || attributes == NULL || portId == NULL) {
4399 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4400 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004401 return BAD_VALUE;
4402 }
4403
Eric Laurentd60560a2015-04-10 11:31:20 -07004404 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4405 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004406 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4407 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004408 return INVALID_OPERATION;
4409 }
4410
François Gaffie11d30102018-11-02 16:09:09 +01004411 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004412 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004413 String8(source->ext.device.address),
4414 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004415 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004416 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004417 return BAD_VALUE;
4418 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004419
jiabin4ef93452019-09-10 14:29:54 -07004420 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004421
François Gaffieaaac0fd2018-11-22 17:56:39 +01004422 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004423 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004424 mEngine->getStreamTypeForAttributes(*attributes),
4425 mEngine->getProductStrategyForAttributes(*attributes),
4426 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004427
4428 status_t status = connectAudioSource(sourceDesc);
4429 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004430 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004431 }
4432 return status;
4433}
4434
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004435status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004436{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004437 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004438
4439 // make sure we only have one patch per source.
4440 disconnectAudioSource(sourceDesc);
4441
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004442 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004443 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4444 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4445 sourceDesc->srcDevice()->type(),
4446 String8(sourceDesc->srcDevice()->address().c_str()),
4447 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004448 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004449 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004450 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004451 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004452 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4453 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4454 return INVALID_OPERATION;
4455 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004456 PatchBuilder patchBuilder;
4457 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4458 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4459 status_t status =
4460 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4461 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4462 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4463 return INVALID_OPERATION;
4464 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004465 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004466 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4467 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4468 if (swOutput != 0) {
4469 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004470 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004471 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004472 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004473 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004474 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004475 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004476 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004477 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004478 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004479 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004480 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4482 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004483 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004484 if (delayMs != 0) {
4485 usleep(delayMs * 1000);
4486 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 } else {
4488 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4489 if (hwOutputDesc != 0) {
4490 // create Hwoutput and add to mHwOutputs
4491 } else {
4492 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4493 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004494 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004495 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004496
4497FailureSourceActive:
4498 swOutput->stop();
4499 releaseOutput(sourceDesc->portId());
4500FailureSourceAdded:
4501 sourceDesc->setSwOutput(nullptr);
4502FailureReleasePatch:
4503 releaseAudioPatchInternal(handle);
4504 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004505}
4506
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004507status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004508{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004509 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4510 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004511 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004512 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004513 return BAD_VALUE;
4514 }
4515 status_t status = disconnectAudioSource(sourceDesc);
4516
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004517 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004518 return status;
4519}
4520
Andy Hung2ddee192015-12-18 17:34:44 -08004521status_t AudioPolicyManager::setMasterMono(bool mono)
4522{
4523 if (mMasterMono == mono) {
4524 return NO_ERROR;
4525 }
4526 mMasterMono = mono;
4527 // if enabling mono we close all offloaded devices, which will invalidate the
4528 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4529 // for recreating the new AudioTrack as non-offloaded PCM.
4530 //
4531 // If disabling mono, we leave all tracks as is: we don't know which clients
4532 // and tracks are able to be recreated as offloaded. The next "song" should
4533 // play back offloaded.
4534 if (mMasterMono) {
4535 Vector<audio_io_handle_t> offloaded;
4536 for (size_t i = 0; i < mOutputs.size(); ++i) {
4537 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4538 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4539 offloaded.push(desc->mIoHandle);
4540 }
4541 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004542 for (const auto& handle : offloaded) {
4543 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004544 }
4545 }
4546 // update master mono for all remaining outputs
4547 for (size_t i = 0; i < mOutputs.size(); ++i) {
4548 updateMono(mOutputs.keyAt(i));
4549 }
4550 return NO_ERROR;
4551}
4552
4553status_t AudioPolicyManager::getMasterMono(bool *mono)
4554{
4555 *mono = mMasterMono;
4556 return NO_ERROR;
4557}
4558
Eric Laurentac9cef52017-06-09 15:46:26 -07004559float AudioPolicyManager::getStreamVolumeDB(
4560 audio_stream_type_t stream, int index, audio_devices_t device)
4561{
jiabin9a3361e2019-10-01 09:38:30 -07004562 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004563}
4564
jiabin81772902018-04-02 17:52:27 -07004565status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4566 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004567 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004568{
Kriti Dang6537def2021-03-02 13:46:59 +01004569 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4570 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004571 return BAD_VALUE;
4572 }
Kriti Dang6537def2021-03-02 13:46:59 +01004573 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4574 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004575
4576 size_t formatsWritten = 0;
4577 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004578
Kriti Dang6537def2021-03-02 13:46:59 +01004579 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004580 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4581 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004582 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004583 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004584 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004585 bool formatEnabled = true;
4586 switch (forceUse) {
4587 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004588 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004589 break;
4590 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4591 formatEnabled = false;
4592 break;
4593 default: // AUTO or ALWAYS => true
4594 break;
jiabin81772902018-04-02 17:52:27 -07004595 }
4596 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4597 }
jiabin81772902018-04-02 17:52:27 -07004598 }
4599 return NO_ERROR;
4600}
4601
Kriti Dang6537def2021-03-02 13:46:59 +01004602status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4603 audio_format_t *surroundFormats) {
4604 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4605 return BAD_VALUE;
4606 }
4607 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4608 __func__, *numSurroundFormats, surroundFormats);
4609
4610 size_t formatsWritten = 0;
4611 size_t formatsMax = *numSurroundFormats;
4612 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4613
4614 // Return formats from all device profiles that have already been resolved by
4615 // checkOutputsForDevice().
4616 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4617 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4618 audio_devices_t deviceType = device->type();
4619 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4620 // returns formats reported by HDMI devices.
4621 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4622 continue;
4623 }
4624 // Formats reported by sink devices
4625 std::unordered_set<audio_format_t> formatset;
4626 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4627 formatset.insert(it->second.begin(), it->second.end());
4628 }
4629
4630 // Formats hard-coded in the in policy configuration file (if any).
4631 FormatVector encodedFormats = device->encodedFormats();
4632 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4633 // Filter the formats which are supported by the vendor hardware.
4634 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4635 if (mConfig.getSurroundFormats().count(*it) != 0) {
4636 formats.insert(*it);
4637 } else {
4638 for (const auto& pair : mConfig.getSurroundFormats()) {
4639 if (pair.second.count(*it) != 0) {
4640 formats.insert(pair.first);
4641 break;
4642 }
4643 }
4644 }
4645 }
4646 }
4647 *numSurroundFormats = formats.size();
4648 for (const auto& format: formats) {
4649 if (formatsWritten < formatsMax) {
4650 surroundFormats[formatsWritten++] = format;
4651 }
4652 }
4653 return NO_ERROR;
4654}
4655
jiabin81772902018-04-02 17:52:27 -07004656status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4657{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004658 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004659 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4660 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004661 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004662 return BAD_VALUE;
4663 }
4664
Mikhail Naganov100f0122018-11-29 11:22:16 -08004665 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4666 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004667 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004668 return INVALID_OPERATION;
4669 }
4670
Mikhail Naganov100f0122018-11-29 11:22:16 -08004671 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004672 return NO_ERROR;
4673 }
4674
Mikhail Naganov100f0122018-11-29 11:22:16 -08004675 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004676 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004677 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004678 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004679 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004680 }
4681 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004682 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004683 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004684 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004685 }
4686 }
4687
4688 sp<SwAudioOutputDescriptor> outputDesc;
4689 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004690 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4691 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004692 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4693 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004694 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004695 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004696 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4697 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4698 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004699 name.c_str(),
4700 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004701 if (status != NO_ERROR) {
4702 continue;
4703 }
4704 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4705 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
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 profileUpdated |= (status == NO_ERROR);
4710 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004711 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004712 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004713 AUDIO_DEVICE_IN_HDMI);
4714 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4715 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004716 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004717 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004718 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4719 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4720 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004721 name.c_str(),
4722 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004723 if (status != NO_ERROR) {
4724 continue;
4725 }
4726 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4727 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4728 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004729 name.c_str(),
4730 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004731 profileUpdated |= (status == NO_ERROR);
4732 }
4733
jiabin81772902018-04-02 17:52:27 -07004734 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004735 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004736 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004737 }
4738
4739 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4740}
4741
Eric Laurent5ada82e2019-08-29 17:53:54 -07004742void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004743{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004744 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004745 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004746 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004747 }
4748}
4749
jiabin6012f912018-11-02 17:06:30 -07004750bool AudioPolicyManager::isHapticPlaybackSupported()
4751{
4752 for (const auto& hwModule : mHwModules) {
4753 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4754 for (const auto &outProfile : outputProfiles) {
4755 struct audio_port audioPort;
4756 outProfile->toAudioPort(&audioPort);
4757 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4758 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4759 return true;
4760 }
4761 }
4762 }
4763 }
4764 return false;
4765}
4766
Eric Laurent8340e672019-11-06 11:01:08 -08004767bool AudioPolicyManager::isCallScreenModeSupported()
4768{
4769 return getConfig().isCallScreenModeSupported();
4770}
4771
4772
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004773status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004774{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004775 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004776 if (!sourceDesc->isConnected()) {
4777 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4778 return NO_ERROR;
4779 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004780 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4781 if (swOutput != 0) {
4782 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004783 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004784 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004785 }
jiabinbce0c1d2020-10-05 11:20:18 -07004786 if (releaseOutput(sourceDesc->portId())) {
4787 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4788 // no need to release audio patch here but just return NO_ERROR.
4789 return NO_ERROR;
4790 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004791 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004792 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004793 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004794 // close Hwoutput and remove from mHwOutputs
4795 } else {
4796 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4797 }
4798 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004799 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4800 sourceDesc->disconnect();
4801 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004802}
4803
François Gaffiec005e562018-11-06 15:04:49 +01004804sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4805 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004806{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004807 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004808 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004809 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004810 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004811 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4812 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004813 source = sourceDesc;
4814 break;
4815 }
4816 }
4817 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004818}
4819
Eric Laurente552edb2014-03-10 17:42:56 -07004820// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004821// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004822// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004823uint32_t AudioPolicyManager::nextAudioPortGeneration()
4824{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004825 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004826}
4827
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004828static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004829 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4830 !audioPolicyXmlConfigFile.empty()) {
4831 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4832 if (ret == NO_ERROR) {
4833 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004834 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004835 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004836 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004837 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004838}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004839
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004840AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4841 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004842 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004843 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004844 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004845 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004846 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004847 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004848 mAudioPortGeneration(1),
4849 mBeaconMuteRefCount(0),
4850 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004851 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004852 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004853 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004854 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004855{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004856}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004857
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004858AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4859 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4860{
4861 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004862}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004863
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004864void AudioPolicyManager::loadConfig() {
4865 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004866 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004867 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004868 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004869}
4870
4871status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004872 {
4873 auto engLib = EngineLibrary::load(
4874 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4875 if (!engLib) {
4876 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4877 return NO_INIT;
4878 }
4879 mEngine = engLib->createEngine();
4880 if (mEngine == nullptr) {
4881 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4882 return NO_INIT;
4883 }
François Gaffie2110e042015-03-24 08:41:51 +01004884 }
4885 mEngine->setObserver(this);
4886 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004887 if (status != NO_ERROR) {
4888 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4889 return status;
4890 }
François Gaffie2110e042015-03-24 08:41:51 +01004891
Eric Laurent1d69c872021-01-11 18:53:01 +01004892 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4893 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4894
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004895 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004896 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004897 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004898
Eric Laurent3a4311c2014-03-17 12:00:47 -07004899 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004900 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4901 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4902 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004903 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004904 }
jiabin9ff780e2018-03-19 18:19:52 -07004905 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004906 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004907 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004908 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004909 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004910 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004911 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004912 }
4913 }
4914 }
Eric Laurente552edb2014-03-10 17:42:56 -07004915
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004916 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004917
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004918 // Silence ALOGV statements
4919 property_set("log.tag." LOG_TAG, "D");
4920
Eric Laurente552edb2014-03-10 17:42:56 -07004921 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004922 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004923}
4924
Eric Laurente0720872014-03-11 09:30:41 -07004925AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004926{
Eric Laurente552edb2014-03-10 17:42:56 -07004927 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004928 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004929 }
4930 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004931 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004932 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004933 mAvailableOutputDevices.clear();
4934 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004935 mOutputs.clear();
4936 mInputs.clear();
4937 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004938 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004939 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004940}
4941
Eric Laurente0720872014-03-11 09:30:41 -07004942status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004943{
Eric Laurent87ffa392015-05-22 10:32:38 -07004944 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004945}
4946
Eric Laurente552edb2014-03-10 17:42:56 -07004947// ---
4948
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004949void AudioPolicyManager::onNewAudioModulesAvailable()
4950{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004951 DeviceVector newDevices;
4952 onNewAudioModulesAvailableInt(&newDevices);
4953 if (!newDevices.empty()) {
4954 nextAudioPortGeneration();
4955 mpClientInterface->onAudioPortListUpdate();
4956 }
4957}
4958
4959void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4960{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004961 for (const auto& hwModule : mHwModulesAll) {
4962 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4963 continue;
4964 }
4965 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4966 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4967 ALOGW("could not open HW module %s", hwModule->getName());
4968 continue;
4969 }
4970 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10004971 // open all output streams needed to access attached devices.
4972 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004973 // This also validates mAvailableOutputDevices list
4974 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4975 if (!outProfile->canOpenNewIo()) {
4976 ALOGE("Invalid Output profile max open count %u for profile %s",
4977 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4978 continue;
4979 }
4980 if (!outProfile->hasSupportedDevices()) {
4981 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4982 continue;
4983 }
4984 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4985 mTtsOutputAvailable = true;
4986 }
4987
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004988 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4989 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4990 sp<DeviceDescriptor> supportedDevice = 0;
4991 if (supportedDevices.contains(mDefaultOutputDevice)) {
4992 supportedDevice = mDefaultOutputDevice;
4993 } else {
4994 // choose first device present in profile's SupportedDevices also part of
4995 // mAvailableOutputDevices.
4996 if (availProfileDevices.isEmpty()) {
4997 continue;
4998 }
4999 supportedDevice = availProfileDevices.itemAt(0);
5000 }
5001 if (!mOutputDevicesAll.contains(supportedDevice)) {
5002 continue;
5003 }
5004 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5005 mpClientInterface);
5006 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5007 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
5008 AUDIO_STREAM_DEFAULT,
5009 AUDIO_OUTPUT_FLAG_NONE, &output);
5010 if (status != NO_ERROR) {
5011 ALOGW("Cannot open output stream for devices %s on hw module %s",
5012 supportedDevice->toString().c_str(), hwModule->getName());
5013 continue;
5014 }
5015 for (const auto &device : availProfileDevices) {
5016 // give a valid ID to an attached device once confirmed it is reachable
5017 if (!device->isAttached()) {
5018 device->attach(hwModule);
5019 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005020 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005021 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005022 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5023 }
5024 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005025 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005026 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5027 mPrimaryOutput = outputDesc;
5028 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005029 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5030 outputDesc->close();
5031 } else {
5032 addOutput(output, outputDesc);
5033 setOutputDevices(outputDesc,
5034 DeviceVector(supportedDevice),
5035 true,
5036 0,
5037 NULL);
5038 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005039 }
5040 // open input streams needed to access attached devices to validate
5041 // mAvailableInputDevices list
5042 for (const auto& inProfile : hwModule->getInputProfiles()) {
5043 if (!inProfile->canOpenNewIo()) {
5044 ALOGE("Invalid Input profile max open count %u for profile %s",
5045 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5046 continue;
5047 }
5048 if (!inProfile->hasSupportedDevices()) {
5049 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5050 continue;
5051 }
5052 // chose first device present in profile's SupportedDevices also part of
5053 // available input devices
5054 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5055 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5056 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005057 ALOGV("%s: Input device list is empty! for profile %s",
5058 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005059 continue;
5060 }
5061 sp<AudioInputDescriptor> inputDesc =
5062 new AudioInputDescriptor(inProfile, mpClientInterface);
5063
5064 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5065 status_t status = inputDesc->open(nullptr,
5066 availProfileDevices.itemAt(0),
5067 AUDIO_SOURCE_MIC,
5068 AUDIO_INPUT_FLAG_NONE,
5069 &input);
5070 if (status != NO_ERROR) {
5071 ALOGW("Cannot open input stream for device %s on hw module %s",
5072 availProfileDevices.toString().c_str(),
5073 hwModule->getName());
5074 continue;
5075 }
5076 for (const auto &device : availProfileDevices) {
5077 // give a valid ID to an attached device once confirmed it is reachable
5078 if (!device->isAttached()) {
5079 device->attach(hwModule);
5080 device->importAudioPortAndPickAudioProfile(inProfile, true);
5081 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005082 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005083 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5084 }
5085 }
5086 inputDesc->close();
5087 }
5088 }
5089}
5090
Eric Laurent98e38192018-02-15 18:31:53 -08005091void AudioPolicyManager::addOutput(audio_io_handle_t output,
5092 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005093{
Eric Laurent1c333e22014-05-20 10:48:17 -07005094 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005095 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005096 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005097 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005099}
5100
François Gaffie53615e22015-03-19 09:24:12 +01005101void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5102{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005103 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5104 ALOGV("%s: removing primary output", __func__);
5105 mPrimaryOutput = nullptr;
5106 }
François Gaffie53615e22015-03-19 09:24:12 +01005107 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005108 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005109}
5110
Eric Laurent98e38192018-02-15 18:31:53 -08005111void AudioPolicyManager::addInput(audio_io_handle_t input,
5112 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005113{
Eric Laurent1c333e22014-05-20 10:48:17 -07005114 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005116}
Eric Laurente552edb2014-03-10 17:42:56 -07005117
François Gaffie11d30102018-11-02 16:09:09 +01005118status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005119 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005120 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005121{
François Gaffie11d30102018-11-02 16:09:09 +01005122 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005123 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005124 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005125
François Gaffie11d30102018-11-02 16:09:09 +01005126 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005127 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005128 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005129 }
Eric Laurente552edb2014-03-10 17:42:56 -07005130
Eric Laurent3b73df72014-03-11 09:06:29 -07005131 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005132 // first call getAudioPort to get the supported attributes from the HAL
5133 struct audio_port_v7 port = {};
5134 device->toAudioPort(&port);
5135 status_t status = mpClientInterface->getAudioPort(&port);
5136 if (status == NO_ERROR) {
5137 device->importAudioPort(port);
5138 }
5139
5140 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005141 for (size_t i = 0; i < mOutputs.size(); i++) {
5142 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005143 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005144 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005145 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5146 mOutputs.keyAt(i), device->toString().c_str());
5147 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005148 }
5149 }
5150 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005151 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005152 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005153 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5154 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005155 if (profile->supportsDevice(device)) {
5156 profiles.add(profile);
5157 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5158 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005159 }
5160 }
5161 }
5162
Eric Laurent7b279bb2015-12-14 10:18:23 -08005163 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005164
Eric Laurente552edb2014-03-10 17:42:56 -07005165 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005166 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005167 return BAD_VALUE;
5168 }
5169
5170 // open outputs for matching profiles if needed. Direct outputs are also opened to
5171 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5172 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005173 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005174
5175 // nothing to do if one output is already opened for this profile
5176 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005177 for (j = 0; j < outputs.size(); j++) {
5178 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005179 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005180 // matching profile: save the sample rates, format and channel masks supported
5181 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005182 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005183 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005184 }
Eric Laurente552edb2014-03-10 17:42:56 -07005185 break;
5186 }
5187 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005188 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005189 continue;
5190 }
5191
Eric Laurent3974e3b2017-12-07 17:58:43 -08005192 if (!profile->canOpenNewIo()) {
5193 ALOGW("Max Output number %u already opened for this profile %s",
5194 profile->maxOpenCount, profile->getTagName().c_str());
5195 continue;
5196 }
5197
Eric Laurent83efe1c2017-07-09 16:51:08 -07005198 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005199 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005200 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5201 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005202 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005203 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005204 profiles.removeAt(profile_index);
5205 profile_index--;
5206 } else {
5207 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005208 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005209 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005210 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5211 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005212 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005213 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005214
François Gaffie11d30102018-11-02 16:09:09 +01005215 if (device_distinguishes_on_address(deviceType)) {
5216 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5217 device->toString().c_str());
5218 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5219 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005220 }
Eric Laurente552edb2014-03-10 17:42:56 -07005221 ALOGV("checkOutputsForDevice(): adding output %d", output);
5222 }
5223 }
5224
5225 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005226 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 return BAD_VALUE;
5228 }
Eric Laurentd4692962014-05-05 18:13:44 -07005229 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005230 // check if one opened output is not needed any more after disconnecting one device
5231 for (size_t i = 0; i < mOutputs.size(); i++) {
5232 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005233 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005234 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005235 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005236 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005237 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005238 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005239 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5240 mOutputs.keyAt(i));
5241 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005242 }
Eric Laurente552edb2014-03-10 17:42:56 -07005243 }
5244 }
Eric Laurentd4692962014-05-05 18:13:44 -07005245 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005246 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005247 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5248 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005249 if (!profile->supportsDevice(device)) {
5250 continue;
5251 }
5252 ALOGV("checkOutputsForDevice(): "
5253 "clearing direct output profile %zu on module %s",
5254 j, hwModule->getName());
5255 profile->clearAudioProfiles();
5256 if (!profile->hasDynamicAudioProfile()) {
5257 continue;
5258 }
5259 // When a device is disconnected, if there is an IOProfile that contains dynamic
5260 // profiles and supports the disconnected device, call getAudioPort to repopulate
5261 // the capabilities of the devices that is supported by the IOProfile.
5262 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5263 if (supportedDevice == device ||
5264 !mAvailableOutputDevices.contains(supportedDevice)) {
5265 continue;
5266 }
5267 struct audio_port_v7 port;
5268 supportedDevice->toAudioPort(&port);
5269 status_t status = mpClientInterface->getAudioPort(&port);
5270 if (status == NO_ERROR) {
5271 supportedDevice->importAudioPort(port);
5272 }
Eric Laurente552edb2014-03-10 17:42:56 -07005273 }
5274 }
5275 }
5276 }
5277 return NO_ERROR;
5278}
5279
François Gaffie11d30102018-11-02 16:09:09 +01005280status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005281 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005282{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005283 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005284
François Gaffie11d30102018-11-02 16:09:09 +01005285 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005286 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005287 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005288 }
5289
Eric Laurentd4692962014-05-05 18:13:44 -07005290 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005291 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005292 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005293 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005294 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005295 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005296 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005297 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005298
François Gaffie11d30102018-11-02 16:09:09 +01005299 if (profile->supportsDevice(device)) {
5300 profiles.add(profile);
5301 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5302 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005303 }
5304 }
5305 }
5306
Eric Laurent0dd51852019-04-19 18:18:58 -07005307 if (profiles.isEmpty()) {
5308 ALOGW("%s: No input profile available for device %s",
5309 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005310 return BAD_VALUE;
5311 }
5312
5313 // open inputs for matching profiles if needed. Direct inputs are also opened to
5314 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5315 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5316
Eric Laurent1c333e22014-05-20 10:48:17 -07005317 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005318
Eric Laurentd4692962014-05-05 18:13:44 -07005319 // nothing to do if one input is already opened for this profile
5320 size_t input_index;
5321 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5322 desc = mInputs.valueAt(input_index);
5323 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005324 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005325 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005326 }
Eric Laurentd4692962014-05-05 18:13:44 -07005327 break;
5328 }
5329 }
5330 if (input_index != mInputs.size()) {
5331 continue;
5332 }
5333
Eric Laurent3974e3b2017-12-07 17:58:43 -08005334 if (!profile->canOpenNewIo()) {
5335 ALOGW("Max Input number %u already opened for this profile %s",
5336 profile->maxOpenCount, profile->getTagName().c_str());
5337 continue;
5338 }
5339
Eric Laurentfe231122017-11-17 17:48:06 -08005340 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005341 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005342 status_t status = desc->open(nullptr,
5343 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005344 AUDIO_SOURCE_MIC,
5345 AUDIO_INPUT_FLAG_NONE,
5346 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005347
Eric Laurentcf2c0212014-07-25 16:20:43 -07005348 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005349 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005350 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005351 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005352 mpClientInterface->setParameters(input, String8(param));
5353 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005354 }
François Gaffie11d30102018-11-02 16:09:09 +01005355 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005356 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005357 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005358 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005359 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005360 }
5361
Eric Laurent0dd51852019-04-19 18:18:58 -07005362 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005363 addInput(input, desc);
5364 }
5365 } // endif input != 0
5366
Eric Laurentcf2c0212014-07-25 16:20:43 -07005367 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005368 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005369 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005370 profiles.removeAt(profile_index);
5371 profile_index--;
5372 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005373 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005374 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005375 }
Eric Laurentd4692962014-05-05 18:13:44 -07005376 ALOGV("checkInputsForDevice(): adding input %d", input);
5377 }
5378 } // end scan profiles
5379
5380 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005381 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005382 return BAD_VALUE;
5383 }
5384 } else {
5385 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005386 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005387 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005388 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005389 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005390 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005391 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005392 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005393 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5394 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005395 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005396 }
5397 }
5398 }
5399 } // end disconnect
5400
5401 return NO_ERROR;
5402}
5403
5404
Eric Laurente0720872014-03-11 09:30:41 -07005405void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005406{
5407 ALOGV("closeOutput(%d)", output);
5408
François Gaffie1c878552018-11-22 16:53:21 +01005409 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5410 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005411 ALOGW("closeOutput() unknown output %d", output);
5412 return;
5413 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005414 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005415 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005416
Eric Laurente552edb2014-03-10 17:42:56 -07005417 // look for duplicated outputs connected to the output being removed.
5418 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005419 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5420 if (dupOutput->isDuplicated() &&
5421 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5422 sp<SwAudioOutputDescriptor> remainingOutput =
5423 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005424 // As all active tracks on duplicated output will be deleted,
5425 // and as they were also referenced on the other output, the reference
5426 // count for their stream type must be adjusted accordingly on
5427 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005428 const bool wasActive = remainingOutput->isActive();
5429 // Note: no-op on the closing output where all clients has already been set inactive
5430 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005431 // stop() will be a no op if the output is still active but is needed in case all
5432 // active streams refcounts where cleared above
5433 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005434 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005435 }
Eric Laurente552edb2014-03-10 17:42:56 -07005436 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5437 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5438
5439 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005440 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005441 }
5442 }
5443
Eric Laurent05b90f82014-08-27 15:32:29 -07005444 nextAudioPortGeneration();
5445
François Gaffie1c878552018-11-22 16:53:21 +01005446 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005447 if (index >= 0) {
5448 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5450 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005451 mAudioPatches.removeItemsAt(index);
5452 mpClientInterface->onAudioPatchListUpdate();
5453 }
5454
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005455 if (closingOutputWasActive) {
5456 closingOutput->stop();
5457 }
François Gaffie1c878552018-11-22 16:53:21 +01005458 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005459
François Gaffie53615e22015-03-19 09:24:12 +01005460 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005461 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005462
5463 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5464 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005465 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005466 bool directOutputOpen = false;
5467 for (size_t i = 0; i < mOutputs.size(); i++) {
5468 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5469 directOutputOpen = true;
5470 break;
5471 }
5472 }
5473 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005474 ALOGV("no direct outputs open, reset MSD patches");
5475 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5476 // how output devices for patching are resolved. Avoid by caching and reusing the
5477 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5478 // devices to patch to. This may be complicated by the fact that devices may become
5479 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005480 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005481 }
5482 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005483}
5484
5485void AudioPolicyManager::closeInput(audio_io_handle_t input)
5486{
5487 ALOGV("closeInput(%d)", input);
5488
5489 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5490 if (inputDesc == NULL) {
5491 ALOGW("closeInput() unknown input %d", input);
5492 return;
5493 }
5494
Eric Laurent6a94d692014-05-20 11:18:06 -07005495 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005496
François Gaffie11d30102018-11-02 16:09:09 +01005497 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005498 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005499 if (index >= 0) {
5500 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005501 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5502 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005503 mAudioPatches.removeItemsAt(index);
5504 mpClientInterface->onAudioPatchListUpdate();
5505 }
5506
Eric Laurentfe231122017-11-17 17:48:06 -08005507 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005508 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005509
François Gaffie11d30102018-11-02 16:09:09 +01005510 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5511 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005512 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005513 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005514 }
Eric Laurente552edb2014-03-10 17:42:56 -07005515}
5516
François Gaffie11d30102018-11-02 16:09:09 +01005517SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5518 const DeviceVector &devices,
5519 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005520{
5521 SortedVector<audio_io_handle_t> outputs;
5522
François Gaffie11d30102018-11-02 16:09:09 +01005523 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005524 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005525 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005526 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005527 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005528 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005529 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005530 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005531 outputs.add(openOutputs.keyAt(i));
5532 }
5533 }
5534 return outputs;
5535}
5536
Mikhail Naganov37977152018-07-11 15:54:44 -07005537void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5538{
5539 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5540 // output is suspended before any tracks are moved to it
5541 checkA2dpSuspend();
5542 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005543 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005544 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005545 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005546 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005547 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5548 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5549 // configuration changes will ultimately be rerouted correctly. We can still avoid
5550 // unnecessary rerouting by caching and reusing the arguments to
5551 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5552 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005553 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005554 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005555 // an event that changed routing likely occurred, inform upper layers
5556 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005557}
5558
François Gaffiec005e562018-11-06 15:04:49 +01005559bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5560 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005561{
François Gaffiec005e562018-11-06 15:04:49 +01005562 return mEngine->getProductStrategyForAttributes(lAttr) ==
5563 mEngine->getProductStrategyForAttributes(rAttr);
5564}
5565
Francois Gaffieff1eb522020-05-06 18:37:04 +02005566void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5567{
5568 for (size_t i = 0; i < mAudioSources.size(); i++) {
5569 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5570 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005571 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5572 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005573 connectAudioSource(sourceDesc);
5574 }
5575 }
5576}
5577
5578void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5579{
5580 for (size_t i = 0; i < mAudioSources.size(); i++) {
5581 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5582 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5583 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5584 disconnectAudioSource(sourceDesc);
5585 }
5586 }
5587}
5588
François Gaffiec005e562018-11-06 15:04:49 +01005589void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5590{
5591 auto psId = mEngine->getProductStrategyForAttributes(attr);
5592
5593 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5594 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005595
François Gaffie11d30102018-11-02 16:09:09 +01005596 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5597 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005598
Eric Laurentc209fe42020-06-05 18:11:23 -07005599 uint32_t maxLatency = 0;
5600 bool invalidate = false;
5601 // take into account dynamic audio policies related changes: if a client is now associated
5602 // to a different policy mix than at creation time, invalidate corresponding stream
5603 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5604 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5605 if (desc->isDuplicated()) {
5606 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005607 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005608 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5609 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5610 continue;
5611 }
5612 sp<AudioPolicyMix> primaryMix;
5613 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5614 client->flags(), primaryMix, nullptr);
5615 if (status != OK) {
5616 continue;
5617 }
yucliuf4de36d2020-09-14 14:57:56 -07005618 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005619 invalidate = true;
5620 if (desc->isStrategyActive(psId)) {
5621 maxLatency = desc->latency();
5622 }
5623 break;
5624 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005625 }
5626 }
5627
Eric Laurentc209fe42020-06-05 18:11:23 -07005628 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005629 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5630 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005631 for (audio_io_handle_t srcOut : srcOutputs) {
5632 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005633 if (desc == nullptr) continue;
5634
5635 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005636 maxLatency = desc->latency();
5637 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005638
5639 if (invalidate) continue;
5640
5641 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005642 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005643 // a client on a non direct outputs has necessarily a linear PCM format
5644 // so we can call selectOutput() safely
5645 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5646 client->flags(),
5647 client->config().format,
5648 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005649 client->config().sample_rate,
5650 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005651 if (newOutput != srcOut) {
5652 invalidate = true;
5653 break;
5654 }
5655 } else {
5656 sp<IOProfile> profile = getProfileForOutput(newDevices,
5657 client->config().sample_rate,
5658 client->config().format,
5659 client->config().channel_mask,
5660 client->flags(),
5661 true /* directOnly */);
5662 if (profile != desc->mProfile) {
5663 invalidate = true;
5664 break;
5665 }
5666 }
5667 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005668 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005669
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005670 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005671 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005672 std::to_string(srcOutputs[0]).c_str(),
5673 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005674 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005675 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005676 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005677 if (desc == nullptr) continue;
5678
5679 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005680 setStrategyMute(psId, true, desc);
5681 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005682 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005683 }
François Gaffiec005e562018-11-06 15:04:49 +01005684 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005685 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005686 connectAudioSource(source);
5687 }
Eric Laurente552edb2014-03-10 17:42:56 -07005688 }
5689
François Gaffiec005e562018-11-06 15:04:49 +01005690 // Move effects associated to this stream from previous output to new output
5691 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005692 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005693 }
François Gaffiec005e562018-11-06 15:04:49 +01005694 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005695 if (invalidate) {
5696 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5697 mpClientInterface->invalidateStream(stream);
5698 }
Eric Laurente552edb2014-03-10 17:42:56 -07005699 }
5700 }
5701}
5702
Eric Laurente0720872014-03-11 09:30:41 -07005703void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005704{
François Gaffiec005e562018-11-06 15:04:49 +01005705 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5706 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5707 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005708 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005709 }
Eric Laurente552edb2014-03-10 17:42:56 -07005710}
5711
Kevin Rocard153f92d2018-12-18 18:33:28 -08005712void AudioPolicyManager::checkSecondaryOutputs() {
5713 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005714 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005715 for (size_t i = 0; i < mOutputs.size(); i++) {
5716 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5717 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005718 sp<AudioPolicyMix> primaryMix;
5719 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005720 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005721 client->flags(), primaryMix, &secondaryMixes);
5722 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5723 for (auto &secondaryMix : secondaryMixes) {
5724 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5725 if (outputDesc != nullptr &&
5726 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5727 secondaryDescs.push_back(outputDesc);
5728 }
5729 }
5730
jiabinf042b9b2021-05-07 23:46:28 +00005731 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005732 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005733 } else if (!std::equal(
5734 client->getSecondaryOutputs().begin(),
5735 client->getSecondaryOutputs().end(),
5736 secondaryDescs.begin(), secondaryDescs.end())) {
5737 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5738 std::vector<audio_io_handle_t> secondaryOutputIds;
5739 for (const auto& secondaryDesc : secondaryDescs) {
5740 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5741 weakSecondaryDescs.push_back(secondaryDesc);
5742 }
5743 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5744 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005745 }
5746 }
5747 }
jiabinf042b9b2021-05-07 23:46:28 +00005748 if (!trackSecondaryOutputs.empty()) {
5749 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5750 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005751 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005752 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005753 mpClientInterface->invalidateStream(stream);
5754 }
5755}
5756
Eric Laurent2517af32020-11-25 15:31:27 +01005757bool AudioPolicyManager::isScoRequestedForComm() const {
5758 AudioDeviceTypeAddrVector devices;
5759 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5760 for (const auto &device : devices) {
5761 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5762 return true;
5763 }
5764 }
5765 return false;
5766}
5767
Eric Laurente0720872014-03-11 09:30:41 -07005768void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005769{
François Gaffie53615e22015-03-19 09:24:12 +01005770 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005771 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005772 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005773 return;
5774 }
5775
Eric Laurent3a4311c2014-03-17 12:00:47 -07005776 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005777 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5778 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005779 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005780
5781 // if suspended, restore A2DP output if:
5782 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005783 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005784 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005785 //
Eric Laurentf732e072016-08-03 19:30:28 -07005786 // if not suspended, suspend A2DP output if:
5787 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005788 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005789 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005790 //
5791 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005792 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005793 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005794 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005795 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005796
5797 mpClientInterface->restoreOutput(a2dpOutput);
5798 mA2dpSuspended = false;
5799 }
5800 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005801 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005802 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005803 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005804 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005805
5806 mpClientInterface->suspendOutput(a2dpOutput);
5807 mA2dpSuspended = true;
5808 }
5809 }
5810}
5811
François Gaffie11d30102018-11-02 16:09:09 +01005812DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5813 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005814{
François Gaffie11d30102018-11-02 16:09:09 +01005815 DeviceVector devices;
5816
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005817 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005818 if (index >= 0) {
5819 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005820 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005821 ALOGV("%s device %s forced by patch %d", __func__,
5822 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5823 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005824 }
5825 }
5826
Dean Wheatley514b4312020-06-17 21:45:00 +10005827 // Do not retrieve engine device for outputs through MSD
5828 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5829 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5830 return outputDesc->devices();
5831 }
5832
Eric Laurent97ac8712018-07-27 18:59:02 -07005833 // Honor explicit routing requests only if no client using default routing is active on this
5834 // input: a specific app can not force routing for other apps by setting a preferred device.
5835 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005836 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005837 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005838 if (device != nullptr) {
5839 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005840 }
5841
François Gaffiea807ef92018-11-05 10:44:33 +01005842 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5843 // of setForceUse / Default Bus device here
5844 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5845 if (device != nullptr) {
5846 return DeviceVector(device);
5847 }
5848
François Gaffiec005e562018-11-06 15:04:49 +01005849 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5850 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5851 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305852 auto hasStreamActive = [&](auto stream) {
5853 return hasStream(streams, stream) && isStreamActive(stream, 0);
5854 };
Eric Laurent484e9272018-06-07 17:29:23 -07005855
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305856 auto doGetOutputDevicesForVoice = [&]() {
5857 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5858 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5859 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02005860 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5861 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305862 };
5863
5864 // With low-latency playing on speaker, music on WFD, when the first low-latency
5865 // output is stopped, getNewOutputDevices checks for a product strategy
5866 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00005867 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305868 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5869 // stream is associated to the output descriptor.
5870 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5871 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5872 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5873 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005874 // Retrieval of devices for voice DL is done on primary output profile, cannot
5875 // check the route (would force modifying configuration file for this profile)
5876 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5877 break;
5878 }
Eric Laurente552edb2014-03-10 17:42:56 -07005879 }
François Gaffiec005e562018-11-06 15:04:49 +01005880 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005881 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005882}
5883
François Gaffie11d30102018-11-02 16:09:09 +01005884sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5885 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005886{
François Gaffie11d30102018-11-02 16:09:09 +01005887 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005888
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005889 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005890 if (index >= 0) {
5891 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005892 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005893 ALOGV("getNewInputDevice() device %s forced by patch %d",
5894 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5895 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005896 }
5897 }
5898
Eric Laurent97ac8712018-07-27 18:59:02 -07005899 // Honor explicit routing requests only if no client using default routing is active on this
5900 // input: a specific app can not force routing for other apps by setting a preferred device.
5901 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005902 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5903 if (device != nullptr) {
5904 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005905 }
5906
Eric Laurentdc95a252018-04-12 12:46:56 -07005907 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005908 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005909 audio_attributes_t attributes;
5910 uid_t uid;
5911 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5912 if (topClient != nullptr) {
5913 attributes = topClient->attributes();
5914 uid = topClient->uid();
5915 } else {
5916 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5917 uid = 0;
5918 }
5919
Francois Gaffie716e1432019-01-14 16:58:59 +01005920 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5921 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005922 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005923 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005924 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005925 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005926
Eric Laurente552edb2014-03-10 17:42:56 -07005927 return device;
5928}
5929
Eric Laurent794fde22016-03-11 09:50:45 -08005930bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5931 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005932 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005933}
5934
Eric Laurente0720872014-03-11 09:30:41 -07005935audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005936 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005937 // getOutputDevicesForStream's behavior for invalid streams.
5938 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5939 // device for music stream), but we want to return the empty set.
5940 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005941 return AUDIO_DEVICE_NONE;
5942 }
François Gaffie11d30102018-11-02 16:09:09 +01005943 DeviceVector activeDevices;
5944 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005945 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5946 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005947 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005948 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005949 }
François Gaffiec005e562018-11-06 15:04:49 +01005950 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005951 devices.merge(curDevices);
5952 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005953 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005954 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005955 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005956 }
5957 }
Eric Laurente552edb2014-03-10 17:42:56 -07005958 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005959
Eric Laurentb0688d62018-08-14 15:49:18 -07005960 // Favor devices selected on active streams if any to report correct device in case of
5961 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005962 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005963 devices = activeDevices;
5964 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005965 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5966 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005967 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005968 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005969 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005970 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005971 }
jiabin9a3361e2019-10-01 09:38:30 -07005972 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5973 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005974}
5975
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005976status_t AudioPolicyManager::getDevicesForAttributes(
5977 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5978 if (devices == nullptr) {
5979 return BAD_VALUE;
5980 }
5981 // check dynamic policies but only for primary descriptors (secondary not used for audible
5982 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005983 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005984 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07005985 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005986 if (status != OK) {
5987 return status;
5988 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005989 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5990 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5991 devices->push_back(device);
5992 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005993 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005994 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5995 for (const auto& device : curDevices) {
5996 devices->push_back(device->getDeviceTypeAddr());
5997 }
5998 return NO_ERROR;
5999}
6000
Eric Laurente0720872014-03-11 09:30:41 -07006001void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006002 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006003 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006004 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006005 updateDevicesAndOutputs();
6006 break;
6007 default:
6008 break;
6009 }
6010}
6011
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006012uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006013
6014 // skip beacon mute management if a dedicated TTS output is available
6015 if (mTtsOutputAvailable) {
6016 return 0;
6017 }
6018
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006019 switch(event) {
6020 case STARTING_OUTPUT:
6021 mBeaconMuteRefCount++;
6022 break;
6023 case STOPPING_OUTPUT:
6024 if (mBeaconMuteRefCount > 0) {
6025 mBeaconMuteRefCount--;
6026 }
6027 break;
6028 case STARTING_BEACON:
6029 mBeaconPlayingRefCount++;
6030 break;
6031 case STOPPING_BEACON:
6032 if (mBeaconPlayingRefCount > 0) {
6033 mBeaconPlayingRefCount--;
6034 }
6035 break;
6036 }
6037
6038 if (mBeaconMuteRefCount > 0) {
6039 // any playback causes beacon to be muted
6040 return setBeaconMute(true);
6041 } else {
6042 // no other playback: unmute when beacon starts playing, mute when it stops
6043 return setBeaconMute(mBeaconPlayingRefCount == 0);
6044 }
6045}
6046
6047uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6048 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6049 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6050 // keep track of muted state to avoid repeating mute/unmute operations
6051 if (mBeaconMuted != mute) {
6052 // mute/unmute AUDIO_STREAM_TTS on all outputs
6053 ALOGV("\t muting %d", mute);
6054 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006055 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006056 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006057 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006058 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006059 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006060 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006061 maxLatency = latency;
6062 }
6063 }
6064 mBeaconMuted = mute;
6065 return maxLatency;
6066 }
6067 return 0;
6068}
6069
Eric Laurente0720872014-03-11 09:30:41 -07006070void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006071{
François Gaffiec005e562018-11-06 15:04:49 +01006072 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006073 mPreviousOutputs = mOutputs;
6074}
6075
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006076uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006077 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006078 uint32_t delayMs)
6079{
6080 // mute/unmute strategies using an incompatible device combination
6081 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6082 // if unmuting, unmute only after the specified delay
6083 if (outputDesc->isDuplicated()) {
6084 return 0;
6085 }
6086
6087 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006088 DeviceVector devices = outputDesc->devices();
6089 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006090
François Gaffiec005e562018-11-06 15:04:49 +01006091 auto productStrategies = mEngine->getOrderedProductStrategies();
6092 for (const auto &productStrategy : productStrategies) {
6093 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6094 DeviceVector curDevices =
6095 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6096 curDevices = curDevices.filter(outputDesc->supportedDevices());
6097 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006098 bool doMute = false;
6099
François Gaffiec005e562018-11-06 15:04:49 +01006100 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006101 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006102 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6103 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006104 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006105 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006106 }
Eric Laurent99401132014-05-07 19:48:15 -07006107 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006108 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006109 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006110 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006111 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006112 continue;
6113 }
François Gaffiec005e562018-11-06 15:04:49 +01006114 ALOGVV("%s() %s (curDevice %s)", __func__,
6115 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6116 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6117 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006118 if (mute) {
6119 // FIXME: should not need to double latency if volume could be applied
6120 // immediately by the audioflinger mixer. We must account for the delay
6121 // between now and the next time the audioflinger thread for this output
6122 // will process a buffer (which corresponds to one buffer size,
6123 // usually 1/2 or 1/4 of the latency).
6124 if (muteWaitMs < desc->latency() * 2) {
6125 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006126 }
6127 }
6128 }
6129 }
6130 }
6131 }
6132
Eric Laurent99401132014-05-07 19:48:15 -07006133 // temporary mute output if device selection changes to avoid volume bursts due to
6134 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006135 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006136 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6137 // temporary mute duration is conservatively set to 4 times the reported latency
6138 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6139 if (muteWaitMs < tempMuteWaitMs) {
6140 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006141 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006142 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6143 // make sure that we do not start the temporary mute period too early in case of
6144 // delayed device change
6145 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6146 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006147 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006148 }
6149 }
6150
Eric Laurente552edb2014-03-10 17:42:56 -07006151 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6152 if (muteWaitMs > delayMs) {
6153 muteWaitMs -= delayMs;
6154 usleep(muteWaitMs * 1000);
6155 return muteWaitMs;
6156 }
6157 return 0;
6158}
6159
François Gaffie11d30102018-11-02 16:09:09 +01006160uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6161 const DeviceVector &devices,
6162 bool force,
6163 int delayMs,
6164 audio_patch_handle_t *patchHandle,
6165 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006166{
François Gaffie11d30102018-11-02 16:09:09 +01006167 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006168 uint32_t muteWaitMs;
6169
6170 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006171 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6172 nullptr /* patchHandle */, requiresMuteCheck);
6173 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6174 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006175 return muteWaitMs;
6176 }
Eric Laurente552edb2014-03-10 17:42:56 -07006177
6178 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006179 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006180 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006181
François Gaffie11d30102018-11-02 16:09:09 +01006182 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6183
6184 if (!filteredDevices.isEmpty()) {
6185 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006186 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006187
6188 // if the outputs are not materially active, there is no need to mute.
6189 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006190 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006191 } else {
6192 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6193 muteWaitMs = 0;
6194 }
Eric Laurente552edb2014-03-10 17:42:56 -07006195
Eric Laurent79ea9582020-06-11 18:49:24 -07006196 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6197 // output profile or if new device is not supported AND previous device(s) is(are) still
6198 // available (otherwise reset device must be done on the output)
6199 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6200 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6201 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6202 // restore previous device after evaluating strategy mute state
6203 outputDesc->setDevices(prevDevices);
6204 return muteWaitMs;
6205 }
6206
Eric Laurente552edb2014-03-10 17:42:56 -07006207 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006208 // the requested device is AUDIO_DEVICE_NONE
6209 // OR the requested device is the same as current device
6210 // AND force is not specified
6211 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006212 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006213 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006214 !force && outputDesc->getPatchHandle() != 0) {
6215 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6216 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006217 return muteWaitMs;
6218 }
6219
François Gaffie11d30102018-11-02 16:09:09 +01006220 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006221
Eric Laurente552edb2014-03-10 17:42:56 -07006222 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006223 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006224 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006225 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006226 PatchBuilder patchBuilder;
6227 patchBuilder.addSource(outputDesc);
6228 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6229 for (const auto &filteredDevice : filteredDevices) {
6230 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006231 }
6232
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006233 // Add half reported latency to delayMs when muteWaitMs is null in order
6234 // to avoid disordered sequence of muting volume and changing devices.
6235 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6236 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006237 }
Eric Laurente552edb2014-03-10 17:42:56 -07006238
6239 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006240 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006241
6242 return muteWaitMs;
6243}
6244
Eric Laurentc75307b2015-03-17 15:29:32 -07006245status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006246 int delayMs,
6247 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006248{
Eric Laurent6a94d692014-05-20 11:18:06 -07006249 ssize_t index;
6250 if (patchHandle) {
6251 index = mAudioPatches.indexOfKey(*patchHandle);
6252 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006253 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006254 }
6255 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006256 return INVALID_OPERATION;
6257 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006258 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006259 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006260 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006261 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006262 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006263 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006264 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006265 return status;
6266}
6267
6268status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006269 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006270 bool force,
6271 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006272{
6273 status_t status = NO_ERROR;
6274
Eric Laurent1f2f2232014-06-02 12:01:23 -07006275 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006276 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6277 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006278
François Gaffie11d30102018-11-02 16:09:09 +01006279 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006280 PatchBuilder patchBuilder;
6281 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006282 // AUDIO_SOURCE_HOTWORD is for internal use only:
6283 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006284 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6285 auto result = usecase;
6286 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6287 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6288 }
6289 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006290 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006291 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006292 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006293 }
6294 }
6295 return status;
6296}
6297
Eric Laurent6a94d692014-05-20 11:18:06 -07006298status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6299 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006300{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006302 ssize_t index;
6303 if (patchHandle) {
6304 index = mAudioPatches.indexOfKey(*patchHandle);
6305 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006306 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006307 }
6308 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006309 return INVALID_OPERATION;
6310 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006311 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006312 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006313 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006314 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006315 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006316 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006317 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006318 return status;
6319}
6320
François Gaffie11d30102018-11-02 16:09:09 +01006321sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006322 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006323 audio_format_t& format,
6324 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006325 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006326{
6327 // Choose an input profile based on the requested capture parameters: select the first available
6328 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006329 //
6330 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6331 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006332
Glenn Kasten730b9262018-03-29 15:01:26 -07006333 sp<IOProfile> firstInexact;
6334 uint32_t updatedSamplingRate = 0;
6335 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6336 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006337 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006338 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006339 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006340 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006341 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006342 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006343 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006344 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006345 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006346 &channelMask /*updatedChannelMask*/,
6347 // FIXME ugly cast
6348 (audio_output_flags_t) flags,
6349 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006350 return profile;
6351 }
François Gaffie11d30102018-11-02 16:09:09 +01006352 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006353 samplingRate,
6354 &updatedSamplingRate,
6355 format,
6356 &updatedFormat,
6357 channelMask,
6358 &updatedChannelMask,
6359 // FIXME ugly cast
6360 (audio_output_flags_t) flags,
6361 false /*exactMatchRequiredForInputFlags*/)) {
6362 firstInexact = profile;
6363 }
6364
Eric Laurente552edb2014-03-10 17:42:56 -07006365 }
6366 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006367 if (firstInexact != nullptr) {
6368 samplingRate = updatedSamplingRate;
6369 format = updatedFormat;
6370 channelMask = updatedChannelMask;
6371 return firstInexact;
6372 }
Eric Laurente552edb2014-03-10 17:42:56 -07006373 return NULL;
6374}
6375
François Gaffieaaac0fd2018-11-22 17:56:39 +01006376float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6377 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006378 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006379 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006380{
jiabin9a3361e2019-10-01 09:38:30 -07006381 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006382
6383 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6384 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6385 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6386 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006387 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6388 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6389 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6390 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006391 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006392
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006393 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006394 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6395 mOutputs.isActive(ringVolumeSrc, 0)) {
6396 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006397 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006398 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006399 }
6400
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006401 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006402 if ((volumeSource != callVolumeSrc && (isInCall() ||
6403 mOutputs.isActiveLocally(callVolumeSrc))) &&
6404 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6405 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6406 volumeSource == alarmVolumeSrc ||
6407 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6408 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6409 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006410 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006411 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006412 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006413 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006414 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006415 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006416 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6417 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6418 // programmatically muted.
6419 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6420 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6421 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006422 bool exemptFromCapping =
6423 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6424 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006425 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6426 volumeSource, volumeDb);
6427 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006428 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6429 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6430 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006431 }
6432 }
Eric Laurente552edb2014-03-10 17:42:56 -07006433 // if a headset is connected, apply the following rules to ring tones and notifications
6434 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006435 // - always attenuate notifications volume by 6dB
6436 // - attenuate ring tones volume by 6dB unless music is not playing and
6437 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006438 // - if music is playing, always limit the volume to current music volume,
6439 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006440 if (!Intersection(deviceTypes,
6441 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6442 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006443 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6444 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006445 ((volumeSource == alarmVolumeSrc ||
6446 volumeSource == ringVolumeSrc) ||
6447 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6448 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6449 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6450 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6451 curves.canBeMuted()) {
6452
Eric Laurente552edb2014-03-10 17:42:56 -07006453 // when the phone is ringing we must consider that music could have been paused just before
6454 // by the music application and behave as if music was active if the last music track was
6455 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006456 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006457 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006458 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006459 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006460 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6461 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006462 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006463 float musicVolDb = computeVolume(musicCurves,
6464 musicVolumeSrc,
6465 musicCurves.getVolumeIndex(musicDevice),
6466 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006467 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6468 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6469 if (volumeDb > minVolDb) {
6470 volumeDb = minVolDb;
6471 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006472 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006473 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6474 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6475 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006476 // on A2DP, also ensure notification volume is not too low compared to media when
6477 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006478 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006479 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006480 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6481 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006482 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6483 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006484 }
6485 }
jiabin9a3361e2019-10-01 09:38:30 -07006486 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006487 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006488 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006489 }
6490 }
6491
François Gaffie43c73442018-11-08 08:21:55 +01006492 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006493}
6494
Eric Laurent3839bc02018-07-10 18:33:34 -07006495int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006496 VolumeSource fromVolumeSource,
6497 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006498{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006499 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006500 return srcIndex;
6501 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006502 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6503 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006504 float minSrc = (float)srcCurves.getVolumeIndexMin();
6505 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6506 float minDst = (float)dstCurves.getVolumeIndexMin();
6507 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006508
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006509 // preserve mute request or correct range
6510 if (srcIndex < minSrc) {
6511 if (srcIndex == 0) {
6512 return 0;
6513 }
6514 srcIndex = minSrc;
6515 } else if (srcIndex > maxSrc) {
6516 srcIndex = maxSrc;
6517 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006518 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6519}
6520
François Gaffieaaac0fd2018-11-22 17:56:39 +01006521status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6522 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006523 int index,
6524 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006525 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006526 int delayMs,
6527 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006528{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006529 // do not change actual attributes volume if the attributes is muted
6530 if (outputDesc->isMuted(volumeSource)) {
6531 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6532 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006533 return NO_ERROR;
6534 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006535 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6536 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6537 bool isVoiceVolSrc = callVolSrc == volumeSource;
6538 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6539
Eric Laurent2517af32020-11-25 15:31:27 +01006540 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006541 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006542 // if sco and call follow same curves, bypass forceUseForComm
6543 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006544 ((isVoiceVolSrc && isScoRequested) ||
6545 (isBtScoVolSrc && !isScoRequested))) {
6546 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6547 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006548 // Do not return an error here as AudioService will always set both voice call
6549 // and bluetooth SCO volumes due to stream aliasing.
6550 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006551 }
jiabin9a3361e2019-10-01 09:38:30 -07006552 if (deviceTypes.empty()) {
6553 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006554 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006555
jiabin9a3361e2019-10-01 09:38:30 -07006556 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6557 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006558 // Force VoIP volume to max for bluetooth SCO device except if muted
6559 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006560 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006561 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006562 }
jiabin9a3361e2019-10-01 09:38:30 -07006563 outputDesc->setVolume(
6564 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006565
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006566 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006567 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006568 // 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 +01006569 if (isVoiceVolSrc) {
6570 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006571 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006572 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006573 }
Eric Laurent18fba842016-03-31 14:41:26 -07006574 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006575 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6576 mLastVoiceVolume = voiceVolume;
6577 }
6578 }
Eric Laurente552edb2014-03-10 17:42:56 -07006579 return NO_ERROR;
6580}
6581
Eric Laurentc75307b2015-03-17 15:29:32 -07006582void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006583 const DeviceTypeSet& deviceTypes,
6584 int delayMs,
6585 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006586{
jiabincd510522020-01-22 09:40:55 -08006587 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006588 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6589 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6590 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006591 curves.getVolumeIndex(deviceTypes),
6592 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006593 }
6594}
6595
François Gaffiec005e562018-11-06 15:04:49 +01006596void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6597 bool on,
6598 const sp<AudioOutputDescriptor>& outputDesc,
6599 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006600 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006601{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006602 std::vector<VolumeSource> sourcesToMute;
6603 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6604 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6605 toString(attributes).c_str(), on, outputDesc->getId());
6606 VolumeSource source = toVolumeSource(attributes);
6607 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6608 sourcesToMute.push_back(source);
6609 }
Eric Laurente552edb2014-03-10 17:42:56 -07006610 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006611 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006612 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006613 }
6614
Eric Laurente552edb2014-03-10 17:42:56 -07006615}
6616
François Gaffieaaac0fd2018-11-22 17:56:39 +01006617void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6618 bool on,
6619 const sp<AudioOutputDescriptor>& outputDesc,
6620 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006621 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006622{
jiabin9a3361e2019-10-01 09:38:30 -07006623 if (deviceTypes.empty()) {
6624 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006625 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006626 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006627 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006628 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006629 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006630 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6631 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6632 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006633 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006634 }
6635 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006636 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6637 // ignored
6638 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006639 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006640 if (!outputDesc->isMuted(volumeSource)) {
6641 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006642 return;
6643 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006644 if (outputDesc->decMuteCount(volumeSource) == 0) {
6645 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006646 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006647 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006648 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006649 delayMs);
6650 }
6651 }
6652}
6653
François Gaffie53615e22015-03-19 09:24:12 +01006654bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6655{
François Gaffiec005e562018-11-06 15:04:49 +01006656 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006657 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6658 return true;
6659 }
6660
6661 // has known usage?
6662 switch (paa->usage) {
6663 case AUDIO_USAGE_UNKNOWN:
6664 case AUDIO_USAGE_MEDIA:
6665 case AUDIO_USAGE_VOICE_COMMUNICATION:
6666 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6667 case AUDIO_USAGE_ALARM:
6668 case AUDIO_USAGE_NOTIFICATION:
6669 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6670 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6671 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6672 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6673 case AUDIO_USAGE_NOTIFICATION_EVENT:
6674 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6675 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6676 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6677 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006678 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006679 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006680 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006681 case AUDIO_USAGE_EMERGENCY:
6682 case AUDIO_USAGE_SAFETY:
6683 case AUDIO_USAGE_VEHICLE_STATUS:
6684 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006685 break;
6686 default:
6687 return false;
6688 }
6689 return true;
6690}
6691
François Gaffie2110e042015-03-24 08:41:51 +01006692audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6693{
6694 return mEngine->getForceUse(usage);
6695}
6696
6697bool AudioPolicyManager::isInCall()
6698{
6699 return isStateInCall(mEngine->getPhoneState());
6700}
6701
6702bool AudioPolicyManager::isStateInCall(int state)
6703{
6704 return is_state_in_call(state);
6705}
6706
Eric Laurent74b71512019-11-06 17:21:57 -08006707bool AudioPolicyManager::isCallAudioAccessible()
6708{
6709 audio_mode_t mode = mEngine->getPhoneState();
6710 return (mode == AUDIO_MODE_IN_CALL)
6711 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6712 || (mode == AUDIO_MODE_CALL_SCREEN);
6713}
6714
Eric Laurentd60560a2015-04-10 11:31:20 -07006715void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6716{
6717 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006718 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006719 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006720 sourceDesc->sinkDevice()->equals(deviceDesc))
6721 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006722 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006723 }
6724 }
6725
6726 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6728 bool release = false;
6729 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6730 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6731 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6732 source->ext.device.type == deviceDesc->type()) {
6733 release = true;
6734 }
6735 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006736 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006737 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6738 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6739 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006740 sink->ext.device.type == deviceDesc->type() &&
6741 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6742 || strncmp(sink->ext.device.address, address,
6743 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006744 release = true;
6745 }
6746 }
6747 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006748 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6749 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006750 }
6751 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006752
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006753 mInputs.clearSessionRoutesForDevice(deviceDesc);
6754
Francois Gaffie716e1432019-01-14 16:58:59 +01006755 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006756}
6757
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006758void AudioPolicyManager::modifySurroundFormats(
6759 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006760 std::unordered_set<audio_format_t> enforcedSurround(
6761 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006762 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6763 for (const auto& pair : mConfig.getSurroundFormats()) {
6764 allSurround.insert(pair.first);
6765 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6766 }
Phil Burk09bc4612016-02-24 15:58:15 -08006767
6768 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6769 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006770 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006771 // This is the resulting set of formats depending on the surround mode:
6772 // 'all surround' = allSurround
6773 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6774 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6775 // 'manual surround' = mManualSurroundFormats
6776 // AUTO: formats v 'enforced surround'
6777 // ALWAYS: formats v 'all surround' v 'enforced surround'
6778 // NEVER: formats ^ 'non-surround'
6779 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006780
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006781 std::unordered_set<audio_format_t> formatSet;
6782 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6783 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006784 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006785 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006786 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006787 formatSet.insert(*formatIter);
6788 }
6789 }
6790 } else {
6791 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6792 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006793 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006794
jiabin81772902018-04-02 17:52:27 -07006795 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006796 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006797 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6798 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6799 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006800 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006801 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6802 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6803 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006804 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006805 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006806 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006807 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006808 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006809 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006810}
6811
jiabin06e4bab2019-07-29 10:13:34 -07006812void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6813 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006814 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6815 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6816
6817 // If NEVER, then remove support for channelMasks > stereo.
6818 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006819 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6820 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006821 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006822 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006823 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006824 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006825 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006826 }
6827 }
jiabin81772902018-04-02 17:52:27 -07006828 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6829 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6830 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006831 bool supports5dot1 = false;
6832 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006833 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006834 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6835 supports5dot1 = true;
6836 break;
6837 }
6838 }
6839 // If not then add 5.1 support.
6840 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006841 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006842 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006843 }
Phil Burk09bc4612016-02-24 15:58:15 -08006844 }
6845}
6846
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006847void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006848 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006849 AudioProfileVector &profiles)
6850{
6851 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006852 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006853
François Gaffie112b0af2015-11-19 16:13:25 +01006854 // Format MUST be checked first to update the list of AudioProfile
6855 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006856 reply = mpClientInterface->getParameters(
6857 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006858 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006859 AudioParameter repliedParameters(reply);
6860 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006861 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006862 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6863 return;
6864 }
Phil Burk09bc4612016-02-24 15:58:15 -08006865 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006866 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006867 if (device == AUDIO_DEVICE_OUT_HDMI
6868 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006869 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006870 }
jiabin3e277cc2019-09-10 14:27:34 -07006871 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006872 }
François Gaffie112b0af2015-11-19 16:13:25 +01006873
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006874 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006875 ChannelMaskSet channelMasks;
6876 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006877 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006878 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006879
6880 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006881 reply = mpClientInterface->getParameters(
6882 ioHandle,
6883 requestedParameters.toString() + ";" +
6884 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006885 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006886 AudioParameter repliedParameters(reply);
6887 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006888 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006889 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006890 }
6891 }
6892 if (profiles.hasDynamicChannelsFor(format)) {
6893 reply = mpClientInterface->getParameters(ioHandle,
6894 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006895 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006896 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006897 AudioParameter repliedParameters(reply);
6898 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006899 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006900 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006901 if (device == AUDIO_DEVICE_OUT_HDMI
6902 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006903 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006904 }
François Gaffie112b0af2015-11-19 16:13:25 +01006905 }
6906 }
jiabin3e277cc2019-09-10 14:27:34 -07006907 addDynamicAudioProfileAndSort(
6908 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006909 }
6910}
Eric Laurentd60560a2015-04-10 11:31:20 -07006911
Mikhail Naganovdc769682018-05-04 15:34:08 -07006912status_t AudioPolicyManager::installPatch(const char *caller,
6913 audio_patch_handle_t *patchHandle,
6914 AudioIODescriptorInterface *ioDescriptor,
6915 const struct audio_patch *patch,
6916 int delayMs)
6917{
6918 ssize_t index = mAudioPatches.indexOfKey(
6919 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6920 *patchHandle : ioDescriptor->getPatchHandle());
6921 sp<AudioPatch> patchDesc;
6922 status_t status = installPatch(
6923 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6924 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006925 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006926 }
6927 return status;
6928}
6929
6930status_t AudioPolicyManager::installPatch(const char *caller,
6931 ssize_t index,
6932 audio_patch_handle_t *patchHandle,
6933 const struct audio_patch *patch,
6934 int delayMs,
6935 uid_t uid,
6936 sp<AudioPatch> *patchDescPtr)
6937{
6938 sp<AudioPatch> patchDesc;
6939 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6940 if (index >= 0) {
6941 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006942 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006943 }
6944
6945 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6946 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6947 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6948 if (status == NO_ERROR) {
6949 if (index < 0) {
6950 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006951 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006952 } else {
6953 patchDesc->mPatch = *patch;
6954 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006955 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006956 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006957 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006958 }
6959 nextAudioPortGeneration();
6960 mpClientInterface->onAudioPatchListUpdate();
6961 }
6962 if (patchDescPtr) *patchDescPtr = patchDesc;
6963 return status;
6964}
6965
jiabinbce0c1d2020-10-05 11:20:18 -07006966bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6967{
6968 const TrackClientVector activeClients = output->getActiveClients();
6969 if (activeClients.empty()) {
6970 return true;
6971 }
6972 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6973 if (index < 0) {
6974 ALOGE("%s, no audio patch found while there are active clients on output %d",
6975 __func__, output->getId());
6976 return false;
6977 }
6978 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6979 DeviceVector routedDevices;
6980 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6981 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6982 patchDesc->mPatch.sinks[i].id);
6983 if (device == nullptr) {
6984 ALOGE("%s, no audio device found with id(%d)",
6985 __func__, patchDesc->mPatch.sinks[i].id);
6986 return false;
6987 }
6988 routedDevices.add(device);
6989 }
6990 for (const auto& client : activeClients) {
6991 // TODO: b/175343099 only travel the valid client
6992 sp<DeviceDescriptor> preferredDevice =
6993 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6994 if (mEngine->getOutputDevicesForAttributes(
6995 client->attributes(), preferredDevice, false) == routedDevices) {
6996 return false;
6997 }
6998 }
6999 return true;
7000}
7001
7002sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7003 const sp<IOProfile>& profile, const DeviceVector& devices)
7004{
7005 for (const auto& device : devices) {
7006 // TODO: This should be checking if the profile supports the device combo.
7007 if (!profile->supportsDevice(device)) {
7008 return nullptr;
7009 }
7010 }
7011 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7012 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
7013 status_t status = desc->open(nullptr, devices,
7014 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7015 if (status != NO_ERROR) {
7016 return nullptr;
7017 }
7018
7019 // Here is where the out_set_parameters() for card & device gets called
7020 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7021 const audio_devices_t deviceType = device->type();
7022 const String8 &address = String8(device->address().c_str());
7023 if (!address.isEmpty()) {
7024 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7025 mpClientInterface->setParameters(output, String8(param));
7026 free(param);
7027 }
7028 updateAudioProfiles(device, output, profile->getAudioProfiles());
7029 if (!profile->hasValidAudioProfile()) {
7030 ALOGW("%s() missing param", __func__);
7031 desc->close();
7032 return nullptr;
7033 } else if (profile->hasDynamicAudioProfile()) {
7034 desc->close();
7035 output = AUDIO_IO_HANDLE_NONE;
7036 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7037 profile->pickAudioProfile(
7038 config.sample_rate, config.channel_mask, config.format);
7039 config.offload_info.sample_rate = config.sample_rate;
7040 config.offload_info.channel_mask = config.channel_mask;
7041 config.offload_info.format = config.format;
7042
7043 status = desc->open(&config, devices,
7044 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7045 if (status != NO_ERROR) {
7046 return nullptr;
7047 }
7048 }
7049
7050 addOutput(output, desc);
7051 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7052 sp<AudioPolicyMix> policyMix;
7053 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7054 policyMix->setOutput(desc);
7055 desc->mPolicyMix = policyMix;
7056 } else {
7057 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7058 address.string());
7059 }
7060
7061 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7062 // no duplicated output for direct outputs and
7063 // outputs used by dynamic policy mixes
7064 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7065
7066 //TODO: configure audio effect output stage here
7067
7068 // open a duplicating output thread for the new output and the primary output
7069 sp<SwAudioOutputDescriptor> dupOutputDesc =
7070 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7071 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7072 if (status == NO_ERROR) {
7073 // add duplicated output descriptor
7074 addOutput(duplicatedOutput, dupOutputDesc);
7075 } else {
7076 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7077 mPrimaryOutput->mIoHandle, output);
7078 desc->close();
7079 removeOutput(output);
7080 nextAudioPortGeneration();
7081 return nullptr;
7082 }
7083 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007084 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7085 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7086 mPrimaryOutput = desc;
7087 }
jiabinbce0c1d2020-10-05 11:20:18 -07007088 return desc;
7089}
7090
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007091} // namespace android