blob: 0b63d334d9718e996963b803701dcbd0dab0060c [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>
jiabin10a03f12021-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 Ganov3e5f14f2021-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
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200249 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
250 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200251 (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
Pattydd807582021-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{
Pattydd807582021-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 }
Pattydd807582021-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(
Pattydd807582021-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 Laurentfa0f6742021-08-17 18:39:44 +0200943sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200944 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200945{
946 for (const auto& hwModule : mHwModules) {
947 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200948 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200949 continue;
950 }
951 // reject profiles not corresponding to a device currently available
952 DeviceVector supportedDevices = curProfile->getSupportedDevices();
953 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
954 continue;
955 }
956 if (!devices.empty()) {
957 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
958 != devices.size()) {
959 continue;
960 }
961 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200962 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
963 return curProfile;
964 }
965 }
966 return nullptr;
967}
968
Eric Laurentf4e63452017-11-06 19:31:46 +0000969audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700970{
François Gaffiec005e562018-11-06 15:04:49 +0100971 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800972
973 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
974 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
975 // format, flags, etc. This may result in some discrepancy for functions that utilize
976 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
977 // and AudioSystem::getOutputSamplingRate().
978
François Gaffie11d30102018-11-02 16:09:09 +0100979 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700980 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700981
François Gaffie11d30102018-11-02 16:09:09 +0100982 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
983 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000984 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700985}
986
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700987status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
988 const audio_attributes_t *srcAttr,
989 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700990{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700991 if (srcAttr != NULL) {
992 if (!isValidAttributes(srcAttr)) {
993 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
994 __func__,
995 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
996 srcAttr->tags);
997 return BAD_VALUE;
998 }
999 *dstAttr = *srcAttr;
1000 } else {
1001 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1002 ALOGE("%s: invalid stream type", __func__);
1003 return BAD_VALUE;
1004 }
François Gaffiec005e562018-11-06 15:04:49 +01001005 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001006 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001007
1008 // Only honor audibility enforced when required. The client will be
1009 // forced to reconnect if the forced usage changes.
1010 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001011 dstAttr->flags = static_cast<audio_flags_mask_t>(
1012 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001013 }
1014
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001015 return NO_ERROR;
1016}
1017
Kevin Rocard153f92d2018-12-18 18:33:28 -08001018status_t AudioPolicyManager::getOutputForAttrInt(
1019 audio_attributes_t *resultAttr,
1020 audio_io_handle_t *output,
1021 audio_session_t session,
1022 const audio_attributes_t *attr,
1023 audio_stream_type_t *stream,
1024 uid_t uid,
1025 const audio_config_t *config,
1026 audio_output_flags_t *flags,
1027 audio_port_handle_t *selectedDeviceId,
1028 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001029 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001030 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001031{
François Gaffiec005e562018-11-06 15:04:49 +01001032 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001033 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001034 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001035 const sp<DeviceDescriptor> requestedDevice =
1036 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1037
Eric Laurent8a1095a2019-11-08 14:44:16 -08001038 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001039 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1040 if (status != NO_ERROR) {
1041 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001042 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001043 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001044 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001045 }
François Gaffiec005e562018-11-06 15:04:49 +01001046 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001047
François Gaffiec005e562018-11-06 15:04:49 +01001048 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1049 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001050
Kevin Rocard153f92d2018-12-18 18:33:28 -08001051 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1052 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1053 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001054 sp<AudioPolicyMix> primaryMix;
1055 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001056 if (status != OK) {
1057 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001058 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001059
Kevin Rocard153f92d2018-12-18 18:33:28 -08001060 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001061 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001062
1063 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001064 if ((usePrimaryOutputFromPolicyMixes
1065 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001066 && !audio_is_linear_pcm(config->format)) {
1067 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001068 return BAD_VALUE;
1069 }
1070 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001071 sp<DeviceDescriptor> deviceDesc =
1072 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1073 primaryMix->mDeviceAddress,
1074 AUDIO_FORMAT_DEFAULT);
1075 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001076 if (deviceDesc != nullptr
1077 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001078 audio_io_handle_t newOutput;
1079 status = openDirectOutput(
1080 *stream, session, config,
1081 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1082 DeviceVector(deviceDesc), &newOutput);
1083 if (status != NO_ERROR) {
1084 policyDesc = nullptr;
1085 } else {
1086 policyDesc = mOutputs.valueFor(newOutput);
1087 primaryMix->setOutput(policyDesc);
1088 }
1089 }
1090 if (policyDesc != nullptr) {
1091 policyDesc->mPolicyMix = primaryMix;
1092 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001093 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001094
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001095 ALOGV("getOutputForAttr() returns output %d", *output);
1096 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1097 *outputType = API_OUT_MIX_PLAYBACK;
1098 } else {
1099 *outputType = API_OUTPUT_LEGACY;
1100 }
1101 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001102 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001103 }
François Gaffiec005e562018-11-06 15:04:49 +01001104 // Virtual sources must always be dynamicaly or explicitly routed
1105 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1106 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1107 return BAD_VALUE;
1108 }
1109 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1110 // in order to let the choice of the order to future vendor engine
1111 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001112
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001114 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001115 }
1116
Nadav Barb2f18162018-07-18 13:01:53 +03001117 // Set incall music only if device was explicitly set, and fallback to the device which is
1118 // chosen by the engine if not.
1119 // FIXME: provide a more generic approach which is not device specific and move this back
1120 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001121 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001122 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001123 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001124 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001125 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001126 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001127 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001128 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001129 }
1130 }
1131
François Gaffiec005e562018-11-06 15:04:49 +01001132 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1133 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1134 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001135
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001136 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001137 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001138 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001139 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001140 ALOGV("%s() Using MSD devices %s instead of devices %s",
1141 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001142 } else {
1143 *output = AUDIO_IO_HANDLE_NONE;
1144 }
1145 }
1146 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001147 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001148 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001149 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001150 if (*output == AUDIO_IO_HANDLE_NONE) {
1151 return INVALID_OPERATION;
1152 }
Paul McLeanaa981192015-03-21 09:55:15 -07001153
François Gaffiec005e562018-11-06 15:04:49 +01001154 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001155 for (auto &outputDevice : outputDevices) {
1156 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1157 *selectedDeviceId = outputDevice->getId();
1158 break;
1159 }
1160 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001161
Eric Laurent8a1095a2019-11-08 14:44:16 -08001162 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1163 *outputType = API_OUTPUT_TELEPHONY_TX;
1164 } else {
1165 *outputType = API_OUTPUT_LEGACY;
1166 }
1167
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1169
1170 return NO_ERROR;
1171}
1172
1173status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1174 audio_io_handle_t *output,
1175 audio_session_t session,
1176 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001177 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001178 const audio_config_t *config,
1179 audio_output_flags_t *flags,
1180 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001182 std::vector<audio_io_handle_t> *secondaryOutputs,
1183 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001184{
1185 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1186 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1187 return INVALID_OPERATION;
1188 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001189 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001190 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001191 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001192 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001193 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001195 const sp<DeviceDescriptor> requestedDevice =
1196 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1197
1198 // Prevent from storing invalid requested device id in clients
1199 const audio_port_handle_t sanitizedRequestedPortId =
1200 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1201 *selectedDeviceId = sanitizedRequestedPortId;
1202
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001203 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001204 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001205 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001206 if (status != NO_ERROR) {
1207 return status;
1208 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001209 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 if (secondaryOutputs != nullptr) {
1211 for (auto &secondaryMix : secondaryMixes) {
1212 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1213 if (outputDesc != nullptr &&
1214 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1215 secondaryOutputs->push_back(outputDesc->mIoHandle);
1216 weakSecondaryOutputDescs.push_back(outputDesc);
1217 }
1218 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001220
Eric Laurent8fc147b2018-07-22 19:13:55 -07001221 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001222 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001223 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001224 };
jiabin4ef93452019-09-10 14:29:54 -07001225 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001226
Eric Laurentc209fe42020-06-05 18:11:23 -07001227 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001228 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001229 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001230 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001231 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001232 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001233 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001234 std::move(weakSecondaryOutputDescs),
1235 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001236 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001237
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001238 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1239 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001240
Eric Laurente83b55d2014-11-14 10:06:21 -08001241 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001242}
1243
Eric Laurentc529cf62020-04-17 18:19:10 -07001244status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1245 audio_session_t session,
1246 const audio_config_t *config,
1247 audio_output_flags_t flags,
1248 const DeviceVector &devices,
1249 audio_io_handle_t *output) {
1250
1251 *output = AUDIO_IO_HANDLE_NONE;
1252
1253 // skip direct output selection if the request can obviously be attached to a mixed output
1254 // and not explicitly requested
1255 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1256 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1257 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1258 return NAME_NOT_FOUND;
1259 }
1260
1261 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1262 // This prevents creating an offloaded track and tearing it down immediately after start
1263 // when audioflinger detects there is an active non offloadable effect.
1264 // FIXME: We should check the audio session here but we do not have it in this context.
1265 // This may prevent offloading in rare situations where effects are left active by apps
1266 // in the background.
1267 sp<IOProfile> profile;
1268 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1269 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1270 profile = getProfileForOutput(
1271 devices, config->sample_rate, config->format, config->channel_mask,
1272 flags, true /* directOnly */);
1273 }
1274
1275 if (profile == nullptr) {
1276 return NAME_NOT_FOUND;
1277 }
1278
1279 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1280 for (size_t i = 0; i < mOutputs.size(); i++) {
1281 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1282 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1283 // reuse direct output if currently open by the same client
1284 // and configured with same parameters
1285 if ((config->sample_rate == desc->getSamplingRate()) &&
1286 (config->format == desc->getFormat()) &&
1287 (config->channel_mask == desc->getChannelMask()) &&
1288 (session == desc->mDirectClientSession)) {
1289 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001290 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001291 mOutputs.keyAt(i), session);
1292 *output = mOutputs.keyAt(i);
1293 return NO_ERROR;
1294 }
1295 }
1296 }
1297
1298 if (!profile->canOpenNewIo()) {
1299 return NAME_NOT_FOUND;
1300 }
1301
1302 sp<SwAudioOutputDescriptor> outputDesc =
1303 new SwAudioOutputDescriptor(profile, mpClientInterface);
1304
Michael Chan6fb34492020-12-08 15:44:49 +11001305 // An MSD patch may be using the only output stream that can service this request. Release
1306 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001307 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001308
Eric Laurentf1f22e72021-07-13 14:04:14 +02001309 status_t status =
1310 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001311
1312 // only accept an output with the requested parameters
1313 if (status != NO_ERROR ||
1314 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1315 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1316 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1317 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1318 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1319 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1320 config->channel_mask, outputDesc->getChannelMask());
1321 if (*output != AUDIO_IO_HANDLE_NONE) {
1322 outputDesc->close();
1323 }
1324 // fall back to mixer output if possible when the direct output could not be open
1325 if (audio_is_linear_pcm(config->format) &&
1326 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1327 return NAME_NOT_FOUND;
1328 }
1329 *output = AUDIO_IO_HANDLE_NONE;
1330 return BAD_VALUE;
1331 }
1332 outputDesc->mDirectOpenCount = 1;
1333 outputDesc->mDirectClientSession = session;
1334
1335 addOutput(*output, outputDesc);
1336 mPreviousOutputs = mOutputs;
1337 ALOGV("%s returns new direct output %d", __func__, *output);
1338 mpClientInterface->onAudioPortListUpdate();
1339 return NO_ERROR;
1340}
1341
François Gaffie11d30102018-11-02 16:09:09 +01001342audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1343 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001344 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001345 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001346 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001347 audio_output_flags_t *flags,
1348 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001349{
Andy Hungc88b0642018-04-27 15:42:35 -07001350 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001351
jiabine375d412019-02-26 12:54:53 -08001352 // Discard haptic channel mask when forcing muting haptic channels.
1353 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001354 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1355 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001356
Eric Laurente552edb2014-03-10 17:42:56 -07001357 // open a direct output if required by specified parameters
1358 //force direct flag if offload flag is set: offloading implies a direct output stream
1359 // and all common behaviors are driven by checking only the direct flag
1360 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001361 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1362 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001363 }
Nadav Bar766fb022018-01-07 12:18:03 +02001364 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1365 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001366 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001367
1368 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1369
Eric Laurente83b55d2014-11-14 10:06:21 -08001370 // only allow deep buffering for music stream type
1371 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001372 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001373 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001374 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001375 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1376 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001377 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001378 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001379 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001380 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001381 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001382 audio_is_linear_pcm(config->format) &&
1383 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001384 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001385 AUDIO_OUTPUT_FLAG_DIRECT);
1386 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001387 }
Eric Laurente552edb2014-03-10 17:42:56 -07001388
Eric Laurentfa0f6742021-08-17 18:39:44 +02001389 if (mSpatializerOutput != nullptr
1390 && canBeSpatialized(attr, config, devices.toTypeAddrVector())) {
1391 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001392 }
1393
Eric Laurentc529cf62020-04-17 18:19:10 -07001394 audio_config_t directConfig = *config;
1395 directConfig.channel_mask = channelMask;
1396 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1397 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001398 return output;
1399 }
1400
Eric Laurent14cbfca2016-03-17 09:42:16 -07001401 // A request for HW A/V sync cannot fallback to a mixed output because time
1402 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001403 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001404 return AUDIO_IO_HANDLE_NONE;
1405 }
1406
Eric Laurente552edb2014-03-10 17:42:56 -07001407 // ignoring channel mask due to downmix capability in mixer
1408
1409 // open a non direct output
1410
1411 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001412 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001413 // get which output is suitable for the specified stream. The actual
1414 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001415 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001416
Eric Laurent8838a382014-09-08 16:44:28 -07001417 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001418 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001419 output = selectOutput(
1420 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001421 }
François Gaffie11d30102018-11-02 16:09:09 +01001422 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001423 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001424 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001425
Eric Laurente552edb2014-03-10 17:42:56 -07001426 return output;
1427}
1428
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001429sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001430 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1431 mAvailableInputDevices);
1432 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1433}
1434
1435DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1436 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1437 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001438}
1439
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001440const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001442 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1443 if (msdModule != 0) {
1444 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1445 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1446 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1447 const struct audio_port_config *source = &patch->mPatch.sources[j];
1448 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1449 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001450 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001451 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001452 }
1453 }
1454 }
1455 return msdPatches;
1456}
1457
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001458status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1459 const InputProfileCollection &inputProfiles,
1460 const OutputProfileCollection &outputProfiles,
1461 const sp<DeviceDescriptor> &sourceDevice,
1462 const sp<DeviceDescriptor> &sinkDevice,
1463 AudioProfileVector& sourceProfiles,
1464 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001465 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001466 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001467 return NO_INIT;
1468 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001469 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001470 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 return NO_INIT;
1472 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001473 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1475 inProfile->supportsDevice(sourceDevice)) {
1476 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001477 }
1478 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001479 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001480 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001481 outProfile->supportsDevice(sinkDevice)) {
1482 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 }
1484 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001485 return NO_ERROR;
1486}
1487
1488status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1489 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1490 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1491{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001492 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001493 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1494 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1495 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001496 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001497 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1498 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001499 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001500 }
1501 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1502 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1503 sinkConfig->format = bestSinkConfig.format;
1504 // For encoded streams force direct flag to prevent downstream mixing.
1505 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1506 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001507 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1508 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001509 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001510 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1511 // raw and IEC61937 framed streams.
1512 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1513 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1514 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001515 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1516 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1517 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1518 sourceConfig->format = bestSinkConfig.format;
1519 // Copy input stream directly without any processing (e.g. resampling).
1520 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1521 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1522 if (hwAvSync) {
1523 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1524 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1525 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1526 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1527 }
1528 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1529 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1530 sinkConfig->config_mask |= config_mask;
1531 sourceConfig->config_mask |= config_mask;
1532 return NO_ERROR;
1533}
1534
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001535PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1536 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537{
1538 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001539 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1540 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1541 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1542 if (deviceModule == nullptr) {
1543 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1544 return patchBuilder;
1545 }
1546 const InputProfileCollection inputProfiles = msdIsSource ?
1547 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1548 const OutputProfileCollection outputProfiles = msdIsSource ?
1549 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1550
1551 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1552 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1553 device : getMsdAudioOutDevices().itemAt(0);
1554 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1555
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001556 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1557 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001558 AudioProfileVector sourceProfiles;
1559 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1561 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001562 for (auto hwAvSync : { true, false }) {
1563 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1564 sourceProfiles, sinkProfiles) != NO_ERROR) {
1565 continue;
1566 }
1567 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1568 &sinkConfig) == NO_ERROR) {
1569 // Found a matching config. Re-create PatchBuilder with this config.
1570 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1571 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001573 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 " supporting PCM format conversion.", __func__);
1575 return patchBuilder;
1576}
1577
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001578status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001579 DeviceVector devices;
1580 if (outputDevices != nullptr && outputDevices->size() > 0) {
1581 devices.add(*outputDevices);
1582 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001583 // Use media strategy for unspecified output device. This should only
1584 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1585 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001586 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001587 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001588 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001589 }
Michael Chan6fb34492020-12-08 15:44:49 +11001590 std::vector<PatchBuilder> patchesToCreate;
1591 for (auto i = 0u; i < devices.size(); ++i) {
1592 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001593 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001594 }
1595 // Retain only the MSD patches associated with outputDevices request.
1596 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001597 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001598 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1599 auto retainedPatch = false;
1600 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1601 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1602 patchesToRemove.removeItemsAt(i);
1603 retainedPatch = true;
1604 break;
1605 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001606 }
Michael Chan6fb34492020-12-08 15:44:49 +11001607 if (retainedPatch) {
1608 it = patchesToCreate.erase(it);
1609 continue;
1610 }
1611 ++it;
1612 }
1613 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1614 return NO_ERROR;
1615 }
1616 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1617 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001618 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001619 }
Michael Chan6fb34492020-12-08 15:44:49 +11001620 status_t status = NO_ERROR;
1621 for (const auto &p : patchesToCreate) {
1622 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1623 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1624 char message[256];
1625 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1626 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1627 currStatus == NO_ERROR ? "Success" : "Error",
1628 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1629 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1630 if (currStatus == NO_ERROR) {
1631 ALOGD("%s", message);
1632 } else {
1633 ALOGE("%s", message);
1634 if (status == NO_ERROR) {
1635 status = currStatus;
1636 }
1637 }
1638 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001639 return status;
1640}
1641
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001642void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1643 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001644 for (size_t i = 0; i < msdPatches.size(); i++) {
1645 const auto& patch = msdPatches[i];
1646 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1647 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1648 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1649 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1650 releaseAudioPatch(patch->getHandle(), mUidCached);
1651 break;
1652 }
1653 }
1654 }
1655}
1656
Eric Laurente0720872014-03-11 09:30:41 -07001657audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001658 audio_output_flags_t flags,
1659 audio_format_t format,
1660 audio_channel_mask_t channelMask,
1661 uint32_t samplingRate,
1662 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001663{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001664 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1665 "%s called with format %#x", __func__, format);
1666
jiabinebb6af42020-06-09 17:31:17 -07001667 // Return the output that haptic-generating attached to when 1) session id is specified,
1668 // 2) haptic-generating effect exists for given session id and 3) the output that
1669 // haptic-generating effect attached to is in given outputs.
1670 if (sessionId != AUDIO_SESSION_NONE) {
1671 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1672 sessionId, FX_IID_HAPTICGENERATOR);
1673 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1674 return hapticGeneratingOutput;
1675 }
1676 }
1677
Eric Laurent16c66dd2019-05-01 17:54:10 -07001678 // Flags disqualifying an output: the match must happen before calling selectOutput()
1679 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1680 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1681
1682 // Flags expressing a functional request: must be honored in priority over
1683 // other criteria
1684 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1685 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1686 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1687 // Flags expressing a performance request: have lower priority than serving
1688 // requested sampling rate or channel mask
1689 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1690 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1691 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1692
1693 const audio_output_flags_t functionalFlags =
1694 (audio_output_flags_t)(flags & kFunctionalFlags);
1695 const audio_output_flags_t performanceFlags =
1696 (audio_output_flags_t)(flags & kPerformanceFlags);
1697
1698 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1699
Eric Laurente552edb2014-03-10 17:42:56 -07001700 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001701 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001702 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001703 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001704 // 2: the output with the highest number of requested functional flags
1705 // 3: the output supporting the exact channel mask
1706 // 4: the output with a higher channel count than requested
1707 // 5: the output with a higher sampling rate than requested
1708 // 6: the output with the highest number of requested performance flags
1709 // 7: the output with the bit depth the closest to the requested one
1710 // 8: the primary output
1711 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001712
Eric Laurent16c66dd2019-05-01 17:54:10 -07001713 // matching criteria values in priority order for best matching output so far
1714 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurent16c66dd2019-05-01 17:54:10 -07001716 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1717 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1718 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001719
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001720 for (audio_io_handle_t output : outputs) {
1721 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001722 // matching criteria values in priority order for current output
1723 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001724
Eric Laurent16c66dd2019-05-01 17:54:10 -07001725 if (outputDesc->isDuplicated()) {
1726 continue;
1727 }
1728 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1729 continue;
1730 }
Eric Laurent8838a382014-09-08 16:44:28 -07001731
Eric Laurent16c66dd2019-05-01 17:54:10 -07001732 // If haptic channel is specified, use the haptic output if present.
1733 // When using haptic output, same audio format and sample rate are required.
1734 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001735 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001736 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1737 continue;
1738 }
1739 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001740 && format == outputDesc->getFormat()
1741 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001742 currentMatchCriteria[0] = outputHapticChannelCount;
1743 }
1744
1745 // functional flags match
1746 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1747
1748 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001749 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1750 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001751 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1752 channelCount <= outputChannelCount) {
1753 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001754 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1755 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001756 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001757 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001758 currentMatchCriteria[3] = outputChannelCount;
1759 }
1760
1761 // sampling rate match
1762 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001763 samplingRate <= outputDesc->getSamplingRate()) {
1764 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001765 }
1766
1767 // performance flags match
1768 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1769
1770 // format match
1771 if (format != AUDIO_FORMAT_INVALID) {
1772 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001773 PolicyAudioPort::kFormatDistanceMax -
1774 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001775 }
1776
1777 // primary output match
1778 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1779
1780 // compare match criteria by priority then value
1781 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1782 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1783 bestMatchCriteria = currentMatchCriteria;
1784 bestOutput = output;
1785
1786 std::stringstream result;
1787 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1788 std::ostream_iterator<int>(result, " "));
1789 ALOGV("%s new bestOutput %d criteria %s",
1790 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001791 }
1792 }
1793
Eric Laurent16c66dd2019-05-01 17:54:10 -07001794 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001795}
1796
Eric Laurent8fc147b2018-07-22 19:13:55 -07001797status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001798{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001799 ALOGV("%s portId %d", __FUNCTION__, portId);
1800
1801 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1802 if (outputDesc == 0) {
1803 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001804 return BAD_VALUE;
1805 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001806 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001807
Eric Laurent8fc147b2018-07-22 19:13:55 -07001808 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001809 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001810
Eric Laurent733ce942017-12-07 12:18:25 -08001811 status_t status = outputDesc->start();
1812 if (status != NO_ERROR) {
1813 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001814 }
1815
Eric Laurent97ac8712018-07-27 18:59:02 -07001816 uint32_t delayMs;
1817 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001818
1819 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001820 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001821 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001822 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001823 if (delayMs != 0) {
1824 usleep(delayMs * 1000);
1825 }
1826
1827 return status;
1828}
1829
Eric Laurent97ac8712018-07-27 18:59:02 -07001830status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1831 const sp<TrackClientDescriptor>& client,
1832 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001833{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001834 // cannot start playback of STREAM_TTS if any other output is being used
1835 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001836
1837 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001838 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001839 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001840 auto clientStrategy = client->strategy();
1841 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001842 if (stream == AUDIO_STREAM_TTS) {
1843 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001844 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001845 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001846 return INVALID_OPERATION;
1847 } else {
1848 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1849 }
1850 } else {
1851 // some playback other than beacon starts
1852 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1853 }
1854
Eric Laurent77305a62016-07-25 16:39:22 -07001855 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001856 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001857 bool force = !outputDesc->isActive() &&
1858 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001859
François Gaffie11d30102018-11-02 16:09:09 +01001860 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001861 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001862 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001863 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001864 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001865 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001866 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001867 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001868 } else {
1869 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001870 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001871 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1872 AUDIO_FORMAT_DEFAULT);
1873 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1874 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001875 }
1876
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001877 // requiresMuteCheck is false when we can bypass mute strategy.
1878 // It covers a common case when there is no materially active audio
1879 // and muting would result in unnecessary delay and dropped audio.
1880 const uint32_t outputLatencyMs = outputDesc->latency();
1881 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1882
Eric Laurente552edb2014-03-10 17:42:56 -07001883 // increment usage count for this stream on the requested output:
1884 // NOTE that the usage count is the same for duplicated output and hardware output which is
1885 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001886 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001887
1888 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001889 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1890 client->isPreferredDeviceForExclusiveUse()) {
1891 // Preferred device may be exclusive, use only if no other active clients on this output
1892 devices = DeviceVector(
1893 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1894 } else {
1895 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1896 }
François Gaffie11d30102018-11-02 16:09:09 +01001897 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001898 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001899 }
1900 }
Eric Laurente552edb2014-03-10 17:42:56 -07001901
François Gaffiec005e562018-11-06 15:04:49 +01001902 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001903 selectOutputForMusicEffects();
1904 }
1905
François Gaffie1c878552018-11-22 16:53:21 +01001906 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001907 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001908 if (devices.isEmpty()) {
1909 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001910 }
François Gaffiec005e562018-11-06 15:04:49 +01001911 bool shouldWait =
1912 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1913 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1914 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001915 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001916 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001918 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001919 // An output has a shared device if
1920 // - managed by the same hw module
1921 // - supports the currently selected device
1922 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001923 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001924
Eric Laurent77305a62016-07-25 16:39:22 -07001925 // force a device change if any other output is:
1926 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001927 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001928 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001929 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001930 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001931 // change the device currently selected by the other output.
1932 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001933 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001934 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001935 force = true;
1936 }
1937 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001938 // a notification so that audio focus effect can propagate, or that a mute/unmute
1939 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001940 const uint32_t latencyMs = desc->latency();
1941 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1942
1943 if (shouldWait && isActive && (waitMs < latencyMs)) {
1944 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001945 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001946
1947 // Require mute check if another output is on a shared device
1948 // and currently active to have proper drain and avoid pops.
1949 // Note restoring AudioTracks onto this output needs to invoke
1950 // a volume ramp if there is no mute.
1951 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001952 }
1953 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001954
1955 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001956 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001957
Eric Laurente552edb2014-03-10 17:42:56 -07001958 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001959 auto &curves = getVolumeCurves(client->attributes());
1960 checkAndSetVolume(curves, client->volumeSource(),
1961 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001962 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001963 outputDesc->devices().types(), 0 /*delay*/,
1964 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001965
1966 // update the outputs if starting an output with a stream that can affect notification
1967 // routing
1968 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001969
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001970 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001971 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001972 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1973 }
Eric Laurentdc462862016-07-19 12:29:53 -07001974
1975 if (waitMs > muteWaitMs) {
1976 *delayMs = waitMs - muteWaitMs;
1977 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001978
1979 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1980 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1981 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1982 // change occurs after the MixerThread starts and causes a stream volume
1983 // glitch.
1984 //
1985 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001986 }
Eric Laurentdc462862016-07-19 12:29:53 -07001987
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001988 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001989 mEngine->getForceUse(
1990 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001991 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001992 }
1993
Eric Laurent97ac8712018-07-27 18:59:02 -07001994 // Automatically enable the remote submix input when output is started on a re routing mix
1995 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001996 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1997 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001998 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1999 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2000 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002001 "remote-submix",
2002 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002003 }
2004
Eric Laurente552edb2014-03-10 17:42:56 -07002005 return NO_ERROR;
2006}
2007
Eric Laurent8fc147b2018-07-22 19:13:55 -07002008status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002009{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002010 ALOGV("%s portId %d", __FUNCTION__, portId);
2011
2012 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2013 if (outputDesc == 0) {
2014 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002015 return BAD_VALUE;
2016 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002017 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002018
Eric Laurent97ac8712018-07-27 18:59:02 -07002019 ALOGV("stopOutput() output %d, stream %d, session %d",
2020 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002021
Eric Laurent97ac8712018-07-27 18:59:02 -07002022 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002023
Eric Laurent733ce942017-12-07 12:18:25 -08002024 if (status == NO_ERROR ) {
2025 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002026 }
2027 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002028}
2029
Eric Laurent97ac8712018-07-27 18:59:02 -07002030status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2031 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002032{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002033 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002034 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002035 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002036
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002037 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2038
François Gaffie1c878552018-11-22 16:53:21 +01002039 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2040 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002041 // Automatically disable the remote submix input when output is stopped on a
2042 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002043 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002044 if (isSingleDeviceType(
2045 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002046 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002047 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002048 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2049 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002050 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002051 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002052 }
2053 }
2054 bool forceDeviceUpdate = false;
2055 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002056 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002057 forceDeviceUpdate = true;
2058 }
2059
Eric Laurente552edb2014-03-10 17:42:56 -07002060 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002061 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002062
Eric Laurente552edb2014-03-10 17:42:56 -07002063 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002064 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002065 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002066 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002067 // delay the device switch by twice the latency because stopOutput() is executed when
2068 // the track stop() command is received and at that time the audio track buffer can
2069 // still contain data that needs to be drained. The latency only covers the audio HAL
2070 // and kernel buffers. Also the latency does not always include additional delay in the
2071 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002072 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002073
2074 // force restoring the device selection on other active outputs if it differs from the
2075 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002076 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002077 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002078 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002079 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002080 desc->isActive() &&
2081 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002082 (newDevices != desc->devices())) {
2083 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2084 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002085
François Gaffie11d30102018-11-02 16:09:09 +01002086 setOutputDevices(desc, newDevices2, force, delayMs);
2087
Eric Laurent57de36c2016-09-28 16:59:11 -07002088 // re-apply device specific volume if not done by setOutputDevice()
2089 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002090 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002091 }
Eric Laurente552edb2014-03-10 17:42:56 -07002092 }
2093 }
2094 // update the outputs if stopping one with a stream that can affect notification routing
2095 handleNotificationRoutingForStream(stream);
2096 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002097
2098 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2099 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002100 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002101 }
2102
François Gaffiec005e562018-11-06 15:04:49 +01002103 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002104 selectOutputForMusicEffects();
2105 }
Eric Laurente552edb2014-03-10 17:42:56 -07002106 return NO_ERROR;
2107 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002108 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002109 return INVALID_OPERATION;
2110 }
2111}
2112
jiabinbce0c1d2020-10-05 11:20:18 -07002113bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002114{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002115 ALOGV("%s portId %d", __FUNCTION__, portId);
2116
2117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2118 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002119 // If an output descriptor is closed due to a device routing change,
2120 // then there are race conditions with releaseOutput from tracks
2121 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2122 // destroyed shortly thereafter.
2123 //
2124 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002125 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002126 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002127 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002128
2129 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302131 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2132 if (outputDesc->isClientActive(client)) {
2133 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2134 stopOutput(portId);
2135 }
2136
Eric Laurent8fc147b2018-07-22 19:13:55 -07002137 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2138 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002139 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002140 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002141 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002142 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143 if (--outputDesc->mDirectOpenCount == 0) {
2144 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002145 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002146 }
2147 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302148
Andy Hung39efb7a2018-09-26 15:39:28 -07002149 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002150 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2151 // The output is pending reopened to query dynamic profiles and
2152 // there is no active clients
2153 closeOutput(outputDesc->mIoHandle);
2154 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2155 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2156 if (newOutputDesc == nullptr) {
2157 ALOGE("%s failed to open output", __func__);
2158 }
2159 return true;
2160 }
2161 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002162}
2163
Eric Laurentcaf7f482014-11-25 17:50:47 -08002164status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2165 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002166 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002167 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002168 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002169 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002170 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002171 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002172 input_type_t *inputType,
2173 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002174{
François Gaffiec005e562018-11-06 15:04:49 +01002175 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002176 "flags %#x attributes=%s requested device ID %d",
2177 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2178 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002179
Eric Laurentad2e7b92017-09-14 20:06:42 -07002180 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002181 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002182 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002183 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002184 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002185 sp<AudioInputDescriptor> inputDesc;
2186 sp<RecordClientDescriptor> clientDesc;
2187 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002188 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002189 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002190
2191 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2192 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2193 return INVALID_OPERATION;
2194 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002195
Francois Gaffie716e1432019-01-14 16:58:59 +01002196 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2197 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002198 }
2199
Paul McLean466dc8e2015-04-17 13:15:36 -06002200 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002201 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002202 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002203
Eric Laurentad2e7b92017-09-14 20:06:42 -07002204 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2205 // possible
2206 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2207 *input != AUDIO_IO_HANDLE_NONE) {
2208 ssize_t index = mInputs.indexOfKey(*input);
2209 if (index < 0) {
2210 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2211 status = BAD_VALUE;
2212 goto error;
2213 }
2214 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002215 RecordClientVector clients = inputDesc->getClientsForSession(session);
2216 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002217 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2218 status = BAD_VALUE;
2219 goto error;
2220 }
2221 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2222 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002223 // corresponds to a new client and is only permitted from the same UID.
2224 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002225 if (clients.size() > 1) {
2226 for (const auto& client : clients) {
2227 // The client map is ordered by key values (portId) and portIds are allocated
2228 // incrementaly. So the first client in this list is the one opened by audio flinger
2229 // when the mmap stream is created and should be ignored as it does not correspond
2230 // to an actual client
2231 if (client == *clients.cbegin()) {
2232 continue;
2233 }
2234 if (uid != client->uid() && !client->isSilenced()) {
2235 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2236 uid, client->portId(), client->uid());
2237 status = INVALID_OPERATION;
2238 goto error;
2239 }
Eric Laurent331679c2018-04-16 17:03:16 -07002240 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002241 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002242 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002243 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002244
Eric Laurentfecbceb2021-02-09 14:46:43 +01002245 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002246 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002247 }
2248
2249 *input = AUDIO_IO_HANDLE_NONE;
2250 *inputType = API_INPUT_INVALID;
2251
Francois Gaffie716e1432019-01-14 16:58:59 +01002252 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002253
Francois Gaffie716e1432019-01-14 16:58:59 +01002254 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2255 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2256 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002257 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002258 ALOGW("%s could not find input mix for attr %s",
2259 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002260 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002261 }
jiabinc1de2df2019-05-07 14:26:40 -07002262 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2263 String8(attr->tags + strlen("addr=")),
2264 AUDIO_FORMAT_DEFAULT);
2265 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002266 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002267 __func__, attributes.source, attributes.tags);
2268 status = BAD_VALUE;
2269 goto error;
2270 }
2271
Kevin Rocard25f9b052019-02-27 15:08:54 -08002272 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2273 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2274 } else {
2275 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2276 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002277 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002278 if (explicitRoutingDevice != nullptr) {
2279 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002281 // Prevent from storing invalid requested device id in clients
2282 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002283 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002284 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2285 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 }
François Gaffie11d30102018-11-02 16:09:09 +01002287 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002288 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002289 status = BAD_VALUE;
2290 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002291 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002292 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2293 *inputType = API_INPUT_MIX_CAPTURE;
2294 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002295 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2296 // there is an external policy, but this input is attached to a mix of recorders,
2297 // meaning it receives audio injected into the framework, so the recorder doesn't
2298 // know about it and is therefore considered "legacy"
2299 *inputType = API_INPUT_LEGACY;
2300 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002301 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002302 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002303 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002304 } else {
2305 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002306 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002307
Eric Laurent599c7582015-12-07 18:05:55 -08002308 }
2309
François Gaffiec005e562018-11-06 15:04:49 +01002310 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002311 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002312 status = INVALID_OPERATION;
2313 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002314 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002315
Eric Laurent8f42ea12018-08-08 09:08:25 -07002316exit:
2317
François Gaffiec005e562018-11-06 15:04:49 +01002318 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2319 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002320
Francois Gaffie716e1432019-01-14 16:58:59 +01002321 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002322 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002323 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002324
Mikhail Naganov2996f672019-04-18 12:29:59 -07002325 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002326 requestedDeviceId, attributes.source, flags,
2327 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002328 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002329 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002330
2331 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2332 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002333
Eric Laurent599c7582015-12-07 18:05:55 -08002334 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002335
2336error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002337 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002338}
2339
2340
François Gaffie11d30102018-11-02 16:09:09 +01002341audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002342 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002343 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002344 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002345 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002346 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002347{
2348 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002349 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002350 bool isSoundTrigger = false;
2351
François Gaffiec005e562018-11-06 15:04:49 +01002352 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002353 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2354 if (index >= 0) {
2355 input = mSoundTriggerSessions.valueFor(session);
2356 isSoundTrigger = true;
2357 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2358 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2359 } else {
2360 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002361 }
François Gaffiec005e562018-11-06 15:04:49 +01002362 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002363 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002364 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002365 }
2366
Andy Hungf129b032015-04-07 13:45:50 -07002367 // find a compatible input profile (not necessarily identical in parameters)
2368 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002369 // sampling rate and flags may be updated by getInputProfile
2370 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2371 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002372 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002373 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002374 audio_input_flags_t profileFlags = flags;
2375 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002376 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002377 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002378 profileFlags);
2379 if (profile != 0) {
2380 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002381 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2382 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002383 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2384 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2385 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002386 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002387 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002388 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002389 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002390 }
Eric Laurente552edb2014-03-10 17:42:56 -07002391 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002392 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002393 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002394 if (samplingRate == 0) {
2395 samplingRate = profileSamplingRate;
2396 }
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurent322b4d22015-04-03 15:57:54 -07002398 if (profile->getModuleHandle() == 0) {
2399 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002400 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002401 }
2402
Eric Laurentec376dc2021-04-08 20:41:22 +02002403 // Reuse an already opened input if a client with the same session ID already exists
2404 // on that input
2405 for (size_t i = 0; i < mInputs.size(); i++) {
2406 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2407 if (desc->mProfile != profile) {
2408 continue;
2409 }
2410 RecordClientVector clients = desc->clientsList();
2411 for (const auto &client : clients) {
2412 if (session == client->session()) {
2413 return desc->mIoHandle;
2414 }
2415 }
2416 }
2417
Eric Laurent3974e3b2017-12-07 17:58:43 -08002418 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002419 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002420 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002421 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002422 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002423 continue;
2424 }
2425 // if sound trigger, reuse input if used by other sound trigger on same session
2426 // else
2427 // reuse input if active client app is not in IDLE state
2428 //
2429 RecordClientVector clients = desc->clientsList();
2430 bool doClose = false;
2431 for (const auto& client : clients) {
2432 if (isSoundTrigger != client->isSoundTrigger()) {
2433 continue;
2434 }
2435 if (client->isSoundTrigger()) {
2436 if (session == client->session()) {
2437 return desc->mIoHandle;
2438 }
2439 continue;
2440 }
2441 if (client->active() && client->appState() != APP_STATE_IDLE) {
2442 return desc->mIoHandle;
2443 }
2444 doClose = true;
2445 }
2446 if (doClose) {
2447 closeInput(desc->mIoHandle);
2448 } else {
2449 i++;
2450 }
2451 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002452 }
2453
Eric Laurentfe231122017-11-17 17:48:06 -08002454 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002455
Eric Laurentfe231122017-11-17 17:48:06 -08002456 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2457 lConfig.sample_rate = profileSamplingRate;
2458 lConfig.channel_mask = profileChannelMask;
2459 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002460
François Gaffie11d30102018-11-02 16:09:09 +01002461 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002462
2463 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002464 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002465 (profileSamplingRate != lConfig.sample_rate) ||
2466 !audio_formats_match(profileFormat, lConfig.format) ||
2467 (profileChannelMask != lConfig.channel_mask)) {
2468 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002469 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002470 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002471 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002472 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002473 }
Eric Laurent599c7582015-12-07 18:05:55 -08002474 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002475 }
2476
Eric Laurentc722f302014-12-10 11:21:49 -08002477 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002478
Eric Laurent599c7582015-12-07 18:05:55 -08002479 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002480 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002481
Eric Laurent599c7582015-12-07 18:05:55 -08002482 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002483}
2484
Eric Laurent4eb58f12018-12-07 16:41:02 -08002485status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002486{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002487 ALOGV("%s portId %d", __FUNCTION__, portId);
2488
2489 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2490 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002491 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002492 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002493 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002494 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002495 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002496 if (client->active()) {
2497 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2498 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002499 }
2500
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 audio_session_t session = client->session();
2502
Eric Laurent4eb58f12018-12-07 16:41:02 -08002503 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002504
Eric Laurent4eb58f12018-12-07 16:41:02 -08002505 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002506
Eric Laurent4eb58f12018-12-07 16:41:02 -08002507 status_t status = inputDesc->start();
2508 if (status != NO_ERROR) {
2509 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002510 }
Eric Laurente552edb2014-03-10 17:42:56 -07002511
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002512 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002513 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002515
Eric Laurent8f42ea12018-08-08 09:08:25 -07002516 // indicate active capture to sound trigger service if starting capture from a mic on
2517 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002518 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002519 if (device != nullptr) {
2520 status = setInputDevice(input, device, true /* force */);
2521 } else {
2522 ALOGW("%s no new input device can be found for descriptor %d",
2523 __FUNCTION__, inputDesc->getId());
2524 status = BAD_VALUE;
2525 }
Eric Laurente552edb2014-03-10 17:42:56 -07002526
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002527 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002528 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002529 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002530 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002531 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2532 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002533 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002534 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002535
François Gaffie11d30102018-11-02 16:09:09 +01002536 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2537 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002538 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002539 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002540 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002541
Eric Laurent8f42ea12018-08-08 09:08:25 -07002542 // automatically enable the remote submix output when input is started if not
2543 // used by a policy mix of type MIX_TYPE_RECORDERS
2544 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002545 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002546 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002547 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002548 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002549 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2550 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002551 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552 if (address != "") {
2553 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2554 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002555 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002556 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002557 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002558 } else if (status != NO_ERROR) {
2559 // Restore client activity state.
2560 inputDesc->setClientActive(client, false);
2561 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002562 }
2563
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002564 ALOGV("%s input %d source = %d status = %d exit",
2565 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002566
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002567 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002568}
2569
Eric Laurent8fc147b2018-07-22 19:13:55 -07002570status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002571{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002572 ALOGV("%s portId %d", __FUNCTION__, portId);
2573
2574 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2575 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002576 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002577 return BAD_VALUE;
2578 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002579 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002580 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002581 if (!client->active()) {
2582 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002583 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002584 }
Carter Hsue6139d52021-07-08 10:30:20 +08002585 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002587
Eric Laurent8f42ea12018-08-08 09:08:25 -07002588 inputDesc->stop();
2589 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002590 auto current_source = inputDesc->source();
2591 setInputDevice(input, getNewInputDevice(inputDesc),
2592 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002594 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002595 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002596 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002597 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2598 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002600 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601
2602 // automatically disable the remote submix output when input is stopped if not
2603 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002604 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002606 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002607 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002608 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2609 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002610 }
2611 if (address != "") {
2612 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2613 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002614 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002615 }
2616 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002617 resetInputDevice(input);
2618
2619 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2620 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002621 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2622 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002623 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002624 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625 }
2626 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002627 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002628 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002629}
2630
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002632{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002633 ALOGV("%s portId %d", __FUNCTION__, portId);
2634
2635 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2636 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002637 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002638 return;
2639 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002640 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002641 audio_io_handle_t input = inputDesc->mIoHandle;
2642
Eric Laurent8f42ea12018-08-08 09:08:25 -07002643 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002644
Andy Hung39efb7a2018-09-26 15:39:28 -07002645 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002646
Andy Hung39efb7a2018-09-26 15:39:28 -07002647 if (inputDesc->getClientCount() > 0) {
2648 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002649 return;
2650 }
2651
Eric Laurent05b90f82014-08-27 15:32:29 -07002652 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002653 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002654 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002655}
2656
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002658{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002660
2661 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002662 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 }
2664}
2665
Eric Laurent8f42ea12018-08-08 09:08:25 -07002666void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2667{
2668 stopInput(portId);
2669 releaseInput(portId);
2670}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002671
Eric Laurent0dd51852019-04-19 18:18:58 -07002672void AudioPolicyManager::checkCloseInputs() {
2673 // After connecting or disconnecting an input device, close input if:
2674 // - it has no client (was just opened to check profile) OR
2675 // - none of its supported devices are connected anymore OR
2676 // - one of its clients cannot be routed to one of its supported
2677 // devices anymore. Otherwise update device selection
2678 std::vector<audio_io_handle_t> inputsToClose;
2679 for (size_t i = 0; i < mInputs.size(); i++) {
2680 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2681 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002682 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002683 inputsToClose.push_back(mInputs.keyAt(i));
2684 } else {
2685 bool close = false;
2686 for (const auto& client : input->clientsList()) {
2687 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002688 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002689 if (!input->supportedDevices().contains(device)) {
2690 close = true;
2691 break;
2692 }
2693 }
2694 if (close) {
2695 inputsToClose.push_back(mInputs.keyAt(i));
2696 } else {
2697 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2698 }
2699 }
2700 }
2701
2702 for (const audio_io_handle_t handle : inputsToClose) {
2703 ALOGV("%s closing input %d", __func__, handle);
2704 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002705 }
Eric Laurentd4692962014-05-05 18:13:44 -07002706}
2707
François Gaffie251c7f02018-11-07 10:41:08 +01002708void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002709{
2710 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002711 if (indexMin < 0 || indexMax < 0) {
2712 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2713 return;
2714 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002715 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002716
2717 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002718 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2719 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002720 continue;
2721 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002722 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002723 }
Eric Laurente552edb2014-03-10 17:42:56 -07002724}
2725
Eric Laurente0720872014-03-11 09:30:41 -07002726status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002727 int index,
2728 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002729{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002730 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002731 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2732 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2733 return NO_ERROR;
2734 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002735 ALOGV("%s: stream %s attributes=%s", __func__,
2736 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002737 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002738}
2739
Eric Laurente0720872014-03-11 09:30:41 -07002740status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002741 int *index,
2742 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002743{
François Gaffiec005e562018-11-06 15:04:49 +01002744 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2745 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002746 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002747 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002748 deviceTypes = mEngine->getOutputDevicesForStream(
2749 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002750 }
jiabin9a3361e2019-10-01 09:38:30 -07002751 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002752}
2753
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002754status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002755 int index,
2756 audio_devices_t device)
2757{
2758 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002759 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2760 if (group == VOLUME_GROUP_NONE) {
2761 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002762 return BAD_VALUE;
2763 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002764 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002765 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002766 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002767 VolumeSource vs = toVolumeSource(group);
2768 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2769
2770 status = setVolumeCurveIndex(index, device, curves);
2771 if (status != NO_ERROR) {
2772 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2773 return status;
2774 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002775
jiabin9a3361e2019-10-01 09:38:30 -07002776 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002777 auto curCurvAttrs = curves.getAttributes();
2778 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2779 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002780 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002781 } else if (!curves.getStreamTypes().empty()) {
2782 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002783 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002784 } else {
2785 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2786 return BAD_VALUE;
2787 }
jiabin9a3361e2019-10-01 09:38:30 -07002788 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2789 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002790
François Gaffiecfe17322018-11-07 13:41:29 +01002791 // update volume on all outputs and streams matching the following:
2792 // - The requested stream (or a stream matching for volume control) is active on the output
2793 // - The device (or devices) selected by the engine for this stream includes
2794 // the requested device
2795 // - For non default requested device, currently selected device on the output is either the
2796 // requested device or one of the devices selected by the engine for this stream
2797 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2798 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002799 for (size_t i = 0; i < mOutputs.size(); i++) {
2800 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002801 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002802
jiabin9a3361e2019-10-01 09:38:30 -07002803 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2804 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002805 }
François Gaffieed91f582020-01-31 10:35:37 +01002806 if (!(desc->isActive(vs) || isInCall())) {
2807 continue;
2808 }
2809 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2810 curDevices.find(device) == curDevices.end()) {
2811 continue;
2812 }
2813 bool applyVolume = false;
2814 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2815 curSrcDevices.insert(device);
2816 applyVolume = (curSrcDevices.find(
2817 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2818 } else {
2819 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2820 }
2821 if (!applyVolume) {
2822 continue; // next output
2823 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002824 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2825 // If a higher priority strategy is active, and the output is routed to a device with a
2826 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002827 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002828 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002829 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2830 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2831 false /*preferredDevice*/);
2832 if (activeClients.empty()) {
2833 continue;
2834 }
2835 bool isPreempted = false;
2836 bool isHigherPriority = productStrategy < strategy;
2837 for (const auto &client : activeClients) {
2838 if (isHigherPriority && (client->volumeSource() != vs)) {
2839 ALOGV("%s: Strategy=%d (\nrequester:\n"
2840 " group %d, volumeGroup=%d attributes=%s)\n"
2841 " higher priority source active:\n"
2842 " volumeGroup=%d attributes=%s) \n"
2843 " on output %zu, bailing out", __func__, productStrategy,
2844 group, group, toString(attributes).c_str(),
2845 client->volumeSource(), toString(client->attributes()).c_str(), i);
2846 applyVolume = false;
2847 isPreempted = true;
2848 break;
2849 }
2850 // However, continue for loop to ensure no higher prio clients running on output
2851 if (client->volumeSource() == vs) {
2852 applyVolume = true;
2853 }
2854 }
2855 if (isPreempted || applyVolume) {
2856 break;
2857 }
2858 }
2859 if (!applyVolume) {
2860 continue; // next output
2861 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002862 }
François Gaffieed91f582020-01-31 10:35:37 +01002863 //FIXME: workaround for truncated touch sounds
2864 // delayed volume change for system stream to be removed when the problem is
2865 // handled by system UI
2866 status_t volStatus = checkAndSetVolume(
2867 curves, vs, index, desc, curDevices,
2868 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2869 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2870 if (volStatus != NO_ERROR) {
2871 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002872 }
2873 }
François Gaffiecfe17322018-11-07 13:41:29 +01002874 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2875 return status;
2876}
2877
François Gaffieaaac0fd2018-11-22 17:56:39 +01002878status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002879 audio_devices_t device,
2880 IVolumeCurves &volumeCurves)
2881{
2882 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2883 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002884 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2885 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002886 (index > volumeCurves.getVolumeIndexMax())) {
2887 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2888 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2889 return BAD_VALUE;
2890 }
2891 if (!audio_is_output_device(device)) {
2892 return BAD_VALUE;
2893 }
2894
2895 // Force max volume if stream cannot be muted
2896 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2897
François Gaffieaaac0fd2018-11-22 17:56:39 +01002898 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002899 volumeCurves.addCurrentVolumeIndex(device, index);
2900 return NO_ERROR;
2901}
2902
2903status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2904 int &index,
2905 audio_devices_t device)
2906{
2907 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2908 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002909 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002910 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002911 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2912 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002913 }
jiabin9a3361e2019-10-01 09:38:30 -07002914 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002915}
2916
2917status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2918 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002919 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002920{
jiabin9a3361e2019-10-01 09:38:30 -07002921 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002922 return BAD_VALUE;
2923 }
jiabin9a3361e2019-10-01 09:38:30 -07002924 index = curves.getVolumeIndex(deviceTypes);
2925 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002926 return NO_ERROR;
2927}
2928
2929status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2930 int &index)
2931{
2932 index = getVolumeCurves(attr).getVolumeIndexMin();
2933 return NO_ERROR;
2934}
2935
2936status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2937 int &index)
2938{
2939 index = getVolumeCurves(attr).getVolumeIndexMax();
2940 return NO_ERROR;
2941}
2942
Eric Laurent36829f92017-04-07 19:04:42 -07002943audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002944{
2945 // select one output among several suitable for global effects.
2946 // The priority is as follows:
2947 // 1: An offloaded output. If the effect ends up not being offloadable,
2948 // AudioFlinger will invalidate the track and the offloaded output
2949 // will be closed causing the effect to be moved to a PCM output.
2950 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002951 // 3: The primary output
2952 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002953
François Gaffiec005e562018-11-06 15:04:49 +01002954 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2955 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002956 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002957
Eric Laurent36829f92017-04-07 19:04:42 -07002958 if (outputs.size() == 0) {
2959 return AUDIO_IO_HANDLE_NONE;
2960 }
Eric Laurente552edb2014-03-10 17:42:56 -07002961
Eric Laurent36829f92017-04-07 19:04:42 -07002962 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2963 bool activeOnly = true;
2964
2965 while (output == AUDIO_IO_HANDLE_NONE) {
2966 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2967 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2968 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2969
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002970 for (audio_io_handle_t output : outputs) {
2971 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002972 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002973 continue;
2974 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002975 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2976 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002977 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002978 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002979 }
2980 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002981 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002982 }
2983 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002984 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002985 }
2986 }
2987 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2988 output = outputOffloaded;
2989 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2990 output = outputDeepBuffer;
2991 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2992 output = outputPrimary;
2993 } else {
2994 output = outputs[0];
2995 }
2996 activeOnly = false;
2997 }
2998
2999 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003000 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003001 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3002 mMusicEffectOutput = output;
3003 }
3004
3005 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003006 return output;
3007}
3008
Eric Laurent36829f92017-04-07 19:04:42 -07003009audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3010{
3011 return selectOutputForMusicEffects();
3012}
3013
Eric Laurente0720872014-03-11 09:30:41 -07003014status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003015 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003016 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003017 int session,
3018 int id)
3019{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003020 if (session != AUDIO_SESSION_DEVICE) {
3021 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003022 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003023 index = mInputs.indexOfKey(io);
3024 if (index < 0) {
3025 ALOGW("registerEffect() unknown io %d", io);
3026 return INVALID_OPERATION;
3027 }
Eric Laurente552edb2014-03-10 17:42:56 -07003028 }
3029 }
François Gaffiec005e562018-11-06 15:04:49 +01003030 return mEffects.registerEffect(desc, io, session, id,
3031 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3032 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003033}
3034
Eric Laurentc241b0d2018-11-28 09:08:49 -08003035status_t AudioPolicyManager::unregisterEffect(int id)
3036{
3037 if (mEffects.getEffect(id) == nullptr) {
3038 return INVALID_OPERATION;
3039 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003040 if (mEffects.isEffectEnabled(id)) {
3041 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3042 setEffectEnabled(id, false);
3043 }
3044 return mEffects.unregisterEffect(id);
3045}
3046
3047status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3048{
3049 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3050 if (effect == nullptr) {
3051 return INVALID_OPERATION;
3052 }
3053
3054 status_t status = mEffects.setEffectEnabled(id, enabled);
3055 if (status == NO_ERROR) {
3056 mInputs.trackEffectEnabled(effect, enabled);
3057 }
3058 return status;
3059}
3060
Eric Laurent6c796322019-04-09 14:13:17 -07003061
3062status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3063{
3064 mEffects.moveEffects(ids, io);
3065 return NO_ERROR;
3066}
3067
Eric Laurentc75307b2015-03-17 15:29:32 -07003068bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3069{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003070 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003071}
3072
3073bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3074{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003075 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003076}
3077
Eric Laurente0720872014-03-11 09:30:41 -07003078bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003079{
3080 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003081 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003082 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003083 return true;
3084 }
3085 }
3086 return false;
3087}
3088
Eric Laurent275e8e92014-11-30 15:14:47 -08003089// Register a list of custom mixes with their attributes and format.
3090// When a mix is registered, corresponding input and output profiles are
3091// added to the remote submix hw module. The profile contains only the
3092// parameters (sampling rate, format...) specified by the mix.
3093// The corresponding input remote submix device is also connected.
3094//
3095// When a remote submix device is connected, the address is checked to select the
3096// appropriate profile and the corresponding input or output stream is opened.
3097//
3098// When capture starts, getInputForAttr() will:
3099// - 1 look for a mix matching the address passed in attribtutes tags if any
3100// - 2 if none found, getDeviceForInputSource() will:
3101// - 2.1 look for a mix matching the attributes source
3102// - 2.2 if none found, default to device selection by policy rules
3103// At this time, the corresponding output remote submix device is also connected
3104// and active playback use cases can be transferred to this mix if needed when reconnecting
3105// after AudioTracks are invalidated
3106//
3107// When playback starts, getOutputForAttr() will:
3108// - 1 look for a mix matching the address passed in attribtutes tags if any
3109// - 2 if none found, look for a mix matching the attributes usage
3110// - 3 if none found, default to device and output selection by policy rules.
3111
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003112status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003113{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003114 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3115 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003116 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003117 sp<HwModule> rSubmixModule;
3118 // examine each mix's route type
3119 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003120 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003121 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3122 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3123 ALOGE("Unsupported Policy Mix %zu of %zu: "
3124 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3125 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003126 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003127 break;
3128 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003129 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3130 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003131 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003132 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3133 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003134 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003135 rSubmixModule = mHwModules.getModuleFromName(
3136 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3137 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003138 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003139 i);
3140 res = INVALID_OPERATION;
3141 break;
3142 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003143 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003144
Eric Laurent97ac8712018-07-27 18:59:02 -07003145 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003146 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003147 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003148 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003149 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3150 } else {
3151 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3152 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003153 }
François Gaffie036e1e92015-03-19 10:16:24 +01003154
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003155 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003156 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003157 res = INVALID_OPERATION;
3158 break;
3159 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003160 audio_config_t outputConfig = mix.mFormat;
3161 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003162 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3163 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003164 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3165 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003166 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003167 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003168 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003169 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003170
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003171 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003172 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3173 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3174 ALOGE("Failed to set remote submix device available, type %u, address %s",
3175 mix.mDeviceType, address.string());
3176 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003177 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003178 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3179 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003180 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003181 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003182 i, mixes.size(), type, address.string());
3183
3184 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3185 mix.mDeviceType, mix.mDeviceAddress,
3186 String8(), AUDIO_FORMAT_DEFAULT);
3187 if (device == nullptr) {
3188 res = INVALID_OPERATION;
3189 break;
3190 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003191
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003192 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003193 // First try to find an already opened output supporting the device
3194 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003196
Eric Laurentc529cf62020-04-17 18:19:10 -07003197 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003198 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003199 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3200 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003201 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003202 } else {
3203 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003204 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003205 }
3206 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003207 // If no output found, try to find a direct output profile supporting the device
3208 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3209 sp<HwModule> module = mHwModules[i];
3210 for (size_t j = 0;
3211 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3212 j++) {
3213 sp<IOProfile> profile = module->getOutputProfiles()[j];
3214 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3215 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3216 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3217 address.string());
3218 res = INVALID_OPERATION;
3219 } else {
3220 foundOutput = true;
3221 }
3222 }
3223 }
3224 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003225 if (res != NO_ERROR) {
3226 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003227 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003228 res = INVALID_OPERATION;
3229 break;
3230 } else if (!foundOutput) {
3231 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003232 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003233 res = INVALID_OPERATION;
3234 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003235 } else {
3236 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003237 }
Eric Laurentc722f302014-12-10 11:21:49 -08003238 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003239 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003240 if (res != NO_ERROR) {
3241 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003242 } else if (checkOutputs) {
3243 checkForDeviceAndOutputChanges();
3244 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003245 }
3246 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003247}
3248
3249status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3250{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003251 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003252 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003253 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003254 sp<HwModule> rSubmixModule;
3255 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003256 for (const auto& mix : mixes) {
3257 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003258
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003259 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003260 rSubmixModule = mHwModules.getModuleFromName(
3261 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3262 if (rSubmixModule == 0) {
3263 res = INVALID_OPERATION;
3264 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265 }
3266 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003267
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003268 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003269
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003270 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003271 res = INVALID_OPERATION;
3272 continue;
3273 }
3274
Kevin Rocard04ed0462019-05-02 17:53:24 -07003275 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3276 if (getDeviceConnectionState(device, address.string()) ==
3277 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3278 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3279 address.string(), "remote-submix",
3280 AUDIO_FORMAT_DEFAULT);
3281 if (res != OK) {
3282 ALOGE("Error making RemoteSubmix device unavailable for mix "
3283 "with type %d, address %s", device, address.string());
3284 }
3285 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003286 }
jiabin5740f082019-08-19 15:08:30 -07003287 rSubmixModule->removeOutputProfile(address.c_str());
3288 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003289
Kevin Rocard153f92d2018-12-18 18:33:28 -08003290 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003291 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003292 res = INVALID_OPERATION;
3293 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003294 } else {
3295 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003296 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003297 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003298 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003299 if (res == NO_ERROR && checkOutputs) {
3300 checkForDeviceAndOutputChanges();
3301 updateCallAndOutputRouting();
3302 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003303 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003304}
3305
Mikhail Naganov100f0122018-11-29 11:22:16 -08003306void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3307{
3308 size_t i = 0;
3309 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3310 for (const auto& fmt : mManualSurroundFormats) {
3311 if (i++ != 0) dst->append(", ");
3312 std::string sfmt;
3313 FormatConverter::toString(fmt, sfmt);
3314 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3315 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3316 }
3317}
3318
Eric Laurentc529cf62020-04-17 18:19:10 -07003319// Returns true if all devices types match the predicate and are supported by one HW module
3320bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003321 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003322 std::function<bool(audio_devices_t)> predicate,
3323 const char *context) {
3324 for (size_t i = 0; i < devices.size(); i++) {
3325 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003326 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003327 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003328 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003329 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003330 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003331 return false;
3332 }
3333 }
3334 return true;
3335}
3336
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003337status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003338 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003339 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003340 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3341 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003342 }
3343 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003344 if (res != NO_ERROR) {
3345 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3346 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003347 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003348
3349 checkForDeviceAndOutputChanges();
3350 updateCallAndOutputRouting();
3351
3352 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003353}
3354
3355status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3356 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003357 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3358 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003359 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003360 __FUNCTION__, uid);
3361 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003362 }
3363
Eric Laurentc529cf62020-04-17 18:19:10 -07003364 checkForDeviceAndOutputChanges();
3365 updateCallAndOutputRouting();
3366
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003367 return res;
3368}
3369
Eric Laurent2517af32020-11-25 15:31:27 +01003370
jiabin0a488932020-08-07 17:32:40 -07003371status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3372 device_role_t role,
3373 const AudioDeviceTypeAddrVector &devices) {
3374 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3375 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003376
Eric Laurentc529cf62020-04-17 18:19:10 -07003377 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003378 return BAD_VALUE;
3379 }
jiabin0a488932020-08-07 17:32:40 -07003380 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003381 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003382 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3383 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003384 return status;
3385 }
3386
3387 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003388
3389 bool forceVolumeReeval = false;
3390 // FIXME: workaround for truncated touch sounds
3391 // to be removed when the problem is handled by system UI
3392 uint32_t delayMs = 0;
3393 if (strategy == mCommunnicationStrategy) {
3394 forceVolumeReeval = true;
3395 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3396 updateInputRouting();
3397 }
3398 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003399
3400 return NO_ERROR;
3401}
3402
3403void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3404{
3405 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003406 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003407 // Only apply special touch sound delay once
3408 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003409 }
3410 for (size_t i = 0; i < mOutputs.size(); i++) {
3411 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3412 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3413 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3414 // As done in setDeviceConnectionState, we could also fix default device issue by
3415 // preventing the force re-routing in case of default dev that distinguishes on address.
3416 // Let's give back to engine full device choice decision however.
3417 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003418 // Only apply special touch sound delay once
3419 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003420 }
3421 if (forceVolumeReeval && !newDevices.isEmpty()) {
3422 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3423 }
3424 }
3425}
3426
Eric Laurent2517af32020-11-25 15:31:27 +01003427void AudioPolicyManager::updateInputRouting() {
3428 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303429 // Skip for hotword recording as the input device switch
3430 // is handled within sound trigger HAL
3431 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3432 continue;
3433 }
Eric Laurent2517af32020-11-25 15:31:27 +01003434 auto newDevice = getNewInputDevice(activeDesc);
3435 // Force new input selection if the new device can not be reached via current input
3436 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3437 setInputDevice(activeDesc->mIoHandle, newDevice);
3438 } else {
3439 closeInput(activeDesc->mIoHandle);
3440 }
3441 }
3442}
3443
jiabin0a488932020-08-07 17:32:40 -07003444status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3445 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003446{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003447 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003448
jiabin0a488932020-08-07 17:32:40 -07003449 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003450 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003451 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3452 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003453 return status;
3454 }
3455
3456 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003457
3458 bool forceVolumeReeval = false;
3459 // FIXME: workaround for truncated touch sounds
3460 // to be removed when the problem is handled by system UI
3461 uint32_t delayMs = 0;
3462 if (strategy == mCommunnicationStrategy) {
3463 forceVolumeReeval = true;
3464 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3465 updateInputRouting();
3466 }
3467 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003468
3469 return NO_ERROR;
3470}
3471
jiabin0a488932020-08-07 17:32:40 -07003472status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3473 device_role_t role,
3474 AudioDeviceTypeAddrVector &devices) {
3475 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003476}
3477
Jiabin Huang3b98d322020-09-03 17:54:16 +00003478status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3479 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3480 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3481 dumpAudioDeviceTypeAddrVector(devices).c_str());
3482
Mikhail Naganov55773032020-10-01 15:08:13 -07003483 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003484 return BAD_VALUE;
3485 }
3486 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3487 ALOGW_IF(status != NO_ERROR,
3488 "Engine could not set preferred devices %s for audio source %d role %d",
3489 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3490
3491 return status;
3492}
3493
3494status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3495 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3496 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3497 dumpAudioDeviceTypeAddrVector(devices).c_str());
3498
Mikhail Naganov55773032020-10-01 15:08:13 -07003499 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003500 return BAD_VALUE;
3501 }
3502 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3503 ALOGW_IF(status != NO_ERROR,
3504 "Engine could not add preferred devices %s for audio source %d role %d",
3505 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3506
Eric Laurent2517af32020-11-25 15:31:27 +01003507 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003508 return status;
3509}
3510
3511status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3512 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3513{
3514 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3515 dumpAudioDeviceTypeAddrVector(devices).c_str());
3516
Mikhail Naganov55773032020-10-01 15:08:13 -07003517 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003518 return BAD_VALUE;
3519 }
3520
3521 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3522 audioSource, role, devices);
3523 ALOGW_IF(status != NO_ERROR,
3524 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3525
Eric Laurent2517af32020-11-25 15:31:27 +01003526 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003527 return status;
3528}
3529
3530status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3531 device_role_t role) {
3532 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3533
3534 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3535 ALOGW_IF(status != NO_ERROR,
3536 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3537
Eric Laurent2517af32020-11-25 15:31:27 +01003538 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003539 return status;
3540}
3541
3542status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3543 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3544 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3545}
3546
Oscar Azucena90e77632019-11-27 17:12:28 -08003547status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003548 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003549 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003550 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3551 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003552 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003553 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3554 if (status != NO_ERROR) {
3555 ALOGE("%s() could not set device affinity for userId %d",
3556 __FUNCTION__, userId);
3557 return status;
3558 }
3559
3560 // reevaluate outputs for all devices
3561 checkForDeviceAndOutputChanges();
3562 updateCallAndOutputRouting();
3563
3564 return NO_ERROR;
3565}
3566
3567status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003568 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003569 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3570 if (status != NO_ERROR) {
3571 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3572 __FUNCTION__, userId);
3573 return status;
3574 }
3575
3576 // reevaluate outputs for all devices
3577 checkForDeviceAndOutputChanges();
3578 updateCallAndOutputRouting();
3579
3580 return NO_ERROR;
3581}
3582
Andy Hungc29d82b2018-10-05 12:23:17 -07003583void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003584{
Andy Hungc29d82b2018-10-05 12:23:17 -07003585 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3586 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003587 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003588 std::string stateLiteral;
3589 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003590 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003591 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3592 "communications", "media", "record", "dock", "system",
3593 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3594 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3595 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003596 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3597 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3598 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3599 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3600 dst->append(" (MANUAL: ");
3601 dumpManualSurroundFormats(dst);
3602 dst->append(")");
3603 }
3604 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003605 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003606 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3607 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003608 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003609 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003610
Andy Hungc29d82b2018-10-05 12:23:17 -07003611 mAvailableOutputDevices.dump(dst, String8("Available output"));
3612 mAvailableInputDevices.dump(dst, String8("Available input"));
3613 mHwModulesAll.dump(dst);
3614 mOutputs.dump(dst);
3615 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003616 mEffects.dump(dst);
3617 mAudioPatches.dump(dst);
3618 mPolicyMixes.dump(dst);
3619 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003620
Kevin Rocardb99cc752019-03-21 20:52:24 -07003621 dst->appendFormat(" AllowedCapturePolicies:\n");
3622 for (auto& policy : mAllowedCapturePolicies) {
3623 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3624 }
3625
François Gaffiec005e562018-11-06 15:04:49 +01003626 dst->appendFormat("\nPolicy Engine dump:\n");
3627 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003628}
3629
3630status_t AudioPolicyManager::dump(int fd)
3631{
3632 String8 result;
3633 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003634 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003635 return NO_ERROR;
3636}
3637
Kevin Rocardb99cc752019-03-21 20:52:24 -07003638status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3639{
3640 mAllowedCapturePolicies[uid] = capturePolicy;
3641 return NO_ERROR;
3642}
3643
Eric Laurente552edb2014-03-10 17:42:56 -07003644// This function checks for the parameters which can be offloaded.
3645// This can be enhanced depending on the capability of the DSP and policy
3646// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003647audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003648{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003649 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003650 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003651 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003652 offloadInfo.format,
3653 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3654 offloadInfo.has_video);
3655
Andy Hung2ddee192015-12-18 17:34:44 -08003656 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003657 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003658 }
3659
Eric Laurente552edb2014-03-10 17:42:56 -07003660 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003661 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003662 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3663 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003664 }
3665
3666 // Check if stream type is music, then only allow offload as of now.
3667 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3668 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003669 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3670 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003671 }
3672
3673 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003674 const bool allowOffloadWithVideo =
3675 property_get_bool("audio.offload.video", false /* default_value */);
3676 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003677 ALOGV("%s: has_video == true, returning false", __func__);
3678 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003679 }
3680
3681 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003682 const int min_duration_secs = property_get_int32(
3683 "audio.offload.min.duration.secs", -1 /* default_value */);
3684 if (min_duration_secs >= 0) {
3685 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003686 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3687 __func__, min_duration_secs);
3688 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003689 }
3690 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003691 ALOGV("%s: Offload denied by duration < default min(=%u)",
3692 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3693 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003694 }
3695
3696 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3697 // creating an offloaded track and tearing it down immediately after start when audioflinger
3698 // detects there is an active non offloadable effect.
3699 // FIXME: We should check the audio session here but we do not have it in this context.
3700 // This may prevent offloading in rare situations where effects are left active by apps
3701 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003702 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003703 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003704 }
3705
3706 // See if there is a profile to support this.
3707 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003708 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003709 offloadInfo.sample_rate,
3710 offloadInfo.format,
3711 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003712 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3713 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003714 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3715 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3716 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003717 if (profile == nullptr) {
3718 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3719 }
3720 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3721 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3722 }
3723 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003724}
3725
Michael Chana94fbb22018-04-24 14:31:19 +10003726bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3727 const audio_attributes_t& attributes) {
3728 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003729 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003730 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003731 config.sample_rate,
3732 config.format,
3733 config.channel_mask,
3734 output_flags,
3735 true /* directOnly */);
3736 ALOGV("%s() profile %sfound with name: %s, "
3737 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3738 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003739 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003740 config.sample_rate, config.format, config.channel_mask, output_flags);
3741 return (profile != 0);
3742}
3743
Eric Laurent6a94d692014-05-20 11:18:06 -07003744status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3745 audio_port_type_t type,
3746 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003747 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003748 unsigned int *generation)
3749{
jiabin19cdba52020-11-24 11:28:58 -08003750 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3751 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003752 return BAD_VALUE;
3753 }
3754 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003755 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003756 *num_ports = 0;
3757 }
3758
3759 size_t portsWritten = 0;
3760 size_t portsMax = *num_ports;
3761 *num_ports = 0;
3762 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003763 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3764 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003765 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003766 for (const auto& dev : mAvailableOutputDevices) {
3767 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003768 continue;
3769 }
3770 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003771 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003772 }
3773 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003774 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003775 }
3776 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003777 for (const auto& dev : mAvailableInputDevices) {
3778 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003779 continue;
3780 }
3781 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003782 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003783 }
3784 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003786 }
3787 }
3788 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3789 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3790 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3791 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3792 }
3793 *num_ports += mInputs.size();
3794 }
3795 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003796 size_t numOutputs = 0;
3797 for (size_t i = 0; i < mOutputs.size(); i++) {
3798 if (!mOutputs[i]->isDuplicated()) {
3799 numOutputs++;
3800 if (portsWritten < portsMax) {
3801 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3802 }
3803 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003804 }
Eric Laurent84c70242014-06-23 08:46:27 -07003805 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003806 }
3807 }
3808 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003809 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003810 return NO_ERROR;
3811}
3812
jiabin19cdba52020-11-24 11:28:58 -08003813status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003814{
Eric Laurent99fcae42018-05-17 16:59:18 -07003815 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3816 return BAD_VALUE;
3817 }
3818 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3819 if (dev != 0) {
3820 dev->toAudioPort(port);
3821 return NO_ERROR;
3822 }
3823 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3824 if (dev != 0) {
3825 dev->toAudioPort(port);
3826 return NO_ERROR;
3827 }
3828 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3829 if (out != 0) {
3830 out->toAudioPort(port);
3831 return NO_ERROR;
3832 }
3833 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3834 if (in != 0) {
3835 in->toAudioPort(port);
3836 return NO_ERROR;
3837 }
3838 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003839}
3840
François Gaffieafd4cea2019-11-18 15:50:22 +01003841status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3842 audio_patch_handle_t *handle,
3843 uid_t uid, uint32_t delayMs,
3844 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003845{
François Gaffieafd4cea2019-11-18 15:50:22 +01003846 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003847 if (handle == NULL || patch == NULL) {
3848 return BAD_VALUE;
3849 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003850 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003851
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003852 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003853 return BAD_VALUE;
3854 }
3855 // only one source per audio patch supported for now
3856 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003857 return INVALID_OPERATION;
3858 }
Eric Laurent874c42872014-08-08 15:13:39 -07003859
3860 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003861 return INVALID_OPERATION;
3862 }
Eric Laurent874c42872014-08-08 15:13:39 -07003863 for (size_t i = 0; i < patch->num_sinks; i++) {
3864 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3865 return INVALID_OPERATION;
3866 }
3867 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003868
3869 sp<AudioPatch> patchDesc;
3870 ssize_t index = mAudioPatches.indexOfKey(*handle);
3871
François Gaffieafd4cea2019-11-18 15:50:22 +01003872 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3873 patch->sources[0].role,
3874 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003875#if LOG_NDEBUG == 0
3876 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003877 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3878 patch->sinks[i].role,
3879 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003880 }
3881#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003882
3883 if (index >= 0) {
3884 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003885 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3886 __func__, mUidCached, patchDesc->getUid(), uid);
3887 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003888 return INVALID_OPERATION;
3889 }
3890 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003891 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003892 }
3893
3894 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003895 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003896 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003897 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003898 return BAD_VALUE;
3899 }
Eric Laurent84c70242014-06-23 08:46:27 -07003900 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3901 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003902 if (patchDesc != 0) {
3903 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003904 ALOGV("%s source id differs for patch current id %d new id %d",
3905 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003906 return BAD_VALUE;
3907 }
3908 }
Eric Laurent874c42872014-08-08 15:13:39 -07003909 DeviceVector devices;
3910 for (size_t i = 0; i < patch->num_sinks; i++) {
3911 // Only support mix to devices connection
3912 // TODO add support for mix to mix connection
3913 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003914 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003915 return INVALID_OPERATION;
3916 }
3917 sp<DeviceDescriptor> devDesc =
3918 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3919 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003920 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003921 return BAD_VALUE;
3922 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003923
François Gaffie11d30102018-11-02 16:09:09 +01003924 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003925 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003926 NULL, // updatedSamplingRate
3927 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003928 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003929 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003930 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003931 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003932 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003933 return INVALID_OPERATION;
3934 }
3935 devices.add(devDesc);
3936 }
3937 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003938 return INVALID_OPERATION;
3939 }
Eric Laurent874c42872014-08-08 15:13:39 -07003940
Eric Laurent6a94d692014-05-20 11:18:06 -07003941 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003942 ALOGV("%s setting device %s on output %d",
3943 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003944 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003945 index = mAudioPatches.indexOfKey(*handle);
3946 if (index >= 0) {
3947 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003948 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003949 }
3950 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003951 patchDesc->setUid(uid);
3952 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003953 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003954 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003955 return INVALID_OPERATION;
3956 }
3957 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3958 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3959 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003960 // only one sink supported when connecting an input device to a mix
3961 if (patch->num_sinks > 1) {
3962 return INVALID_OPERATION;
3963 }
François Gaffie53615e22015-03-19 09:24:12 +01003964 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003965 if (inputDesc == NULL) {
3966 return BAD_VALUE;
3967 }
3968 if (patchDesc != 0) {
3969 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3970 return BAD_VALUE;
3971 }
3972 }
François Gaffie11d30102018-11-02 16:09:09 +01003973 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003975 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 return BAD_VALUE;
3977 }
3978
François Gaffie11d30102018-11-02 16:09:09 +01003979 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003980 patch->sinks[0].sample_rate,
3981 NULL, /*updatedSampleRate*/
3982 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003983 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003984 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003985 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003986 // FIXME for the parameter type,
3987 // and the NONE
3988 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003989 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 return INVALID_OPERATION;
3991 }
3992 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003993 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003994 device->toString().c_str(), inputDesc->mIoHandle);
3995 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003996 index = mAudioPatches.indexOfKey(*handle);
3997 if (index >= 0) {
3998 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003999 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004000 }
4001 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004002 patchDesc->setUid(uid);
4003 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004004 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004005 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004006 return INVALID_OPERATION;
4007 }
4008 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4009 // device to device connection
4010 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004011 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004012 return BAD_VALUE;
4013 }
4014 }
François Gaffie11d30102018-11-02 16:09:09 +01004015 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004016 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004017 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004018 return BAD_VALUE;
4019 }
Eric Laurent874c42872014-08-08 15:13:39 -07004020
Eric Laurent6a94d692014-05-20 11:18:06 -07004021 //update source and sink with our own data as the data passed in the patch may
4022 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004023 PatchBuilder patchBuilder;
4024 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004025
4026 // if first sink is to MSD, establish single MSD patch
4027 if (getMsdAudioOutDevices().contains(
4028 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4029 ALOGV("%s patching to MSD", __FUNCTION__);
4030 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4031 goto installPatch;
4032 }
4033
François Gaffieafd4cea2019-11-18 15:50:22 +01004034 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4035 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004036
Eric Laurent874c42872014-08-08 15:13:39 -07004037 for (size_t i = 0; i < patch->num_sinks; i++) {
4038 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004039 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004040 return INVALID_OPERATION;
4041 }
François Gaffie11d30102018-11-02 16:09:09 +01004042 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004043 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004044 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004045 return BAD_VALUE;
4046 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004047 audio_port_config sinkPortConfig = {};
4048 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4049 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004050
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004051 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4052 // volume management purpose (tracking activity)
4053 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4054 // in config XML to reach the sink so that is can be declared as available.
4055 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4056 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4057 if (sourceDesc != nullptr) {
4058 // take care of dynamic routing for SwOutput selection,
4059 audio_attributes_t attributes = sourceDesc->attributes();
4060 audio_stream_type_t stream = sourceDesc->stream();
4061 audio_attributes_t resultAttr;
4062 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4063 config.sample_rate = sourceDesc->config().sample_rate;
4064 config.channel_mask = sourceDesc->config().channel_mask;
4065 config.format = sourceDesc->config().format;
4066 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4067 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4068 bool isRequestedDeviceForExclusiveUse = false;
4069 output_type_t outputType;
4070 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4071 &stream, sourceDesc->uid(), &config, &flags,
4072 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4073 nullptr, &outputType);
4074 if (output == AUDIO_IO_HANDLE_NONE) {
4075 ALOGV("%s no output for device %s",
4076 __FUNCTION__, sinkDevice->toString().c_str());
4077 return INVALID_OPERATION;
4078 }
4079 outputDesc = mOutputs.valueFor(output);
4080 if (outputDesc->isDuplicated()) {
4081 ALOGE("%s output is duplicated", __func__);
4082 return INVALID_OPERATION;
4083 }
4084 sourceDesc->setSwOutput(outputDesc);
4085 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004086 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004087 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004088 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004089 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004090 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4091 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004092 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4093 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004094 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4095 (sourceDesc != nullptr &&
4096 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004097 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004098 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004099 return INVALID_OPERATION;
4100 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004101 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004102 SortedVector<audio_io_handle_t> outputs =
4103 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4104 // if the sink device is reachable via an opened output stream, request to
4105 // go via this output stream by adding a second source to the patch
4106 // description
4107 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004108 if (output != AUDIO_IO_HANDLE_NONE) {
4109 outputDesc = mOutputs.valueFor(output);
4110 if (outputDesc->isDuplicated()) {
4111 ALOGV("%s output for device %s is duplicated",
4112 __FUNCTION__, sinkDevice->toString().c_str());
4113 return INVALID_OPERATION;
4114 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004115 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004116 }
4117 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004118 audio_port_config srcMixPortConfig = {};
4119 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004120 // for volume control, we may need a valid stream
4121 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4122 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4123 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004124 }
Eric Laurent83b88082014-06-20 18:31:16 -07004125 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004126 }
4127 // TODO: check from routing capabilities in config file and other conflicting patches
4128
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004129installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004130 status_t status = installPatch(
4131 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004132 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004133 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004134 return INVALID_OPERATION;
4135 }
4136 } else {
4137 return BAD_VALUE;
4138 }
4139 } else {
4140 return BAD_VALUE;
4141 }
4142 return NO_ERROR;
4143}
4144
4145status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4146 uid_t uid)
4147{
4148 ALOGV("releaseAudioPatch() patch %d", handle);
4149
4150 ssize_t index = mAudioPatches.indexOfKey(handle);
4151
4152 if (index < 0) {
4153 return BAD_VALUE;
4154 }
4155 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004156 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4157 __func__, mUidCached, patchDesc->getUid(), uid);
4158 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004159 return INVALID_OPERATION;
4160 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004161 return releaseAudioPatchInternal(handle);
4162}
Eric Laurent6a94d692014-05-20 11:18:06 -07004163
François Gaffieafd4cea2019-11-18 15:50:22 +01004164status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4165 uint32_t delayMs)
4166{
4167 ALOGV("%s patch %d", __func__, handle);
4168 if (mAudioPatches.indexOfKey(handle) < 0) {
4169 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4170 return BAD_VALUE;
4171 }
4172 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004173 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004174 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004176 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004177 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004178 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 return BAD_VALUE;
4180 }
4181
François Gaffie11d30102018-11-02 16:09:09 +01004182 setOutputDevices(outputDesc,
4183 getNewOutputDevices(outputDesc, true /*fromCache*/),
4184 true,
4185 0,
4186 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4188 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004189 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004190 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004191 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004192 return BAD_VALUE;
4193 }
4194 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004195 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 true,
4197 NULL);
4198 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004199 status_t status =
4200 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4201 ALOGV("%s patch panel returned %d patchHandle %d",
4202 __func__, status, patchDesc->getAfHandle());
4203 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004204 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004205 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004206 // SW Bridge
4207 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4208 sp<SwAudioOutputDescriptor> outputDesc =
4209 mOutputs.getOutputFromId(patch->sources[1].id);
4210 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004211 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4212 // releaseOutput has already called closeOuput in case of direct output
4213 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004214 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004215 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4216 // force SwOutput patch removal as AF counter part patch has already gone.
4217 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4218 removeAudioPatch(outputDesc->getPatchHandle());
4219 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004220 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4221 setOutputDevices(outputDesc,
4222 getNewOutputDevices(outputDesc, true /*fromCache*/),
4223 true, /*force*/
4224 0,
4225 NULL);
4226 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004227 } else {
4228 return BAD_VALUE;
4229 }
4230 } else {
4231 return BAD_VALUE;
4232 }
4233 return NO_ERROR;
4234}
4235
4236status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4237 struct audio_patch *patches,
4238 unsigned int *generation)
4239{
François Gaffie53615e22015-03-19 09:24:12 +01004240 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004241 return BAD_VALUE;
4242 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004243 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004244 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004245}
4246
Eric Laurente1715a42014-05-20 11:30:42 -07004247status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004248{
Eric Laurente1715a42014-05-20 11:30:42 -07004249 ALOGV("setAudioPortConfig()");
4250
4251 if (config == NULL) {
4252 return BAD_VALUE;
4253 }
4254 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4255 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004256 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4257 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004258 }
4259
Eric Laurenta121f902014-06-03 13:32:54 -07004260 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004261 if (config->type == AUDIO_PORT_TYPE_MIX) {
4262 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004263 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004264 if (outputDesc == NULL) {
4265 return BAD_VALUE;
4266 }
Eric Laurent84c70242014-06-23 08:46:27 -07004267 ALOG_ASSERT(!outputDesc->isDuplicated(),
4268 "setAudioPortConfig() called on duplicated output %d",
4269 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004270 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004271 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004272 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004273 if (inputDesc == NULL) {
4274 return BAD_VALUE;
4275 }
Eric Laurenta121f902014-06-03 13:32:54 -07004276 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004277 } else {
4278 return BAD_VALUE;
4279 }
4280 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4281 sp<DeviceDescriptor> deviceDesc;
4282 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4283 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4284 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4285 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4286 } else {
4287 return BAD_VALUE;
4288 }
4289 if (deviceDesc == NULL) {
4290 return BAD_VALUE;
4291 }
Eric Laurenta121f902014-06-03 13:32:54 -07004292 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004293 } else {
4294 return BAD_VALUE;
4295 }
4296
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004297 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004298 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4299 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004300 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004301 audioPortConfig->toAudioPortConfig(&newConfig, config);
4302 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004303 }
Eric Laurenta121f902014-06-03 13:32:54 -07004304 if (status != NO_ERROR) {
4305 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004306 }
Eric Laurente1715a42014-05-20 11:30:42 -07004307
4308 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004309}
4310
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004311void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4312{
Eric Laurentd60560a2015-04-10 11:31:20 -07004313 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004314 clearAudioPatches(uid);
4315 clearSessionRoutes(uid);
4316}
4317
Eric Laurent6a94d692014-05-20 11:18:06 -07004318void AudioPolicyManager::clearAudioPatches(uid_t uid)
4319{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004320 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004321 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004322 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004323 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004324 }
4325 }
4326}
4327
François Gaffiec005e562018-11-06 15:04:49 +01004328void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004329{
François Gaffiec005e562018-11-06 15:04:49 +01004330 // Take the first attributes following the product strategy as it is used to retrieve the routed
4331 // device. All attributes wihin a strategy follows the same "routing strategy"
4332 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4333 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004334 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004335 for (size_t j = 0; j < mOutputs.size(); j++) {
4336 if (mOutputs.keyAt(j) == ouptutToSkip) {
4337 continue;
4338 }
4339 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004340 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004341 continue;
4342 }
4343 // If the default device for this strategy is on another output mix,
4344 // invalidate all tracks in this strategy to force re connection.
4345 // Otherwise select new device on the output mix.
4346 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004347 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4348 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004349 }
4350 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004351 setOutputDevices(
4352 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004353 }
4354 }
4355}
4356
4357void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4358{
4359 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004360 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004361 for (size_t i = 0; i < mOutputs.size(); i++) {
4362 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004363 for (const auto& client : outputDesc->getClientIterable()) {
4364 if (client->hasPreferredDevice() && client->uid() == uid) {
4365 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004366 auto clientStrategy = client->strategy();
4367 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4368 end(affectedStrategies)) {
4369 continue;
4370 }
4371 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004372 }
4373 }
4374 }
4375 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004376 for (const auto& strategy : affectedStrategies) {
4377 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004378 }
4379
4380 // remove input routes associated with this uid
4381 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004382 for (size_t i = 0; i < mInputs.size(); i++) {
4383 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004384 for (const auto& client : inputDesc->getClientIterable()) {
4385 if (client->hasPreferredDevice() && client->uid() == uid) {
4386 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4387 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004388 }
4389 }
4390 }
4391 // reroute inputs if necessary
4392 SortedVector<audio_io_handle_t> inputsToClose;
4393 for (size_t i = 0; i < mInputs.size(); i++) {
4394 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004395 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004396 inputsToClose.add(inputDesc->mIoHandle);
4397 }
4398 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004399 for (const auto& input : inputsToClose) {
4400 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004401 }
4402}
4403
Eric Laurentd60560a2015-04-10 11:31:20 -07004404void AudioPolicyManager::clearAudioSources(uid_t uid)
4405{
4406 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004407 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4408 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004409 stopAudioSource(mAudioSources.keyAt(i));
4410 }
4411 }
4412}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004413
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004414status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4415 audio_io_handle_t *ioHandle,
4416 audio_devices_t *device)
4417{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004418 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4419 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004420 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004421 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004422
François Gaffiedf372692015-03-19 10:43:27 +01004423 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004424}
4425
Eric Laurentd60560a2015-04-10 11:31:20 -07004426status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004427 const audio_attributes_t *attributes,
4428 audio_port_handle_t *portId,
4429 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004430{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004431 ALOGV("%s", __FUNCTION__);
4432 *portId = AUDIO_PORT_HANDLE_NONE;
4433
4434 if (source == NULL || attributes == NULL || portId == NULL) {
4435 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4436 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004437 return BAD_VALUE;
4438 }
4439
Eric Laurentd60560a2015-04-10 11:31:20 -07004440 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4441 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004442 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4443 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004444 return INVALID_OPERATION;
4445 }
4446
François Gaffie11d30102018-11-02 16:09:09 +01004447 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004448 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004449 String8(source->ext.device.address),
4450 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004451 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004452 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004453 return BAD_VALUE;
4454 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004455
jiabin4ef93452019-09-10 14:29:54 -07004456 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004457
François Gaffieaaac0fd2018-11-22 17:56:39 +01004458 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004460 mEngine->getStreamTypeForAttributes(*attributes),
4461 mEngine->getProductStrategyForAttributes(*attributes),
4462 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004463
4464 status_t status = connectAudioSource(sourceDesc);
4465 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004466 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004467 }
4468 return status;
4469}
4470
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004471status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004472{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004473 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004474
4475 // make sure we only have one patch per source.
4476 disconnectAudioSource(sourceDesc);
4477
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004478 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004479 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4480 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4481 sourceDesc->srcDevice()->type(),
4482 String8(sourceDesc->srcDevice()->address().c_str()),
4483 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004484 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004485 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004486 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004487 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004488 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4489 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4490 return INVALID_OPERATION;
4491 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 PatchBuilder patchBuilder;
4493 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4494 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4495 status_t status =
4496 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4497 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4498 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4499 return INVALID_OPERATION;
4500 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004501 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4503 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4504 if (swOutput != 0) {
4505 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004506 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004507 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004508 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004509 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004510 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004511 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004512 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004513 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004514 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004515 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004516 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004517 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4518 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004519 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004520 if (delayMs != 0) {
4521 usleep(delayMs * 1000);
4522 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004523 } else {
4524 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4525 if (hwOutputDesc != 0) {
4526 // create Hwoutput and add to mHwOutputs
4527 } else {
4528 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4529 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004530 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004531 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004532
4533FailureSourceActive:
4534 swOutput->stop();
4535 releaseOutput(sourceDesc->portId());
4536FailureSourceAdded:
4537 sourceDesc->setSwOutput(nullptr);
4538FailureReleasePatch:
4539 releaseAudioPatchInternal(handle);
4540 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004541}
4542
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004543status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004544{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004545 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4546 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004547 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004548 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004549 return BAD_VALUE;
4550 }
4551 status_t status = disconnectAudioSource(sourceDesc);
4552
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004553 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004554 return status;
4555}
4556
Andy Hung2ddee192015-12-18 17:34:44 -08004557status_t AudioPolicyManager::setMasterMono(bool mono)
4558{
4559 if (mMasterMono == mono) {
4560 return NO_ERROR;
4561 }
4562 mMasterMono = mono;
4563 // if enabling mono we close all offloaded devices, which will invalidate the
4564 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4565 // for recreating the new AudioTrack as non-offloaded PCM.
4566 //
4567 // If disabling mono, we leave all tracks as is: we don't know which clients
4568 // and tracks are able to be recreated as offloaded. The next "song" should
4569 // play back offloaded.
4570 if (mMasterMono) {
4571 Vector<audio_io_handle_t> offloaded;
4572 for (size_t i = 0; i < mOutputs.size(); ++i) {
4573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4574 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4575 offloaded.push(desc->mIoHandle);
4576 }
4577 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004578 for (const auto& handle : offloaded) {
4579 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004580 }
4581 }
4582 // update master mono for all remaining outputs
4583 for (size_t i = 0; i < mOutputs.size(); ++i) {
4584 updateMono(mOutputs.keyAt(i));
4585 }
4586 return NO_ERROR;
4587}
4588
4589status_t AudioPolicyManager::getMasterMono(bool *mono)
4590{
4591 *mono = mMasterMono;
4592 return NO_ERROR;
4593}
4594
Eric Laurentac9cef52017-06-09 15:46:26 -07004595float AudioPolicyManager::getStreamVolumeDB(
4596 audio_stream_type_t stream, int index, audio_devices_t device)
4597{
jiabin9a3361e2019-10-01 09:38:30 -07004598 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004599}
4600
jiabin81772902018-04-02 17:52:27 -07004601status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4602 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004603 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004604{
Kriti Dang6537def2021-03-02 13:46:59 +01004605 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4606 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004607 return BAD_VALUE;
4608 }
Kriti Dang6537def2021-03-02 13:46:59 +01004609 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4610 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004611
4612 size_t formatsWritten = 0;
4613 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004614
Kriti Dang6537def2021-03-02 13:46:59 +01004615 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004616 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4617 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004618 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004619 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004620 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004621 bool formatEnabled = true;
4622 switch (forceUse) {
4623 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004624 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004625 break;
4626 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4627 formatEnabled = false;
4628 break;
4629 default: // AUTO or ALWAYS => true
4630 break;
jiabin81772902018-04-02 17:52:27 -07004631 }
4632 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4633 }
jiabin81772902018-04-02 17:52:27 -07004634 }
4635 return NO_ERROR;
4636}
4637
Kriti Dang6537def2021-03-02 13:46:59 +01004638status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4639 audio_format_t *surroundFormats) {
4640 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4641 return BAD_VALUE;
4642 }
4643 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4644 __func__, *numSurroundFormats, surroundFormats);
4645
4646 size_t formatsWritten = 0;
4647 size_t formatsMax = *numSurroundFormats;
4648 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4649
4650 // Return formats from all device profiles that have already been resolved by
4651 // checkOutputsForDevice().
4652 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4653 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4654 audio_devices_t deviceType = device->type();
4655 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4656 // returns formats reported by HDMI devices.
4657 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4658 continue;
4659 }
4660 // Formats reported by sink devices
4661 std::unordered_set<audio_format_t> formatset;
4662 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4663 formatset.insert(it->second.begin(), it->second.end());
4664 }
4665
4666 // Formats hard-coded in the in policy configuration file (if any).
4667 FormatVector encodedFormats = device->encodedFormats();
4668 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4669 // Filter the formats which are supported by the vendor hardware.
4670 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4671 if (mConfig.getSurroundFormats().count(*it) != 0) {
4672 formats.insert(*it);
4673 } else {
4674 for (const auto& pair : mConfig.getSurroundFormats()) {
4675 if (pair.second.count(*it) != 0) {
4676 formats.insert(pair.first);
4677 break;
4678 }
4679 }
4680 }
4681 }
4682 }
4683 *numSurroundFormats = formats.size();
4684 for (const auto& format: formats) {
4685 if (formatsWritten < formatsMax) {
4686 surroundFormats[formatsWritten++] = format;
4687 }
4688 }
4689 return NO_ERROR;
4690}
4691
jiabin81772902018-04-02 17:52:27 -07004692status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4693{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004694 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004695 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4696 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004697 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004698 return BAD_VALUE;
4699 }
4700
Mikhail Naganov100f0122018-11-29 11:22:16 -08004701 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4702 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004703 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004704 return INVALID_OPERATION;
4705 }
4706
Mikhail Naganov100f0122018-11-29 11:22:16 -08004707 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004708 return NO_ERROR;
4709 }
4710
Mikhail Naganov100f0122018-11-29 11:22:16 -08004711 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004712 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004713 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004714 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004715 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004716 }
4717 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004718 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004719 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004720 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004721 }
4722 }
4723
4724 sp<SwAudioOutputDescriptor> outputDesc;
4725 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004726 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4727 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004728 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4729 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004730 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004731 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004732 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4733 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4734 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004735 name.c_str(),
4736 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004737 if (status != NO_ERROR) {
4738 continue;
4739 }
4740 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4741 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4742 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004743 name.c_str(),
4744 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004745 profileUpdated |= (status == NO_ERROR);
4746 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004747 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004748 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004749 AUDIO_DEVICE_IN_HDMI);
4750 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4751 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004752 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004753 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004754 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4755 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4756 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004757 name.c_str(),
4758 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004759 if (status != NO_ERROR) {
4760 continue;
4761 }
4762 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4763 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4764 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004765 name.c_str(),
4766 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004767 profileUpdated |= (status == NO_ERROR);
4768 }
4769
jiabin81772902018-04-02 17:52:27 -07004770 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004771 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004772 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004773 }
4774
4775 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4776}
4777
Eric Laurent5ada82e2019-08-29 17:53:54 -07004778void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004779{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004780 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004781 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004782 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004783 }
4784}
4785
jiabin6012f912018-11-02 17:06:30 -07004786bool AudioPolicyManager::isHapticPlaybackSupported()
4787{
4788 for (const auto& hwModule : mHwModules) {
4789 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4790 for (const auto &outProfile : outputProfiles) {
4791 struct audio_port audioPort;
4792 outProfile->toAudioPort(&audioPort);
4793 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4794 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4795 return true;
4796 }
4797 }
4798 }
4799 }
4800 return false;
4801}
4802
Eric Laurent8340e672019-11-06 11:01:08 -08004803bool AudioPolicyManager::isCallScreenModeSupported()
4804{
4805 return getConfig().isCallScreenModeSupported();
4806}
4807
4808
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004809status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004810{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004811 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004812 if (!sourceDesc->isConnected()) {
4813 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4814 return NO_ERROR;
4815 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004816 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4817 if (swOutput != 0) {
4818 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004819 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004820 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004821 }
jiabinbce0c1d2020-10-05 11:20:18 -07004822 if (releaseOutput(sourceDesc->portId())) {
4823 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4824 // no need to release audio patch here but just return NO_ERROR.
4825 return NO_ERROR;
4826 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004827 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004828 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004829 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004830 // close Hwoutput and remove from mHwOutputs
4831 } else {
4832 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4833 }
4834 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004835 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4836 sourceDesc->disconnect();
4837 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004838}
4839
François Gaffiec005e562018-11-06 15:04:49 +01004840sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4841 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004842{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004843 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004844 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004845 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004846 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004847 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4848 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004849 source = sourceDesc;
4850 break;
4851 }
4852 }
4853 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004854}
4855
Eric Laurent39095982021-08-24 18:29:27 +02004856/* static */
4857bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
4858 switch (channels) {
4859 case AUDIO_CHANNEL_OUT_5POINT1:
4860 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
4861 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
4862 case AUDIO_CHANNEL_OUT_7POINT1:
4863 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
4864 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
4865 return true;
4866 default:
4867 return false;
4868 }
4869}
4870
Eric Laurentfa0f6742021-08-17 18:39:44 +02004871bool AudioPolicyManager::canBeSpatialized(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004872 const audio_config_t *config,
4873 const AudioDeviceTypeAddrVector &devices) const
4874{
4875 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
4876 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004877 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004878 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02004879 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
4880 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
4881 return false;
4882 }
4883 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
4884 return false;
4885 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004886 }
4887
4888 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02004889 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
4890 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004891 // to the specified devices must exist.
4892 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004893 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004894 if (profile == nullptr) {
4895 return false;
4896 }
4897
4898 // The caller can have the audio config criteria ignored by either passing a null ptr or
4899 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004900 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02004901 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02004902 // If the spatializer output is already opened, only channel masks included in the
4903 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02004904
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004905 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02004906 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004907 return false;
4908 }
Eric Laurent39095982021-08-24 18:29:27 +02004909 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02004910 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004911 != config->channel_mask) {
4912 return false;
4913 }
4914 }
4915 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004916 return true;
4917}
4918
4919void AudioPolicyManager::checkVirtualizerClientRoutes() {
4920 std::set<audio_stream_type_t> streamsToInvalidate;
4921 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02004922 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
4923 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004924 audio_attributes_t attr = client->attributes();
4925 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
4926 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4927 audio_config_base_t clientConfig = client->config();
4928 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02004929 if (desc != mSpatializerOutput
4930 && canBeSpatialized(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004931 streamsToInvalidate.insert(client->stream());
4932 }
4933 }
4934 }
4935
4936 for (audio_stream_type_t stream : streamsToInvalidate) {
4937 mpClientInterface->invalidateStream(stream);
4938 }
4939}
4940
Eric Laurentfa0f6742021-08-17 18:39:44 +02004941status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004942 const audio_attributes_t *attr,
4943 audio_io_handle_t *output) {
4944 *output = AUDIO_IO_HANDLE_NONE;
4945
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004946 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
4947 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
4948 audio_config_t *configPtr = nullptr;
4949 audio_config_t config;
4950 if (mixerConfig != nullptr) {
4951 config = audio_config_initializer(mixerConfig);
4952 configPtr = &config;
4953 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02004954 if (!canBeSpatialized(attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02004955 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004956 return BAD_VALUE;
4957 }
4958
4959 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02004960 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004961 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02004962 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02004963 return BAD_VALUE;
4964 }
4965
Eric Laurent39095982021-08-24 18:29:27 +02004966 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
4967 && configPtr != nullptr
4968 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
4969 *output = mSpatializerOutput->mIoHandle;
4970 ALOGV("%s returns current spatializer output %d", __func__, *output);
4971 return NO_ERROR;
4972 }
4973 mSpatializerOutput.clear();
4974 for (size_t i = 0; i < mOutputs.size(); i++) {
4975 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4976 if (!desc->isDuplicated() && desc->mProfile == profile) {
4977 mSpatializerOutput = desc;
4978 break;
4979 }
4980 }
4981 if (mSpatializerOutput == nullptr) {
4982 ALOGW("%s no opened spatializer output for profile %s",
4983 __func__, profile->getName().c_str());
4984 return BAD_VALUE;
4985 }
4986
4987 if (configPtr != nullptr
4988 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
4989 audio_config_base_t savedMixerConfig = {
4990 .sample_rate = mSpatializerOutput->getSamplingRate(),
4991 .format = mSpatializerOutput->getFormat(),
4992 .channel_mask = mSpatializerOutput->mMixerChannelMask,
4993 };
4994 DeviceVector savedDevices = mSpatializerOutput->devices();
4995
4996 closeOutput(mSpatializerOutput->mIoHandle);
4997 mSpatializerOutput.clear();
4998
4999 const sp<SwAudioOutputDescriptor> desc =
5000 new SwAudioOutputDescriptor(profile, mpClientInterface);
5001 status_t status = desc->open(nullptr, mixerConfig, devices,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005002 mEngine->getStreamTypeForAttributes(*attr),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02005003 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
Eric Laurent39095982021-08-24 18:29:27 +02005004 if (status != NO_ERROR) {
5005 ALOGW("%s failed opening output: status %d, output %d", __func__, status, *output);
5006 if (*output != AUDIO_IO_HANDLE_NONE) {
5007 desc->close();
5008 }
5009 // re open the spatializer output with previous channel mask
5010 status_t newStatus = desc->open(nullptr, &savedMixerConfig, savedDevices,
5011 mEngine->getStreamTypeForAttributes(*attr),
5012 AUDIO_OUTPUT_FLAG_SPATIALIZER, output);
5013 if (newStatus != NO_ERROR) {
5014 if (*output != AUDIO_IO_HANDLE_NONE) {
5015 desc->close();
5016 }
5017 ALOGE("%s failed to re-open mSpatializerOutput, status %d", __func__, newStatus);
5018 } else {
5019 mSpatializerOutput = desc;
5020 addOutput(*output, desc);
5021 }
5022 mPreviousOutputs = mOutputs;
5023 mpClientInterface->onAudioPortListUpdate();
5024 *output = AUDIO_IO_HANDLE_NONE;
5025 return status;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005026 }
Eric Laurent39095982021-08-24 18:29:27 +02005027 mSpatializerOutput = desc;
5028 addOutput(*output, desc);
5029 mPreviousOutputs = mOutputs;
5030 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005031 }
5032
5033 checkVirtualizerClientRoutes();
5034
Eric Laurent39095982021-08-24 18:29:27 +02005035 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005036 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005037 return NO_ERROR;
5038}
5039
Eric Laurentfa0f6742021-08-17 18:39:44 +02005040status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5041 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005042 return INVALID_OPERATION;
5043 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005044 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005045 return BAD_VALUE;
5046 }
Eric Laurent39095982021-08-24 18:29:27 +02005047
Eric Laurentfa0f6742021-08-17 18:39:44 +02005048 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005049
5050 checkVirtualizerClientRoutes();
5051
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005052 return NO_ERROR;
5053}
5054
Eric Laurente552edb2014-03-10 17:42:56 -07005055// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005056// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005057// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005058uint32_t AudioPolicyManager::nextAudioPortGeneration()
5059{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005060 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005061}
5062
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005063static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005064 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5065 !audioPolicyXmlConfigFile.empty()) {
5066 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5067 if (ret == NO_ERROR) {
5068 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005069 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005070 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005071 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005072 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005073}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005074
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005075AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5076 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005077 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005078 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005079 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005080 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005081 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005082 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005083 mAudioPortGeneration(1),
5084 mBeaconMuteRefCount(0),
5085 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005086 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005087 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005088 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005089 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005090{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005091}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005092
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005093AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5094 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5095{
5096 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005097}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005098
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005099void AudioPolicyManager::loadConfig() {
5100 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005101 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005102 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005103 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005104 //TODO: b/193496180 use spatializer flag at audio HAL when available
5105 getConfig().convertSpatializerFlag();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005106}
5107
5108status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005109 {
5110 auto engLib = EngineLibrary::load(
5111 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5112 if (!engLib) {
5113 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5114 return NO_INIT;
5115 }
5116 mEngine = engLib->createEngine();
5117 if (mEngine == nullptr) {
5118 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5119 return NO_INIT;
5120 }
François Gaffie2110e042015-03-24 08:41:51 +01005121 }
5122 mEngine->setObserver(this);
5123 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005124 if (status != NO_ERROR) {
5125 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5126 return status;
5127 }
François Gaffie2110e042015-03-24 08:41:51 +01005128
Eric Laurent1d69c872021-01-11 18:53:01 +01005129 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5130 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5131
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005132 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005133 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005134 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005135
Eric Laurent3a4311c2014-03-17 12:00:47 -07005136 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005137 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5138 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5139 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005140 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005141 }
jiabin9ff780e2018-03-19 18:19:52 -07005142 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005143 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005144 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005145 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005146 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005147 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005148 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005149 }
5150 }
5151 }
Eric Laurente552edb2014-03-10 17:42:56 -07005152
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005153 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005154
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005155 // Silence ALOGV statements
5156 property_set("log.tag." LOG_TAG, "D");
5157
Eric Laurente552edb2014-03-10 17:42:56 -07005158 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005159 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005160}
5161
Eric Laurente0720872014-03-11 09:30:41 -07005162AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005163{
Eric Laurente552edb2014-03-10 17:42:56 -07005164 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005165 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005166 }
5167 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005168 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005169 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005170 mAvailableOutputDevices.clear();
5171 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005172 mOutputs.clear();
5173 mInputs.clear();
5174 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005175 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005176 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005177}
5178
Eric Laurente0720872014-03-11 09:30:41 -07005179status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005180{
Eric Laurent87ffa392015-05-22 10:32:38 -07005181 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005182}
5183
Eric Laurente552edb2014-03-10 17:42:56 -07005184// ---
5185
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005186void AudioPolicyManager::onNewAudioModulesAvailable()
5187{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005188 DeviceVector newDevices;
5189 onNewAudioModulesAvailableInt(&newDevices);
5190 if (!newDevices.empty()) {
5191 nextAudioPortGeneration();
5192 mpClientInterface->onAudioPortListUpdate();
5193 }
5194}
5195
5196void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5197{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005198 for (const auto& hwModule : mHwModulesAll) {
5199 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5200 continue;
5201 }
5202 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5203 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5204 ALOGW("could not open HW module %s", hwModule->getName());
5205 continue;
5206 }
5207 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005208 // open all output streams needed to access attached devices.
5209 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005210 // This also validates mAvailableOutputDevices list
5211 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5212 if (!outProfile->canOpenNewIo()) {
5213 ALOGE("Invalid Output profile max open count %u for profile %s",
5214 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5215 continue;
5216 }
5217 if (!outProfile->hasSupportedDevices()) {
5218 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5219 continue;
5220 }
5221 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
5222 mTtsOutputAvailable = true;
5223 }
5224
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005225 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5226 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5227 sp<DeviceDescriptor> supportedDevice = 0;
5228 if (supportedDevices.contains(mDefaultOutputDevice)) {
5229 supportedDevice = mDefaultOutputDevice;
5230 } else {
5231 // choose first device present in profile's SupportedDevices also part of
5232 // mAvailableOutputDevices.
5233 if (availProfileDevices.isEmpty()) {
5234 continue;
5235 }
5236 supportedDevice = availProfileDevices.itemAt(0);
5237 }
5238 if (!mOutputDevicesAll.contains(supportedDevice)) {
5239 continue;
5240 }
5241 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5242 mpClientInterface);
5243 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005244 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5245 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005246 AUDIO_STREAM_DEFAULT,
5247 AUDIO_OUTPUT_FLAG_NONE, &output);
5248 if (status != NO_ERROR) {
5249 ALOGW("Cannot open output stream for devices %s on hw module %s",
5250 supportedDevice->toString().c_str(), hwModule->getName());
5251 continue;
5252 }
5253 for (const auto &device : availProfileDevices) {
5254 // give a valid ID to an attached device once confirmed it is reachable
5255 if (!device->isAttached()) {
5256 device->attach(hwModule);
5257 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005258 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005259 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005260 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5261 }
5262 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005263 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005264 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5265 mPrimaryOutput = outputDesc;
5266 }
Eric Laurent39095982021-08-24 18:29:27 +02005267 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005268 outputDesc->close();
5269 } else {
5270 addOutput(output, outputDesc);
5271 setOutputDevices(outputDesc,
5272 DeviceVector(supportedDevice),
5273 true,
5274 0,
5275 NULL);
5276 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005277 }
5278 // open input streams needed to access attached devices to validate
5279 // mAvailableInputDevices list
5280 for (const auto& inProfile : hwModule->getInputProfiles()) {
5281 if (!inProfile->canOpenNewIo()) {
5282 ALOGE("Invalid Input profile max open count %u for profile %s",
5283 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5284 continue;
5285 }
5286 if (!inProfile->hasSupportedDevices()) {
5287 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5288 continue;
5289 }
5290 // chose first device present in profile's SupportedDevices also part of
5291 // available input devices
5292 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5293 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5294 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005295 ALOGV("%s: Input device list is empty! for profile %s",
5296 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005297 continue;
5298 }
5299 sp<AudioInputDescriptor> inputDesc =
5300 new AudioInputDescriptor(inProfile, mpClientInterface);
5301
5302 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5303 status_t status = inputDesc->open(nullptr,
5304 availProfileDevices.itemAt(0),
5305 AUDIO_SOURCE_MIC,
5306 AUDIO_INPUT_FLAG_NONE,
5307 &input);
5308 if (status != NO_ERROR) {
5309 ALOGW("Cannot open input stream for device %s on hw module %s",
5310 availProfileDevices.toString().c_str(),
5311 hwModule->getName());
5312 continue;
5313 }
5314 for (const auto &device : availProfileDevices) {
5315 // give a valid ID to an attached device once confirmed it is reachable
5316 if (!device->isAttached()) {
5317 device->attach(hwModule);
5318 device->importAudioPortAndPickAudioProfile(inProfile, true);
5319 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005320 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005321 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5322 }
5323 }
5324 inputDesc->close();
5325 }
5326 }
5327}
5328
Eric Laurent98e38192018-02-15 18:31:53 -08005329void AudioPolicyManager::addOutput(audio_io_handle_t output,
5330 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005331{
Eric Laurent1c333e22014-05-20 10:48:17 -07005332 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005333 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005334 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005335 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005337}
5338
François Gaffie53615e22015-03-19 09:24:12 +01005339void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5340{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005341 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5342 ALOGV("%s: removing primary output", __func__);
5343 mPrimaryOutput = nullptr;
5344 }
François Gaffie53615e22015-03-19 09:24:12 +01005345 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005346 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005347}
5348
Eric Laurent98e38192018-02-15 18:31:53 -08005349void AudioPolicyManager::addInput(audio_io_handle_t input,
5350 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005351{
Eric Laurent1c333e22014-05-20 10:48:17 -07005352 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005353 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005354}
Eric Laurente552edb2014-03-10 17:42:56 -07005355
François Gaffie11d30102018-11-02 16:09:09 +01005356status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005357 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005358 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005359{
François Gaffie11d30102018-11-02 16:09:09 +01005360 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005361 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005362 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005363
François Gaffie11d30102018-11-02 16:09:09 +01005364 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005365 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005366 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005367 }
Eric Laurente552edb2014-03-10 17:42:56 -07005368
Eric Laurent3b73df72014-03-11 09:06:29 -07005369 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005370 // first call getAudioPort to get the supported attributes from the HAL
5371 struct audio_port_v7 port = {};
5372 device->toAudioPort(&port);
5373 status_t status = mpClientInterface->getAudioPort(&port);
5374 if (status == NO_ERROR) {
5375 device->importAudioPort(port);
5376 }
5377
5378 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005379 for (size_t i = 0; i < mOutputs.size(); i++) {
5380 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005381 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005382 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005383 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5384 mOutputs.keyAt(i), device->toString().c_str());
5385 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005386 }
5387 }
5388 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005389 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005390 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005391 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5392 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005393 if (profile->supportsDevice(device)) {
5394 profiles.add(profile);
5395 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5396 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005397 }
5398 }
5399 }
5400
Eric Laurent7b279bb2015-12-14 10:18:23 -08005401 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005402
Eric Laurente552edb2014-03-10 17:42:56 -07005403 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005404 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005405 return BAD_VALUE;
5406 }
5407
5408 // open outputs for matching profiles if needed. Direct outputs are also opened to
5409 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5410 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005411 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005412
5413 // nothing to do if one output is already opened for this profile
5414 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005415 for (j = 0; j < outputs.size(); j++) {
5416 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005417 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005418 // matching profile: save the sample rates, format and channel masks supported
5419 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005420 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005421 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005422 }
Eric Laurente552edb2014-03-10 17:42:56 -07005423 break;
5424 }
5425 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005426 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005427 continue;
5428 }
5429
Eric Laurent3974e3b2017-12-07 17:58:43 -08005430 if (!profile->canOpenNewIo()) {
5431 ALOGW("Max Output number %u already opened for this profile %s",
5432 profile->maxOpenCount, profile->getTagName().c_str());
5433 continue;
5434 }
5435
Eric Laurent83efe1c2017-07-09 16:51:08 -07005436 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005437 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005438 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5439 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005440 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005441 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005442 profiles.removeAt(profile_index);
5443 profile_index--;
5444 } else {
5445 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005446 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005447 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005448 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5449 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005450 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005451 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005452
François Gaffie11d30102018-11-02 16:09:09 +01005453 if (device_distinguishes_on_address(deviceType)) {
5454 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5455 device->toString().c_str());
5456 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5457 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005458 }
Eric Laurente552edb2014-03-10 17:42:56 -07005459 ALOGV("checkOutputsForDevice(): adding output %d", output);
5460 }
5461 }
5462
5463 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005464 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 return BAD_VALUE;
5466 }
Eric Laurentd4692962014-05-05 18:13:44 -07005467 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005468 // check if one opened output is not needed any more after disconnecting one device
5469 for (size_t i = 0; i < mOutputs.size(); i++) {
5470 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005471 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005472 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005473 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffied7a5f2d2021-10-20 17:07:13 +02005474 && desc->containsSingleDeviceSupportingEncodedFormats(device)
5475 && !mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
François Gaffie11d30102018-11-02 16:09:09 +01005476 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005477 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005478 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5479 mOutputs.keyAt(i));
5480 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005481 }
Eric Laurente552edb2014-03-10 17:42:56 -07005482 }
5483 }
Eric Laurentd4692962014-05-05 18:13:44 -07005484 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005485 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005486 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5487 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005488 if (!profile->supportsDevice(device)) {
5489 continue;
5490 }
5491 ALOGV("checkOutputsForDevice(): "
5492 "clearing direct output profile %zu on module %s",
5493 j, hwModule->getName());
5494 profile->clearAudioProfiles();
5495 if (!profile->hasDynamicAudioProfile()) {
5496 continue;
5497 }
5498 // When a device is disconnected, if there is an IOProfile that contains dynamic
5499 // profiles and supports the disconnected device, call getAudioPort to repopulate
5500 // the capabilities of the devices that is supported by the IOProfile.
5501 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5502 if (supportedDevice == device ||
5503 !mAvailableOutputDevices.contains(supportedDevice)) {
5504 continue;
5505 }
5506 struct audio_port_v7 port;
5507 supportedDevice->toAudioPort(&port);
5508 status_t status = mpClientInterface->getAudioPort(&port);
5509 if (status == NO_ERROR) {
5510 supportedDevice->importAudioPort(port);
5511 }
Eric Laurente552edb2014-03-10 17:42:56 -07005512 }
5513 }
5514 }
5515 }
5516 return NO_ERROR;
5517}
5518
François Gaffie11d30102018-11-02 16:09:09 +01005519status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005520 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005521{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005522 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005523
François Gaffie11d30102018-11-02 16:09:09 +01005524 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005525 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005526 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005527 }
5528
Eric Laurentd4692962014-05-05 18:13:44 -07005529 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005530 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005531 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005532 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005533 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005534 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005535 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005536 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005537
François Gaffie11d30102018-11-02 16:09:09 +01005538 if (profile->supportsDevice(device)) {
5539 profiles.add(profile);
5540 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5541 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005542 }
5543 }
5544 }
5545
Eric Laurent0dd51852019-04-19 18:18:58 -07005546 if (profiles.isEmpty()) {
5547 ALOGW("%s: No input profile available for device %s",
5548 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005549 return BAD_VALUE;
5550 }
5551
5552 // open inputs for matching profiles if needed. Direct inputs are also opened to
5553 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5554 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5555
Eric Laurent1c333e22014-05-20 10:48:17 -07005556 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005557
Eric Laurentd4692962014-05-05 18:13:44 -07005558 // nothing to do if one input is already opened for this profile
5559 size_t input_index;
5560 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5561 desc = mInputs.valueAt(input_index);
5562 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005563 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005564 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005565 }
Eric Laurentd4692962014-05-05 18:13:44 -07005566 break;
5567 }
5568 }
5569 if (input_index != mInputs.size()) {
5570 continue;
5571 }
5572
Eric Laurent3974e3b2017-12-07 17:58:43 -08005573 if (!profile->canOpenNewIo()) {
5574 ALOGW("Max Input number %u already opened for this profile %s",
5575 profile->maxOpenCount, profile->getTagName().c_str());
5576 continue;
5577 }
5578
Eric Laurentfe231122017-11-17 17:48:06 -08005579 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005580 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005581 status_t status = desc->open(nullptr,
5582 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005583 AUDIO_SOURCE_MIC,
5584 AUDIO_INPUT_FLAG_NONE,
5585 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005586
Eric Laurentcf2c0212014-07-25 16:20:43 -07005587 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005588 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005589 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005590 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005591 mpClientInterface->setParameters(input, String8(param));
5592 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005593 }
François Gaffie11d30102018-11-02 16:09:09 +01005594 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005595 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005596 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005597 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005598 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005599 }
5600
Eric Laurent0dd51852019-04-19 18:18:58 -07005601 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005602 addInput(input, desc);
5603 }
5604 } // endif input != 0
5605
Eric Laurentcf2c0212014-07-25 16:20:43 -07005606 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005607 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005608 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005609 profiles.removeAt(profile_index);
5610 profile_index--;
5611 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005612 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005613 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005614 }
Eric Laurentd4692962014-05-05 18:13:44 -07005615 ALOGV("checkInputsForDevice(): adding input %d", input);
5616 }
5617 } // end scan profiles
5618
5619 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005620 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005621 return BAD_VALUE;
5622 }
5623 } else {
5624 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005625 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005626 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005627 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005628 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005629 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005630 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005631 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005632 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5633 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005634 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005635 }
5636 }
5637 }
5638 } // end disconnect
5639
5640 return NO_ERROR;
5641}
5642
5643
Eric Laurente0720872014-03-11 09:30:41 -07005644void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005645{
5646 ALOGV("closeOutput(%d)", output);
5647
François Gaffie1c878552018-11-22 16:53:21 +01005648 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5649 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005650 ALOGW("closeOutput() unknown output %d", output);
5651 return;
5652 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005653 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005654 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005655
Eric Laurente552edb2014-03-10 17:42:56 -07005656 // look for duplicated outputs connected to the output being removed.
5657 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005658 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5659 if (dupOutput->isDuplicated() &&
5660 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5661 sp<SwAudioOutputDescriptor> remainingOutput =
5662 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005663 // As all active tracks on duplicated output will be deleted,
5664 // and as they were also referenced on the other output, the reference
5665 // count for their stream type must be adjusted accordingly on
5666 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005667 const bool wasActive = remainingOutput->isActive();
5668 // Note: no-op on the closing output where all clients has already been set inactive
5669 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005670 // stop() will be a no op if the output is still active but is needed in case all
5671 // active streams refcounts where cleared above
5672 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005673 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005674 }
Eric Laurente552edb2014-03-10 17:42:56 -07005675 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5676 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5677
5678 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005679 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005680 }
5681 }
5682
Eric Laurent05b90f82014-08-27 15:32:29 -07005683 nextAudioPortGeneration();
5684
François Gaffie1c878552018-11-22 16:53:21 +01005685 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005686 if (index >= 0) {
5687 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005688 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5689 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005690 mAudioPatches.removeItemsAt(index);
5691 mpClientInterface->onAudioPatchListUpdate();
5692 }
5693
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005694 if (closingOutputWasActive) {
5695 closingOutput->stop();
5696 }
François Gaffie1c878552018-11-22 16:53:21 +01005697 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005698
François Gaffie53615e22015-03-19 09:24:12 +01005699 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005700 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005701
5702 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5703 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005704 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005705 bool directOutputOpen = false;
5706 for (size_t i = 0; i < mOutputs.size(); i++) {
5707 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5708 directOutputOpen = true;
5709 break;
5710 }
5711 }
5712 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005713 ALOGV("no direct outputs open, reset MSD patches");
5714 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5715 // how output devices for patching are resolved. Avoid by caching and reusing the
5716 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5717 // devices to patch to. This may be complicated by the fact that devices may become
5718 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005719 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005720 }
5721 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005722}
5723
5724void AudioPolicyManager::closeInput(audio_io_handle_t input)
5725{
5726 ALOGV("closeInput(%d)", input);
5727
5728 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5729 if (inputDesc == NULL) {
5730 ALOGW("closeInput() unknown input %d", input);
5731 return;
5732 }
5733
Eric Laurent6a94d692014-05-20 11:18:06 -07005734 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005735
François Gaffie11d30102018-11-02 16:09:09 +01005736 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005737 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005738 if (index >= 0) {
5739 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005740 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5741 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005742 mAudioPatches.removeItemsAt(index);
5743 mpClientInterface->onAudioPatchListUpdate();
5744 }
5745
Eric Laurentfe231122017-11-17 17:48:06 -08005746 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005747 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005748
François Gaffie11d30102018-11-02 16:09:09 +01005749 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5750 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005751 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005752 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005753 }
Eric Laurente552edb2014-03-10 17:42:56 -07005754}
5755
François Gaffie11d30102018-11-02 16:09:09 +01005756SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5757 const DeviceVector &devices,
5758 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005759{
5760 SortedVector<audio_io_handle_t> outputs;
5761
François Gaffie11d30102018-11-02 16:09:09 +01005762 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005763 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005764 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005765 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005766 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005767 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005768 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005769 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005770 outputs.add(openOutputs.keyAt(i));
5771 }
5772 }
5773 return outputs;
5774}
5775
Mikhail Naganov37977152018-07-11 15:54:44 -07005776void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5777{
5778 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5779 // output is suspended before any tracks are moved to it
5780 checkA2dpSuspend();
5781 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005782 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005783 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005784 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005785 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005786 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5787 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5788 // configuration changes will ultimately be rerouted correctly. We can still avoid
5789 // unnecessary rerouting by caching and reusing the arguments to
5790 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5791 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005792 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005793 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005794 // an event that changed routing likely occurred, inform upper layers
5795 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005796}
5797
François Gaffiec005e562018-11-06 15:04:49 +01005798bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5799 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005800{
François Gaffiec005e562018-11-06 15:04:49 +01005801 return mEngine->getProductStrategyForAttributes(lAttr) ==
5802 mEngine->getProductStrategyForAttributes(rAttr);
5803}
5804
Francois Gaffieff1eb522020-05-06 18:37:04 +02005805void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5806{
5807 for (size_t i = 0; i < mAudioSources.size(); i++) {
5808 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5809 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005810 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5811 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005812 connectAudioSource(sourceDesc);
5813 }
5814 }
5815}
5816
5817void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5818{
5819 for (size_t i = 0; i < mAudioSources.size(); i++) {
5820 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5821 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5822 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5823 disconnectAudioSource(sourceDesc);
5824 }
5825 }
5826}
5827
François Gaffiec005e562018-11-06 15:04:49 +01005828void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5829{
5830 auto psId = mEngine->getProductStrategyForAttributes(attr);
5831
5832 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5833 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005834
François Gaffie11d30102018-11-02 16:09:09 +01005835 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5836 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005837
Eric Laurentc209fe42020-06-05 18:11:23 -07005838 uint32_t maxLatency = 0;
5839 bool invalidate = false;
5840 // take into account dynamic audio policies related changes: if a client is now associated
5841 // to a different policy mix than at creation time, invalidate corresponding stream
5842 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5843 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5844 if (desc->isDuplicated()) {
5845 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005846 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005847 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5848 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5849 continue;
5850 }
5851 sp<AudioPolicyMix> primaryMix;
5852 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5853 client->flags(), primaryMix, nullptr);
5854 if (status != OK) {
5855 continue;
5856 }
yucliuf4de36d2020-09-14 14:57:56 -07005857 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005858 invalidate = true;
5859 if (desc->isStrategyActive(psId)) {
5860 maxLatency = desc->latency();
5861 }
5862 break;
5863 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005864 }
5865 }
5866
Eric Laurentc209fe42020-06-05 18:11:23 -07005867 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005868 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5869 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005870 for (audio_io_handle_t srcOut : srcOutputs) {
5871 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005872 if (desc == nullptr) continue;
5873
5874 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005875 maxLatency = desc->latency();
5876 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005877
5878 if (invalidate) continue;
5879
5880 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005881 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005882 // a client on a non direct outputs has necessarily a linear PCM format
5883 // so we can call selectOutput() safely
5884 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5885 client->flags(),
5886 client->config().format,
5887 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005888 client->config().sample_rate,
5889 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005890 if (newOutput != srcOut) {
5891 invalidate = true;
5892 break;
5893 }
5894 } else {
5895 sp<IOProfile> profile = getProfileForOutput(newDevices,
5896 client->config().sample_rate,
5897 client->config().format,
5898 client->config().channel_mask,
5899 client->flags(),
5900 true /* directOnly */);
5901 if (profile != desc->mProfile) {
5902 invalidate = true;
5903 break;
5904 }
5905 }
5906 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005907 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005908
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005909 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005910 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005911 std::to_string(srcOutputs[0]).c_str(),
5912 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005913 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005914 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005915 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005916 if (desc == nullptr) continue;
5917
5918 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005919 setStrategyMute(psId, true, desc);
5920 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005921 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005922 }
François Gaffiec005e562018-11-06 15:04:49 +01005923 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005924 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005925 connectAudioSource(source);
5926 }
Eric Laurente552edb2014-03-10 17:42:56 -07005927 }
5928
François Gaffiec005e562018-11-06 15:04:49 +01005929 // Move effects associated to this stream from previous output to new output
5930 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005931 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005932 }
François Gaffiec005e562018-11-06 15:04:49 +01005933 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005934 if (invalidate) {
5935 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5936 mpClientInterface->invalidateStream(stream);
5937 }
Eric Laurente552edb2014-03-10 17:42:56 -07005938 }
5939 }
5940}
5941
Eric Laurente0720872014-03-11 09:30:41 -07005942void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005943{
François Gaffiec005e562018-11-06 15:04:49 +01005944 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5945 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5946 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005947 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005948 }
Eric Laurente552edb2014-03-10 17:42:56 -07005949}
5950
Kevin Rocard153f92d2018-12-18 18:33:28 -08005951void AudioPolicyManager::checkSecondaryOutputs() {
5952 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00005953 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005954 for (size_t i = 0; i < mOutputs.size(); i++) {
5955 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5956 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005957 sp<AudioPolicyMix> primaryMix;
5958 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07005959 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07005960 client->flags(), primaryMix, &secondaryMixes);
5961 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5962 for (auto &secondaryMix : secondaryMixes) {
5963 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5964 if (outputDesc != nullptr &&
5965 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5966 secondaryDescs.push_back(outputDesc);
5967 }
5968 }
5969
jiabin10a03f12021-05-07 23:46:28 +00005970 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005971 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00005972 } else if (!std::equal(
5973 client->getSecondaryOutputs().begin(),
5974 client->getSecondaryOutputs().end(),
5975 secondaryDescs.begin(), secondaryDescs.end())) {
5976 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5977 std::vector<audio_io_handle_t> secondaryOutputIds;
5978 for (const auto& secondaryDesc : secondaryDescs) {
5979 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5980 weakSecondaryDescs.push_back(secondaryDesc);
5981 }
5982 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5983 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005984 }
5985 }
5986 }
jiabin10a03f12021-05-07 23:46:28 +00005987 if (!trackSecondaryOutputs.empty()) {
5988 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5989 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005990 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00005991 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005992 mpClientInterface->invalidateStream(stream);
5993 }
5994}
5995
Eric Laurent2517af32020-11-25 15:31:27 +01005996bool AudioPolicyManager::isScoRequestedForComm() const {
5997 AudioDeviceTypeAddrVector devices;
5998 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5999 for (const auto &device : devices) {
6000 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6001 return true;
6002 }
6003 }
6004 return false;
6005}
6006
Eric Laurente0720872014-03-11 09:30:41 -07006007void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006008{
François Gaffie53615e22015-03-19 09:24:12 +01006009 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006010 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006011 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006012 return;
6013 }
6014
Eric Laurent3a4311c2014-03-17 12:00:47 -07006015 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006016 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6017 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006018 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006019
6020 // if suspended, restore A2DP output if:
6021 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006022 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006023 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006024 //
Eric Laurentf732e072016-08-03 19:30:28 -07006025 // if not suspended, suspend A2DP output if:
6026 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006027 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006028 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006029 //
6030 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006031 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006032 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006033 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006034 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006035
6036 mpClientInterface->restoreOutput(a2dpOutput);
6037 mA2dpSuspended = false;
6038 }
6039 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006040 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006041 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006042 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006043 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006044
6045 mpClientInterface->suspendOutput(a2dpOutput);
6046 mA2dpSuspended = true;
6047 }
6048 }
6049}
6050
François Gaffie11d30102018-11-02 16:09:09 +01006051DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6052 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006053{
François Gaffie11d30102018-11-02 16:09:09 +01006054 DeviceVector devices;
6055
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006056 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006057 if (index >= 0) {
6058 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006059 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006060 ALOGV("%s device %s forced by patch %d", __func__,
6061 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6062 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006063 }
6064 }
6065
Dean Wheatley514b4312020-06-17 21:45:00 +10006066 // Do not retrieve engine device for outputs through MSD
6067 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6068 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6069 return outputDesc->devices();
6070 }
6071
Eric Laurent97ac8712018-07-27 18:59:02 -07006072 // Honor explicit routing requests only if no client using default routing is active on this
6073 // input: a specific app can not force routing for other apps by setting a preferred device.
6074 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006075 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006076 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006077 if (device != nullptr) {
6078 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006079 }
6080
François Gaffiea807ef92018-11-05 10:44:33 +01006081 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6082 // of setForceUse / Default Bus device here
6083 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6084 if (device != nullptr) {
6085 return DeviceVector(device);
6086 }
6087
François Gaffiec005e562018-11-06 15:04:49 +01006088 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6089 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6090 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306091 auto hasStreamActive = [&](auto stream) {
6092 return hasStream(streams, stream) && isStreamActive(stream, 0);
6093 };
Eric Laurent484e9272018-06-07 17:29:23 -07006094
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306095 auto doGetOutputDevicesForVoice = [&]() {
6096 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6097 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6098 (isInCall() ||
6099 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc));
6100 };
6101
6102 // With low-latency playing on speaker, music on WFD, when the first low-latency
6103 // output is stopped, getNewOutputDevices checks for a product strategy
6104 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006105 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306106 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6107 // stream is associated to the output descriptor.
6108 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6109 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6110 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6111 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006112 // Retrieval of devices for voice DL is done on primary output profile, cannot
6113 // check the route (would force modifying configuration file for this profile)
6114 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6115 break;
6116 }
Eric Laurente552edb2014-03-10 17:42:56 -07006117 }
François Gaffiec005e562018-11-06 15:04:49 +01006118 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006119 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006120}
6121
François Gaffie11d30102018-11-02 16:09:09 +01006122sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6123 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006124{
François Gaffie11d30102018-11-02 16:09:09 +01006125 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006126
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006127 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006128 if (index >= 0) {
6129 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006130 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006131 ALOGV("getNewInputDevice() device %s forced by patch %d",
6132 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6133 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006134 }
6135 }
6136
Eric Laurent97ac8712018-07-27 18:59:02 -07006137 // Honor explicit routing requests only if no client using default routing is active on this
6138 // input: a specific app can not force routing for other apps by setting a preferred device.
6139 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006140 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6141 if (device != nullptr) {
6142 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006143 }
6144
Eric Laurentdc95a252018-04-12 12:46:56 -07006145 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006146 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006147 audio_attributes_t attributes;
6148 uid_t uid;
6149 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6150 if (topClient != nullptr) {
6151 attributes = topClient->attributes();
6152 uid = topClient->uid();
6153 } else {
6154 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6155 uid = 0;
6156 }
6157
Francois Gaffie716e1432019-01-14 16:58:59 +01006158 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6159 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006160 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006161 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006162 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006163 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006164
Eric Laurente552edb2014-03-10 17:42:56 -07006165 return device;
6166}
6167
Eric Laurent794fde22016-03-11 09:50:45 -08006168bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6169 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006170 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006171}
6172
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006173DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006174 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006175 // getOutputDevicesForStream's behavior for invalid streams.
6176 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6177 // device for music stream), but we want to return the empty set.
6178 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006179 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006180 }
François Gaffie11d30102018-11-02 16:09:09 +01006181 DeviceVector activeDevices;
6182 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006183 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6184 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006185 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006186 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006187 }
François Gaffiec005e562018-11-06 15:04:49 +01006188 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006189 devices.merge(curDevices);
6190 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006191 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006192 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006193 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006194 }
6195 }
Eric Laurente552edb2014-03-10 17:42:56 -07006196 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006197
Eric Laurentb0688d62018-08-14 15:49:18 -07006198 // Favor devices selected on active streams if any to report correct device in case of
6199 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006200 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006201 devices = activeDevices;
6202 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006203 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6204 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006205 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006206 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006207 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006208 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006209 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006210 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006211}
6212
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006213status_t AudioPolicyManager::getDevicesForAttributes(
6214 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6215 if (devices == nullptr) {
6216 return BAD_VALUE;
6217 }
6218 // check dynamic policies but only for primary descriptors (secondary not used for audible
6219 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006220 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006221 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006222 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006223 if (status != OK) {
6224 return status;
6225 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006226 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6227 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6228 devices->push_back(device);
6229 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006230 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006231 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6232 for (const auto& device : curDevices) {
6233 devices->push_back(device->getDeviceTypeAddr());
6234 }
6235 return NO_ERROR;
6236}
6237
Eric Laurente0720872014-03-11 09:30:41 -07006238void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006239 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006240 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006241 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006242 updateDevicesAndOutputs();
6243 break;
6244 default:
6245 break;
6246 }
6247}
6248
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006249uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006250
6251 // skip beacon mute management if a dedicated TTS output is available
6252 if (mTtsOutputAvailable) {
6253 return 0;
6254 }
6255
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006256 switch(event) {
6257 case STARTING_OUTPUT:
6258 mBeaconMuteRefCount++;
6259 break;
6260 case STOPPING_OUTPUT:
6261 if (mBeaconMuteRefCount > 0) {
6262 mBeaconMuteRefCount--;
6263 }
6264 break;
6265 case STARTING_BEACON:
6266 mBeaconPlayingRefCount++;
6267 break;
6268 case STOPPING_BEACON:
6269 if (mBeaconPlayingRefCount > 0) {
6270 mBeaconPlayingRefCount--;
6271 }
6272 break;
6273 }
6274
6275 if (mBeaconMuteRefCount > 0) {
6276 // any playback causes beacon to be muted
6277 return setBeaconMute(true);
6278 } else {
6279 // no other playback: unmute when beacon starts playing, mute when it stops
6280 return setBeaconMute(mBeaconPlayingRefCount == 0);
6281 }
6282}
6283
6284uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6285 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6286 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6287 // keep track of muted state to avoid repeating mute/unmute operations
6288 if (mBeaconMuted != mute) {
6289 // mute/unmute AUDIO_STREAM_TTS on all outputs
6290 ALOGV("\t muting %d", mute);
6291 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006292 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006293 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006295 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006296 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006297 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006298 maxLatency = latency;
6299 }
6300 }
6301 mBeaconMuted = mute;
6302 return maxLatency;
6303 }
6304 return 0;
6305}
6306
Eric Laurente0720872014-03-11 09:30:41 -07006307void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006308{
François Gaffiec005e562018-11-06 15:04:49 +01006309 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006310 mPreviousOutputs = mOutputs;
6311}
6312
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006313uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006314 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006315 uint32_t delayMs)
6316{
6317 // mute/unmute strategies using an incompatible device combination
6318 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6319 // if unmuting, unmute only after the specified delay
6320 if (outputDesc->isDuplicated()) {
6321 return 0;
6322 }
6323
6324 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006325 DeviceVector devices = outputDesc->devices();
6326 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006327
François Gaffiec005e562018-11-06 15:04:49 +01006328 auto productStrategies = mEngine->getOrderedProductStrategies();
6329 for (const auto &productStrategy : productStrategies) {
6330 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6331 DeviceVector curDevices =
6332 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6333 curDevices = curDevices.filter(outputDesc->supportedDevices());
6334 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006335 bool doMute = false;
6336
François Gaffiec005e562018-11-06 15:04:49 +01006337 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006338 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006339 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6340 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006341 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006342 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006343 }
Eric Laurent99401132014-05-07 19:48:15 -07006344 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006345 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006346 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006347 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006348 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006349 continue;
6350 }
François Gaffiec005e562018-11-06 15:04:49 +01006351 ALOGVV("%s() %s (curDevice %s)", __func__,
6352 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6353 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6354 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006355 if (mute) {
6356 // FIXME: should not need to double latency if volume could be applied
6357 // immediately by the audioflinger mixer. We must account for the delay
6358 // between now and the next time the audioflinger thread for this output
6359 // will process a buffer (which corresponds to one buffer size,
6360 // usually 1/2 or 1/4 of the latency).
6361 if (muteWaitMs < desc->latency() * 2) {
6362 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006363 }
6364 }
6365 }
6366 }
6367 }
6368 }
6369
Eric Laurent99401132014-05-07 19:48:15 -07006370 // temporary mute output if device selection changes to avoid volume bursts due to
6371 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006372 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006373 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006374
Eric Laurentdc462862016-07-19 12:29:53 -07006375 if (muteWaitMs < tempMuteWaitMs) {
6376 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006377 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006378
6379 // If recommended duration is defined, replace temporary mute duration to avoid
6380 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6381 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6382 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6383 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6384 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6385
François Gaffieaaac0fd2018-11-22 17:56:39 +01006386 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6387 // make sure that we do not start the temporary mute period too early in case of
6388 // delayed device change
6389 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6390 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006391 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006392 }
6393 }
6394
Eric Laurente552edb2014-03-10 17:42:56 -07006395 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6396 if (muteWaitMs > delayMs) {
6397 muteWaitMs -= delayMs;
6398 usleep(muteWaitMs * 1000);
6399 return muteWaitMs;
6400 }
6401 return 0;
6402}
6403
François Gaffie11d30102018-11-02 16:09:09 +01006404uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6405 const DeviceVector &devices,
6406 bool force,
6407 int delayMs,
6408 audio_patch_handle_t *patchHandle,
6409 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006410{
François Gaffie11d30102018-11-02 16:09:09 +01006411 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006412 uint32_t muteWaitMs;
6413
6414 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006415 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6416 nullptr /* patchHandle */, requiresMuteCheck);
6417 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6418 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006419 return muteWaitMs;
6420 }
Eric Laurente552edb2014-03-10 17:42:56 -07006421
6422 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006423 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006424 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006425
François Gaffie11d30102018-11-02 16:09:09 +01006426 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6427
6428 if (!filteredDevices.isEmpty()) {
6429 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006430 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006431
6432 // if the outputs are not materially active, there is no need to mute.
6433 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006434 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006435 } else {
6436 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6437 muteWaitMs = 0;
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439
Eric Laurent79ea9582020-06-11 18:49:24 -07006440 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6441 // output profile or if new device is not supported AND previous device(s) is(are) still
6442 // available (otherwise reset device must be done on the output)
6443 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6444 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6445 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6446 // restore previous device after evaluating strategy mute state
6447 outputDesc->setDevices(prevDevices);
6448 return muteWaitMs;
6449 }
6450
Eric Laurente552edb2014-03-10 17:42:56 -07006451 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006452 // the requested device is AUDIO_DEVICE_NONE
6453 // OR the requested device is the same as current device
6454 // AND force is not specified
6455 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006456 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006457 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006458 !force && outputDesc->getPatchHandle() != 0) {
6459 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6460 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006461 return muteWaitMs;
6462 }
6463
François Gaffie11d30102018-11-02 16:09:09 +01006464 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006465
Eric Laurente552edb2014-03-10 17:42:56 -07006466 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006467 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006468 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006469 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006470 PatchBuilder patchBuilder;
6471 patchBuilder.addSource(outputDesc);
6472 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6473 for (const auto &filteredDevice : filteredDevices) {
6474 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006475 }
6476
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006477 // Add half reported latency to delayMs when muteWaitMs is null in order
6478 // to avoid disordered sequence of muting volume and changing devices.
6479 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6480 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006481 }
Eric Laurente552edb2014-03-10 17:42:56 -07006482
6483 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006484 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006485
6486 return muteWaitMs;
6487}
6488
Eric Laurentc75307b2015-03-17 15:29:32 -07006489status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006490 int delayMs,
6491 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006492{
Eric Laurent6a94d692014-05-20 11:18:06 -07006493 ssize_t index;
6494 if (patchHandle) {
6495 index = mAudioPatches.indexOfKey(*patchHandle);
6496 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006497 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006498 }
6499 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006500 return INVALID_OPERATION;
6501 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006502 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006503 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006504 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006505 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006506 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006507 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006508 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006509 return status;
6510}
6511
6512status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006513 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006514 bool force,
6515 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006516{
6517 status_t status = NO_ERROR;
6518
Eric Laurent1f2f2232014-06-02 12:01:23 -07006519 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006520 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6521 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006522
François Gaffie11d30102018-11-02 16:09:09 +01006523 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006524 PatchBuilder patchBuilder;
6525 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006526 // AUDIO_SOURCE_HOTWORD is for internal use only:
6527 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006528 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6529 auto result = usecase;
6530 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6531 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6532 }
6533 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006534 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006535 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006536 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006537 }
6538 }
6539 return status;
6540}
6541
Eric Laurent6a94d692014-05-20 11:18:06 -07006542status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6543 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006544{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006545 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006546 ssize_t index;
6547 if (patchHandle) {
6548 index = mAudioPatches.indexOfKey(*patchHandle);
6549 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006550 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006551 }
6552 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006553 return INVALID_OPERATION;
6554 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006555 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006556 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006557 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006558 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006559 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006560 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006561 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006562 return status;
6563}
6564
François Gaffie11d30102018-11-02 16:09:09 +01006565sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006566 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006567 audio_format_t& format,
6568 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006569 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
6571 // Choose an input profile based on the requested capture parameters: select the first available
6572 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006573 //
6574 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6575 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006576
Glenn Kasten730b9262018-03-29 15:01:26 -07006577 sp<IOProfile> firstInexact;
6578 uint32_t updatedSamplingRate = 0;
6579 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6580 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006581 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006582 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006583 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006584 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006585 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006586 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006587 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006588 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006589 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006590 &channelMask /*updatedChannelMask*/,
6591 // FIXME ugly cast
6592 (audio_output_flags_t) flags,
6593 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006594 return profile;
6595 }
François Gaffie11d30102018-11-02 16:09:09 +01006596 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006597 samplingRate,
6598 &updatedSamplingRate,
6599 format,
6600 &updatedFormat,
6601 channelMask,
6602 &updatedChannelMask,
6603 // FIXME ugly cast
6604 (audio_output_flags_t) flags,
6605 false /*exactMatchRequiredForInputFlags*/)) {
6606 firstInexact = profile;
6607 }
6608
Eric Laurente552edb2014-03-10 17:42:56 -07006609 }
6610 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006611 if (firstInexact != nullptr) {
6612 samplingRate = updatedSamplingRate;
6613 format = updatedFormat;
6614 channelMask = updatedChannelMask;
6615 return firstInexact;
6616 }
Eric Laurente552edb2014-03-10 17:42:56 -07006617 return NULL;
6618}
6619
François Gaffieaaac0fd2018-11-22 17:56:39 +01006620float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6621 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006622 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006623 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006624{
jiabin9a3361e2019-10-01 09:38:30 -07006625 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006626
6627 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6628 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6629 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6630 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006631 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6632 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6633 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6634 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006635 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006636
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006637 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006638 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6639 mOutputs.isActive(ringVolumeSrc, 0)) {
6640 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006641 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006642 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006643 }
6644
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006645 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006646 if ((volumeSource != callVolumeSrc && (isInCall() ||
6647 mOutputs.isActiveLocally(callVolumeSrc))) &&
6648 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6649 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6650 volumeSource == alarmVolumeSrc ||
6651 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6652 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6653 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006654 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006655 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006656 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006657 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006658 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006659 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006660 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6661 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6662 // programmatically muted.
6663 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6664 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6665 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006666 bool exemptFromCapping =
6667 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6668 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006669 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6670 volumeSource, volumeDb);
6671 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006672 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6673 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6674 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006675 }
6676 }
Eric Laurente552edb2014-03-10 17:42:56 -07006677 // if a headset is connected, apply the following rules to ring tones and notifications
6678 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006679 // - always attenuate notifications volume by 6dB
6680 // - attenuate ring tones volume by 6dB unless music is not playing and
6681 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006682 // - if music is playing, always limit the volume to current music volume,
6683 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006684 if (!Intersection(deviceTypes,
6685 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6686 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006687 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6688 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006689 ((volumeSource == alarmVolumeSrc ||
6690 volumeSource == ringVolumeSrc) ||
6691 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6692 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6693 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6694 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6695 curves.canBeMuted()) {
6696
Eric Laurente552edb2014-03-10 17:42:56 -07006697 // when the phone is ringing we must consider that music could have been paused just before
6698 // by the music application and behave as if music was active if the last music track was
6699 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006700 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006701 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006702 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006703 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006704 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6705 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006706 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006707 float musicVolDb = computeVolume(musicCurves,
6708 musicVolumeSrc,
6709 musicCurves.getVolumeIndex(musicDevice),
6710 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006711 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6712 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6713 if (volumeDb > minVolDb) {
6714 volumeDb = minVolDb;
6715 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006716 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006717 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6718 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6719 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006720 // on A2DP, also ensure notification volume is not too low compared to media when
6721 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006722 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006723 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006724 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6725 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006726 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6727 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006728 }
6729 }
jiabin9a3361e2019-10-01 09:38:30 -07006730 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006731 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006732 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006733 }
6734 }
6735
François Gaffie43c73442018-11-08 08:21:55 +01006736 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006737}
6738
Eric Laurent3839bc02018-07-10 18:33:34 -07006739int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006740 VolumeSource fromVolumeSource,
6741 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006742{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006743 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006744 return srcIndex;
6745 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006746 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6747 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006748 float minSrc = (float)srcCurves.getVolumeIndexMin();
6749 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6750 float minDst = (float)dstCurves.getVolumeIndexMin();
6751 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006752
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006753 // preserve mute request or correct range
6754 if (srcIndex < minSrc) {
6755 if (srcIndex == 0) {
6756 return 0;
6757 }
6758 srcIndex = minSrc;
6759 } else if (srcIndex > maxSrc) {
6760 srcIndex = maxSrc;
6761 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006762 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6763}
6764
François Gaffieaaac0fd2018-11-22 17:56:39 +01006765status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6766 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006767 int index,
6768 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006769 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006770 int delayMs,
6771 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006772{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006773 // do not change actual attributes volume if the attributes is muted
6774 if (outputDesc->isMuted(volumeSource)) {
6775 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6776 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006777 return NO_ERROR;
6778 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006779 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6780 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6781 bool isVoiceVolSrc = callVolSrc == volumeSource;
6782 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6783
Eric Laurent2517af32020-11-25 15:31:27 +01006784 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006785 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006786 // if sco and call follow same curves, bypass forceUseForComm
6787 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006788 ((isVoiceVolSrc && isScoRequested) ||
6789 (isBtScoVolSrc && !isScoRequested))) {
6790 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6791 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006792 // Do not return an error here as AudioService will always set both voice call
6793 // and bluetooth SCO volumes due to stream aliasing.
6794 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006795 }
jiabin9a3361e2019-10-01 09:38:30 -07006796 if (deviceTypes.empty()) {
6797 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006798 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006799
jiabin9a3361e2019-10-01 09:38:30 -07006800 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6801 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006802 // Force VoIP volume to max for bluetooth SCO device except if muted
6803 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006804 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006805 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006806 }
jiabin9a3361e2019-10-01 09:38:30 -07006807 outputDesc->setVolume(
6808 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006809
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006810 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006811 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006812 // 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 +01006813 if (isVoiceVolSrc) {
6814 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006815 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006816 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006817 }
Eric Laurent18fba842016-03-31 14:41:26 -07006818 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006819 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6820 mLastVoiceVolume = voiceVolume;
6821 }
6822 }
Eric Laurente552edb2014-03-10 17:42:56 -07006823 return NO_ERROR;
6824}
6825
Eric Laurentc75307b2015-03-17 15:29:32 -07006826void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006827 const DeviceTypeSet& deviceTypes,
6828 int delayMs,
6829 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006830{
jiabincd510522020-01-22 09:40:55 -08006831 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006832 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6833 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6834 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006835 curves.getVolumeIndex(deviceTypes),
6836 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006837 }
6838}
6839
François Gaffiec005e562018-11-06 15:04:49 +01006840void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6841 bool on,
6842 const sp<AudioOutputDescriptor>& outputDesc,
6843 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006844 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006845{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006846 std::vector<VolumeSource> sourcesToMute;
6847 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6848 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6849 toString(attributes).c_str(), on, outputDesc->getId());
6850 VolumeSource source = toVolumeSource(attributes);
6851 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6852 sourcesToMute.push_back(source);
6853 }
Eric Laurente552edb2014-03-10 17:42:56 -07006854 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006855 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006856 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006857 }
6858
Eric Laurente552edb2014-03-10 17:42:56 -07006859}
6860
François Gaffieaaac0fd2018-11-22 17:56:39 +01006861void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6862 bool on,
6863 const sp<AudioOutputDescriptor>& outputDesc,
6864 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006865 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006866{
jiabin9a3361e2019-10-01 09:38:30 -07006867 if (deviceTypes.empty()) {
6868 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006869 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006870 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006871 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006872 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006873 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006874 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6875 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6876 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006877 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006878 }
6879 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006880 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6881 // ignored
6882 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006883 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006884 if (!outputDesc->isMuted(volumeSource)) {
6885 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006886 return;
6887 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006888 if (outputDesc->decMuteCount(volumeSource) == 0) {
6889 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006890 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006891 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006892 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006893 delayMs);
6894 }
6895 }
6896}
6897
François Gaffie53615e22015-03-19 09:24:12 +01006898bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6899{
François Gaffiec005e562018-11-06 15:04:49 +01006900 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006901 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6902 return true;
6903 }
6904
6905 // has known usage?
6906 switch (paa->usage) {
6907 case AUDIO_USAGE_UNKNOWN:
6908 case AUDIO_USAGE_MEDIA:
6909 case AUDIO_USAGE_VOICE_COMMUNICATION:
6910 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6911 case AUDIO_USAGE_ALARM:
6912 case AUDIO_USAGE_NOTIFICATION:
6913 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6914 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6915 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6916 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6917 case AUDIO_USAGE_NOTIFICATION_EVENT:
6918 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6919 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6920 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6921 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006922 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006923 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006924 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006925 case AUDIO_USAGE_EMERGENCY:
6926 case AUDIO_USAGE_SAFETY:
6927 case AUDIO_USAGE_VEHICLE_STATUS:
6928 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006929 break;
6930 default:
6931 return false;
6932 }
6933 return true;
6934}
6935
François Gaffie2110e042015-03-24 08:41:51 +01006936audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6937{
6938 return mEngine->getForceUse(usage);
6939}
6940
6941bool AudioPolicyManager::isInCall()
6942{
6943 return isStateInCall(mEngine->getPhoneState());
6944}
6945
6946bool AudioPolicyManager::isStateInCall(int state)
6947{
6948 return is_state_in_call(state);
6949}
6950
Eric Laurent74b71512019-11-06 17:21:57 -08006951bool AudioPolicyManager::isCallAudioAccessible()
6952{
6953 audio_mode_t mode = mEngine->getPhoneState();
6954 return (mode == AUDIO_MODE_IN_CALL)
6955 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6956 || (mode == AUDIO_MODE_CALL_SCREEN);
6957}
6958
Eric Laurentd60560a2015-04-10 11:31:20 -07006959void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6960{
6961 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006962 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006963 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006964 sourceDesc->sinkDevice()->equals(deviceDesc))
6965 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006966 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006967 }
6968 }
6969
6970 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6971 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6972 bool release = false;
6973 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6974 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6975 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6976 source->ext.device.type == deviceDesc->type()) {
6977 release = true;
6978 }
6979 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006980 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006981 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6982 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6983 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006984 sink->ext.device.type == deviceDesc->type() &&
6985 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6986 || strncmp(sink->ext.device.address, address,
6987 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006988 release = true;
6989 }
6990 }
6991 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006992 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6993 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006994 }
6995 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006996
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006997 mInputs.clearSessionRoutesForDevice(deviceDesc);
6998
Francois Gaffie716e1432019-01-14 16:58:59 +01006999 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007000}
7001
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007002void AudioPolicyManager::modifySurroundFormats(
7003 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007004 std::unordered_set<audio_format_t> enforcedSurround(
7005 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007006 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7007 for (const auto& pair : mConfig.getSurroundFormats()) {
7008 allSurround.insert(pair.first);
7009 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7010 }
Phil Burk09bc4612016-02-24 15:58:15 -08007011
7012 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7013 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007014 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007015 // This is the resulting set of formats depending on the surround mode:
7016 // 'all surround' = allSurround
7017 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7018 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7019 // 'manual surround' = mManualSurroundFormats
7020 // AUTO: formats v 'enforced surround'
7021 // ALWAYS: formats v 'all surround' v 'enforced surround'
7022 // NEVER: formats ^ 'non-surround'
7023 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007024
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007025 std::unordered_set<audio_format_t> formatSet;
7026 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7027 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007028 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007029 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007030 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007031 formatSet.insert(*formatIter);
7032 }
7033 }
7034 } else {
7035 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7036 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007037 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007038
jiabin81772902018-04-02 17:52:27 -07007039 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007040 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007041 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7042 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7043 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007044 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007045 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7046 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7047 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007048 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007049 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007050 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007051 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007052 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007053 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007054}
7055
jiabin06e4bab2019-07-29 10:13:34 -07007056void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7057 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007058 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7059 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7060
7061 // If NEVER, then remove support for channelMasks > stereo.
7062 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007063 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7064 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007065 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007066 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007067 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007068 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007069 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007070 }
7071 }
jiabin81772902018-04-02 17:52:27 -07007072 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7073 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7074 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007075 bool supports5dot1 = false;
7076 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007077 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007078 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7079 supports5dot1 = true;
7080 break;
7081 }
7082 }
7083 // If not then add 5.1 support.
7084 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007085 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007086 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007087 }
Phil Burk09bc4612016-02-24 15:58:15 -08007088 }
7089}
7090
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007091void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007092 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007093 AudioProfileVector &profiles)
7094{
7095 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007096 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007097
François Gaffie112b0af2015-11-19 16:13:25 +01007098 // Format MUST be checked first to update the list of AudioProfile
7099 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007100 reply = mpClientInterface->getParameters(
7101 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007102 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007103 AudioParameter repliedParameters(reply);
7104 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007105 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007106 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7107 return;
7108 }
Phil Burk09bc4612016-02-24 15:58:15 -08007109 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007110 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007111 if (device == AUDIO_DEVICE_OUT_HDMI
7112 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007113 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007114 }
jiabin3e277cc2019-09-10 14:27:34 -07007115 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007116 }
François Gaffie112b0af2015-11-19 16:13:25 +01007117
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007118 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007119 ChannelMaskSet channelMasks;
7120 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007121 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007122 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007123
7124 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007125 reply = mpClientInterface->getParameters(
7126 ioHandle,
7127 requestedParameters.toString() + ";" +
7128 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007129 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007130 AudioParameter repliedParameters(reply);
7131 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007132 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007133 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007134 }
7135 }
7136 if (profiles.hasDynamicChannelsFor(format)) {
7137 reply = mpClientInterface->getParameters(ioHandle,
7138 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007139 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007140 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007141 AudioParameter repliedParameters(reply);
7142 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007143 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007144 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007145 if (device == AUDIO_DEVICE_OUT_HDMI
7146 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007147 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007148 }
François Gaffie112b0af2015-11-19 16:13:25 +01007149 }
7150 }
jiabin3e277cc2019-09-10 14:27:34 -07007151 addDynamicAudioProfileAndSort(
7152 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007153 }
7154}
Eric Laurentd60560a2015-04-10 11:31:20 -07007155
Mikhail Naganovdc769682018-05-04 15:34:08 -07007156status_t AudioPolicyManager::installPatch(const char *caller,
7157 audio_patch_handle_t *patchHandle,
7158 AudioIODescriptorInterface *ioDescriptor,
7159 const struct audio_patch *patch,
7160 int delayMs)
7161{
7162 ssize_t index = mAudioPatches.indexOfKey(
7163 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7164 *patchHandle : ioDescriptor->getPatchHandle());
7165 sp<AudioPatch> patchDesc;
7166 status_t status = installPatch(
7167 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7168 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007169 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007170 }
7171 return status;
7172}
7173
7174status_t AudioPolicyManager::installPatch(const char *caller,
7175 ssize_t index,
7176 audio_patch_handle_t *patchHandle,
7177 const struct audio_patch *patch,
7178 int delayMs,
7179 uid_t uid,
7180 sp<AudioPatch> *patchDescPtr)
7181{
7182 sp<AudioPatch> patchDesc;
7183 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7184 if (index >= 0) {
7185 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007186 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007187 }
7188
7189 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7190 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7191 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7192 if (status == NO_ERROR) {
7193 if (index < 0) {
7194 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007195 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007196 } else {
7197 patchDesc->mPatch = *patch;
7198 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007199 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007200 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007201 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007202 }
7203 nextAudioPortGeneration();
7204 mpClientInterface->onAudioPatchListUpdate();
7205 }
7206 if (patchDescPtr) *patchDescPtr = patchDesc;
7207 return status;
7208}
7209
jiabinbce0c1d2020-10-05 11:20:18 -07007210bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7211{
7212 const TrackClientVector activeClients = output->getActiveClients();
7213 if (activeClients.empty()) {
7214 return true;
7215 }
7216 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7217 if (index < 0) {
7218 ALOGE("%s, no audio patch found while there are active clients on output %d",
7219 __func__, output->getId());
7220 return false;
7221 }
7222 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7223 DeviceVector routedDevices;
7224 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7225 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7226 patchDesc->mPatch.sinks[i].id);
7227 if (device == nullptr) {
7228 ALOGE("%s, no audio device found with id(%d)",
7229 __func__, patchDesc->mPatch.sinks[i].id);
7230 return false;
7231 }
7232 routedDevices.add(device);
7233 }
7234 for (const auto& client : activeClients) {
7235 // TODO: b/175343099 only travel the valid client
7236 sp<DeviceDescriptor> preferredDevice =
7237 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7238 if (mEngine->getOutputDevicesForAttributes(
7239 client->attributes(), preferredDevice, false) == routedDevices) {
7240 return false;
7241 }
7242 }
7243 return true;
7244}
7245
7246sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7247 const sp<IOProfile>& profile, const DeviceVector& devices)
7248{
7249 for (const auto& device : devices) {
7250 // TODO: This should be checking if the profile supports the device combo.
7251 if (!profile->supportsDevice(device)) {
7252 return nullptr;
7253 }
7254 }
7255 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7256 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02007257 status_t status = desc->open(nullptr /* halConfig */, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007258 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7259 if (status != NO_ERROR) {
7260 return nullptr;
7261 }
7262
7263 // Here is where the out_set_parameters() for card & device gets called
7264 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7265 const audio_devices_t deviceType = device->type();
7266 const String8 &address = String8(device->address().c_str());
7267 if (!address.isEmpty()) {
7268 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7269 mpClientInterface->setParameters(output, String8(param));
7270 free(param);
7271 }
7272 updateAudioProfiles(device, output, profile->getAudioProfiles());
7273 if (!profile->hasValidAudioProfile()) {
7274 ALOGW("%s() missing param", __func__);
7275 desc->close();
7276 return nullptr;
7277 } else if (profile->hasDynamicAudioProfile()) {
7278 desc->close();
7279 output = AUDIO_IO_HANDLE_NONE;
7280 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7281 profile->pickAudioProfile(
7282 config.sample_rate, config.channel_mask, config.format);
7283 config.offload_info.sample_rate = config.sample_rate;
7284 config.offload_info.channel_mask = config.channel_mask;
7285 config.offload_info.format = config.format;
7286
Eric Laurentf1f22e72021-07-13 14:04:14 +02007287 status = desc->open(&config, nullptr /* mixerConfig */, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007288 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7289 if (status != NO_ERROR) {
7290 return nullptr;
7291 }
7292 }
7293
7294 addOutput(output, desc);
7295 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7296 sp<AudioPolicyMix> policyMix;
7297 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7298 policyMix->setOutput(desc);
7299 desc->mPolicyMix = policyMix;
7300 } else {
7301 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7302 address.string());
7303 }
7304
7305 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7306 // no duplicated output for direct outputs and
7307 // outputs used by dynamic policy mixes
7308 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7309
7310 //TODO: configure audio effect output stage here
7311
7312 // open a duplicating output thread for the new output and the primary output
7313 sp<SwAudioOutputDescriptor> dupOutputDesc =
7314 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7315 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7316 if (status == NO_ERROR) {
7317 // add duplicated output descriptor
7318 addOutput(duplicatedOutput, dupOutputDesc);
7319 } else {
7320 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7321 mPrimaryOutput->mIoHandle, output);
7322 desc->close();
7323 removeOutput(output);
7324 nextAudioPortGeneration();
7325 return nullptr;
7326 }
7327 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007328 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7329 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7330 mPrimaryOutput = desc;
7331 }
jiabinbce0c1d2020-10-05 11:20:18 -07007332 return desc;
7333}
7334
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007335} // namespace android