blob: 48176da5609a79aa06980ea66037168a20eee732 [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
Carter Hsua3abb402021-10-26 11:11:20 +08001389 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1390 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1391 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1392 }
1393
Eric Laurentfa0f6742021-08-17 18:39:44 +02001394 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001395 && canBeSpatializedInt(attr, config,
1396 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001397 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001398 }
1399
Eric Laurentc529cf62020-04-17 18:19:10 -07001400 audio_config_t directConfig = *config;
1401 directConfig.channel_mask = channelMask;
1402 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1403 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001404 return output;
1405 }
1406
Eric Laurent14cbfca2016-03-17 09:42:16 -07001407 // A request for HW A/V sync cannot fallback to a mixed output because time
1408 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001409 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001410 return AUDIO_IO_HANDLE_NONE;
1411 }
1412
Eric Laurente552edb2014-03-10 17:42:56 -07001413 // ignoring channel mask due to downmix capability in mixer
1414
1415 // open a non direct output
1416
1417 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001418 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001419 // get which output is suitable for the specified stream. The actual
1420 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001421 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001422
Eric Laurent8838a382014-09-08 16:44:28 -07001423 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001424 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001425 output = selectOutput(
1426 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001427 }
François Gaffie11d30102018-11-02 16:09:09 +01001428 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001429 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001430 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001431
Eric Laurente552edb2014-03-10 17:42:56 -07001432 return output;
1433}
1434
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001435sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001436 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1437 mAvailableInputDevices);
1438 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1439}
1440
1441DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1442 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1443 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001444}
1445
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001446const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001447 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001448 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1449 if (msdModule != 0) {
1450 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1451 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1452 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1453 const struct audio_port_config *source = &patch->mPatch.sources[j];
1454 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1455 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001456 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001457 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001458 }
1459 }
1460 }
1461 return msdPatches;
1462}
1463
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001464status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1465 const InputProfileCollection &inputProfiles,
1466 const OutputProfileCollection &outputProfiles,
1467 const sp<DeviceDescriptor> &sourceDevice,
1468 const sp<DeviceDescriptor> &sinkDevice,
1469 AudioProfileVector& sourceProfiles,
1470 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001472 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001473 return NO_INIT;
1474 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001475 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001476 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001477 return NO_INIT;
1478 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001479 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001480 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1481 inProfile->supportsDevice(sourceDevice)) {
1482 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001483 }
1484 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001486 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001487 outProfile->supportsDevice(sinkDevice)) {
1488 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001489 }
1490 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001491 return NO_ERROR;
1492}
1493
1494status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1495 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1496 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1497{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001498 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001499 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1500 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1501 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001502 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001503 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1504 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001505 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001506 }
1507 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1508 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1509 sinkConfig->format = bestSinkConfig.format;
1510 // For encoded streams force direct flag to prevent downstream mixing.
1511 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1512 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001513 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1514 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001515 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001516 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1517 // raw and IEC61937 framed streams.
1518 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1519 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1520 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001521 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1522 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1523 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1524 sourceConfig->format = bestSinkConfig.format;
1525 // Copy input stream directly without any processing (e.g. resampling).
1526 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1527 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1528 if (hwAvSync) {
1529 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1530 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1531 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1532 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1533 }
1534 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1535 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1536 sinkConfig->config_mask |= config_mask;
1537 sourceConfig->config_mask |= config_mask;
1538 return NO_ERROR;
1539}
1540
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001541PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1542 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001543{
1544 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001545 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1546 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1547 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1548 if (deviceModule == nullptr) {
1549 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1550 return patchBuilder;
1551 }
1552 const InputProfileCollection inputProfiles = msdIsSource ?
1553 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1554 const OutputProfileCollection outputProfiles = msdIsSource ?
1555 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1556
1557 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1558 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1559 device : getMsdAudioOutDevices().itemAt(0);
1560 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1561
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001562 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1563 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001564 AudioProfileVector sourceProfiles;
1565 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001566 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1567 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001568 for (auto hwAvSync : { true, false }) {
1569 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1570 sourceProfiles, sinkProfiles) != NO_ERROR) {
1571 continue;
1572 }
1573 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1574 &sinkConfig) == NO_ERROR) {
1575 // Found a matching config. Re-create PatchBuilder with this config.
1576 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1577 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001578 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001579 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001580 " supporting PCM format conversion.", __func__);
1581 return patchBuilder;
1582}
1583
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001585 DeviceVector devices;
1586 if (outputDevices != nullptr && outputDevices->size() > 0) {
1587 devices.add(*outputDevices);
1588 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001589 // Use media strategy for unspecified output device. This should only
1590 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1591 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001592 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001593 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001594 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001595 }
Michael Chan6fb34492020-12-08 15:44:49 +11001596 std::vector<PatchBuilder> patchesToCreate;
1597 for (auto i = 0u; i < devices.size(); ++i) {
1598 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001599 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001600 }
1601 // Retain only the MSD patches associated with outputDevices request.
1602 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001604 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1605 auto retainedPatch = false;
1606 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1607 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1608 patchesToRemove.removeItemsAt(i);
1609 retainedPatch = true;
1610 break;
1611 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001612 }
Michael Chan6fb34492020-12-08 15:44:49 +11001613 if (retainedPatch) {
1614 it = patchesToCreate.erase(it);
1615 continue;
1616 }
1617 ++it;
1618 }
1619 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1620 return NO_ERROR;
1621 }
1622 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1623 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001624 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 }
Michael Chan6fb34492020-12-08 15:44:49 +11001626 status_t status = NO_ERROR;
1627 for (const auto &p : patchesToCreate) {
1628 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1629 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1630 char message[256];
1631 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1632 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1633 currStatus == NO_ERROR ? "Success" : "Error",
1634 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1635 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1636 if (currStatus == NO_ERROR) {
1637 ALOGD("%s", message);
1638 } else {
1639 ALOGE("%s", message);
1640 if (status == NO_ERROR) {
1641 status = currStatus;
1642 }
1643 }
1644 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001645 return status;
1646}
1647
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1649 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001650 for (size_t i = 0; i < msdPatches.size(); i++) {
1651 const auto& patch = msdPatches[i];
1652 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1653 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1654 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1655 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1656 releaseAudioPatch(patch->getHandle(), mUidCached);
1657 break;
1658 }
1659 }
1660 }
1661}
1662
Eric Laurente0720872014-03-11 09:30:41 -07001663audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001664 audio_output_flags_t flags,
1665 audio_format_t format,
1666 audio_channel_mask_t channelMask,
1667 uint32_t samplingRate,
1668 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001669{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001670 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1671 "%s called with format %#x", __func__, format);
1672
jiabinebb6af42020-06-09 17:31:17 -07001673 // Return the output that haptic-generating attached to when 1) session id is specified,
1674 // 2) haptic-generating effect exists for given session id and 3) the output that
1675 // haptic-generating effect attached to is in given outputs.
1676 if (sessionId != AUDIO_SESSION_NONE) {
1677 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1678 sessionId, FX_IID_HAPTICGENERATOR);
1679 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1680 return hapticGeneratingOutput;
1681 }
1682 }
1683
Eric Laurent16c66dd2019-05-01 17:54:10 -07001684 // Flags disqualifying an output: the match must happen before calling selectOutput()
1685 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1686 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1687
1688 // Flags expressing a functional request: must be honored in priority over
1689 // other criteria
1690 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1691 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001692 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1693 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001694 // Flags expressing a performance request: have lower priority than serving
1695 // requested sampling rate or channel mask
1696 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1697 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1698 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1699
1700 const audio_output_flags_t functionalFlags =
1701 (audio_output_flags_t)(flags & kFunctionalFlags);
1702 const audio_output_flags_t performanceFlags =
1703 (audio_output_flags_t)(flags & kPerformanceFlags);
1704
1705 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1706
Eric Laurente552edb2014-03-10 17:42:56 -07001707 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001708 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001709 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001710 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001711 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001712 // with tiebreak preferring the minimum number of extra functional flags
1713 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001714 // 3: the output supporting the exact channel mask
1715 // 4: the output with a higher channel count than requested
1716 // 5: the output with a higher sampling rate than requested
1717 // 6: the output with the highest number of requested performance flags
1718 // 7: the output with the bit depth the closest to the requested one
1719 // 8: the primary output
1720 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001721
Eric Laurent16c66dd2019-05-01 17:54:10 -07001722 // matching criteria values in priority order for best matching output so far
1723 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001724
Eric Laurent16c66dd2019-05-01 17:54:10 -07001725 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1726 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1727 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001728
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001729 for (audio_io_handle_t output : outputs) {
1730 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001731 // matching criteria values in priority order for current output
1732 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001733
Eric Laurent16c66dd2019-05-01 17:54:10 -07001734 if (outputDesc->isDuplicated()) {
1735 continue;
1736 }
1737 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1738 continue;
1739 }
Eric Laurent8838a382014-09-08 16:44:28 -07001740
Eric Laurent16c66dd2019-05-01 17:54:10 -07001741 // If haptic channel is specified, use the haptic output if present.
1742 // When using haptic output, same audio format and sample rate are required.
1743 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001744 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001745 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1746 continue;
1747 }
1748 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001749 && format == outputDesc->getFormat()
1750 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001751 currentMatchCriteria[0] = outputHapticChannelCount;
1752 }
1753
1754 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001755 const int matchingFunctionalFlags =
1756 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1757 const int totalFunctionalFlags =
1758 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1759 // Prefer matching functional flags, but subtract unnecessary functional flags.
1760 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001761
1762 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001763 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1764 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001765 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1766 channelCount <= outputChannelCount) {
1767 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001768 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1769 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001770 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001771 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001772 currentMatchCriteria[3] = outputChannelCount;
1773 }
1774
1775 // sampling rate match
1776 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001777 samplingRate <= outputDesc->getSamplingRate()) {
1778 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001779 }
1780
1781 // performance flags match
1782 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1783
1784 // format match
1785 if (format != AUDIO_FORMAT_INVALID) {
1786 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001787 PolicyAudioPort::kFormatDistanceMax -
1788 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001789 }
1790
1791 // primary output match
1792 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1793
1794 // compare match criteria by priority then value
1795 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1796 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1797 bestMatchCriteria = currentMatchCriteria;
1798 bestOutput = output;
1799
1800 std::stringstream result;
1801 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1802 std::ostream_iterator<int>(result, " "));
1803 ALOGV("%s new bestOutput %d criteria %s",
1804 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001805 }
1806 }
1807
Eric Laurent16c66dd2019-05-01 17:54:10 -07001808 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001809}
1810
Eric Laurent8fc147b2018-07-22 19:13:55 -07001811status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001812{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001813 ALOGV("%s portId %d", __FUNCTION__, portId);
1814
1815 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1816 if (outputDesc == 0) {
1817 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001818 return BAD_VALUE;
1819 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001820 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001821
Eric Laurent8fc147b2018-07-22 19:13:55 -07001822 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001823 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001824
Eric Laurent733ce942017-12-07 12:18:25 -08001825 status_t status = outputDesc->start();
1826 if (status != NO_ERROR) {
1827 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001828 }
1829
Eric Laurent97ac8712018-07-27 18:59:02 -07001830 uint32_t delayMs;
1831 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001832
1833 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001834 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001835 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001836 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001837 if (delayMs != 0) {
1838 usleep(delayMs * 1000);
1839 }
1840
1841 return status;
1842}
1843
Eric Laurent97ac8712018-07-27 18:59:02 -07001844status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1845 const sp<TrackClientDescriptor>& client,
1846 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001847{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001848 // cannot start playback of STREAM_TTS if any other output is being used
1849 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001850
1851 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001852 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001853 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001854 auto clientStrategy = client->strategy();
1855 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001856 if (stream == AUDIO_STREAM_TTS) {
1857 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001858 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001859 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001860 return INVALID_OPERATION;
1861 } else {
1862 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1863 }
1864 } else {
1865 // some playback other than beacon starts
1866 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1867 }
1868
Eric Laurent77305a62016-07-25 16:39:22 -07001869 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001870 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001871 bool force = !outputDesc->isActive() &&
1872 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001873
François Gaffie11d30102018-11-02 16:09:09 +01001874 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001875 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001876 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001877 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001878 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001879 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001880 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001881 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001882 } else {
1883 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001884 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001885 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1886 AUDIO_FORMAT_DEFAULT);
1887 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1888 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001889 }
1890
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001891 // requiresMuteCheck is false when we can bypass mute strategy.
1892 // It covers a common case when there is no materially active audio
1893 // and muting would result in unnecessary delay and dropped audio.
1894 const uint32_t outputLatencyMs = outputDesc->latency();
1895 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1896
Eric Laurente552edb2014-03-10 17:42:56 -07001897 // increment usage count for this stream on the requested output:
1898 // NOTE that the usage count is the same for duplicated output and hardware output which is
1899 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001900 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001901
1902 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001903 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1904 client->isPreferredDeviceForExclusiveUse()) {
1905 // Preferred device may be exclusive, use only if no other active clients on this output
1906 devices = DeviceVector(
1907 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1908 } else {
1909 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1910 }
François Gaffie11d30102018-11-02 16:09:09 +01001911 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001912 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001913 }
1914 }
Eric Laurente552edb2014-03-10 17:42:56 -07001915
François Gaffiec005e562018-11-06 15:04:49 +01001916 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001917 selectOutputForMusicEffects();
1918 }
1919
François Gaffie1c878552018-11-22 16:53:21 +01001920 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001921 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001922 if (devices.isEmpty()) {
1923 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001924 }
François Gaffiec005e562018-11-06 15:04:49 +01001925 bool shouldWait =
1926 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1927 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1928 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001929 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001930 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001931 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001932 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001933 // An output has a shared device if
1934 // - managed by the same hw module
1935 // - supports the currently selected device
1936 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001937 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001938
Eric Laurent77305a62016-07-25 16:39:22 -07001939 // force a device change if any other output is:
1940 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001941 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001942 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001943 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001944 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001945 // change the device currently selected by the other output.
1946 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001947 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001948 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001949 force = true;
1950 }
1951 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001952 // a notification so that audio focus effect can propagate, or that a mute/unmute
1953 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001954 const uint32_t latencyMs = desc->latency();
1955 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1956
1957 if (shouldWait && isActive && (waitMs < latencyMs)) {
1958 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001959 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001960
1961 // Require mute check if another output is on a shared device
1962 // and currently active to have proper drain and avoid pops.
1963 // Note restoring AudioTracks onto this output needs to invoke
1964 // a volume ramp if there is no mute.
1965 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001966 }
1967 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001968
1969 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001970 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001971
Eric Laurente552edb2014-03-10 17:42:56 -07001972 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001973 auto &curves = getVolumeCurves(client->attributes());
1974 checkAndSetVolume(curves, client->volumeSource(),
1975 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001976 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001977 outputDesc->devices().types(), 0 /*delay*/,
1978 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001979
1980 // update the outputs if starting an output with a stream that can affect notification
1981 // routing
1982 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001983
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001984 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001985 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001986 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1987 }
Eric Laurentdc462862016-07-19 12:29:53 -07001988
1989 if (waitMs > muteWaitMs) {
1990 *delayMs = waitMs - muteWaitMs;
1991 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001992
1993 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1994 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1995 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1996 // change occurs after the MixerThread starts and causes a stream volume
1997 // glitch.
1998 //
1999 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002000 }
Eric Laurentdc462862016-07-19 12:29:53 -07002001
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002002 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002003 mEngine->getForceUse(
2004 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002005 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002006 }
2007
Eric Laurent97ac8712018-07-27 18:59:02 -07002008 // Automatically enable the remote submix input when output is started on a re routing mix
2009 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002010 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2011 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002012 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2013 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2014 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002015 "remote-submix",
2016 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002017 }
2018
Eric Laurente552edb2014-03-10 17:42:56 -07002019 return NO_ERROR;
2020}
2021
Eric Laurent8fc147b2018-07-22 19:13:55 -07002022status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002023{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002024 ALOGV("%s portId %d", __FUNCTION__, portId);
2025
2026 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2027 if (outputDesc == 0) {
2028 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002029 return BAD_VALUE;
2030 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002031 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002032
Eric Laurent97ac8712018-07-27 18:59:02 -07002033 ALOGV("stopOutput() output %d, stream %d, session %d",
2034 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002035
Eric Laurent97ac8712018-07-27 18:59:02 -07002036 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002037
Eric Laurent733ce942017-12-07 12:18:25 -08002038 if (status == NO_ERROR ) {
2039 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002040 }
2041 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002042}
2043
Eric Laurent97ac8712018-07-27 18:59:02 -07002044status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2045 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002046{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002047 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002048 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002049 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002050
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002051 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2052
François Gaffie1c878552018-11-22 16:53:21 +01002053 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2054 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002055 // Automatically disable the remote submix input when output is stopped on a
2056 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002057 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002058 if (isSingleDeviceType(
2059 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002060 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002061 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002062 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2063 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002064 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002065 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002066 }
2067 }
2068 bool forceDeviceUpdate = false;
2069 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002070 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002071 forceDeviceUpdate = true;
2072 }
2073
Eric Laurente552edb2014-03-10 17:42:56 -07002074 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002075 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002076
Eric Laurente552edb2014-03-10 17:42:56 -07002077 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002078 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002079 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002080 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002081 // delay the device switch by twice the latency because stopOutput() is executed when
2082 // the track stop() command is received and at that time the audio track buffer can
2083 // still contain data that needs to be drained. The latency only covers the audio HAL
2084 // and kernel buffers. Also the latency does not always include additional delay in the
2085 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002086 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002087
2088 // force restoring the device selection on other active outputs if it differs from the
2089 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002090 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002091 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002092 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002093 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002094 desc->isActive() &&
2095 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002096 (newDevices != desc->devices())) {
2097 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2098 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002099
François Gaffie11d30102018-11-02 16:09:09 +01002100 setOutputDevices(desc, newDevices2, force, delayMs);
2101
Eric Laurent57de36c2016-09-28 16:59:11 -07002102 // re-apply device specific volume if not done by setOutputDevice()
2103 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002104 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002105 }
Eric Laurente552edb2014-03-10 17:42:56 -07002106 }
2107 }
2108 // update the outputs if stopping one with a stream that can affect notification routing
2109 handleNotificationRoutingForStream(stream);
2110 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002111
2112 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2113 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002114 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002115 }
2116
François Gaffiec005e562018-11-06 15:04:49 +01002117 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002118 selectOutputForMusicEffects();
2119 }
Eric Laurente552edb2014-03-10 17:42:56 -07002120 return NO_ERROR;
2121 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002122 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002123 return INVALID_OPERATION;
2124 }
2125}
2126
jiabinbce0c1d2020-10-05 11:20:18 -07002127bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002128{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129 ALOGV("%s portId %d", __FUNCTION__, portId);
2130
2131 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2132 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002133 // If an output descriptor is closed due to a device routing change,
2134 // then there are race conditions with releaseOutput from tracks
2135 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2136 // destroyed shortly thereafter.
2137 //
2138 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002140 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002141 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002142
2143 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002144
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302145 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2146 if (outputDesc->isClientActive(client)) {
2147 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2148 stopOutput(portId);
2149 }
2150
Eric Laurent8fc147b2018-07-22 19:13:55 -07002151 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2152 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002153 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002155 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002156 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002157 if (--outputDesc->mDirectOpenCount == 0) {
2158 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002159 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002160 }
2161 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302162
Andy Hung39efb7a2018-09-26 15:39:28 -07002163 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002164 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2165 // The output is pending reopened to query dynamic profiles and
2166 // there is no active clients
2167 closeOutput(outputDesc->mIoHandle);
2168 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2169 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2170 if (newOutputDesc == nullptr) {
2171 ALOGE("%s failed to open output", __func__);
2172 }
2173 return true;
2174 }
2175 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002176}
2177
Eric Laurentcaf7f482014-11-25 17:50:47 -08002178status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2179 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002180 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002181 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002182 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002183 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002184 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002185 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002186 input_type_t *inputType,
2187 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002188{
François Gaffiec005e562018-11-06 15:04:49 +01002189 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002190 "flags %#x attributes=%s requested device ID %d",
2191 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2192 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002193
Eric Laurentad2e7b92017-09-14 20:06:42 -07002194 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002195 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002196 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002197 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002198 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002199 sp<AudioInputDescriptor> inputDesc;
2200 sp<RecordClientDescriptor> clientDesc;
2201 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002202 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002203 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002204
2205 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2206 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2207 return INVALID_OPERATION;
2208 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002209
Francois Gaffie716e1432019-01-14 16:58:59 +01002210 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2211 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002212 }
2213
Paul McLean466dc8e2015-04-17 13:15:36 -06002214 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002215 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002216 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002217
Eric Laurentad2e7b92017-09-14 20:06:42 -07002218 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2219 // possible
2220 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2221 *input != AUDIO_IO_HANDLE_NONE) {
2222 ssize_t index = mInputs.indexOfKey(*input);
2223 if (index < 0) {
2224 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2225 status = BAD_VALUE;
2226 goto error;
2227 }
2228 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002229 RecordClientVector clients = inputDesc->getClientsForSession(session);
2230 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002231 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2232 status = BAD_VALUE;
2233 goto error;
2234 }
2235 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2236 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002237 // corresponds to a new client and is only permitted from the same UID.
2238 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002239 if (clients.size() > 1) {
2240 for (const auto& client : clients) {
2241 // The client map is ordered by key values (portId) and portIds are allocated
2242 // incrementaly. So the first client in this list is the one opened by audio flinger
2243 // when the mmap stream is created and should be ignored as it does not correspond
2244 // to an actual client
2245 if (client == *clients.cbegin()) {
2246 continue;
2247 }
2248 if (uid != client->uid() && !client->isSilenced()) {
2249 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2250 uid, client->portId(), client->uid());
2251 status = INVALID_OPERATION;
2252 goto error;
2253 }
Eric Laurent331679c2018-04-16 17:03:16 -07002254 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002255 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002256 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002257 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002258
Eric Laurentfecbceb2021-02-09 14:46:43 +01002259 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002260 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002261 }
2262
2263 *input = AUDIO_IO_HANDLE_NONE;
2264 *inputType = API_INPUT_INVALID;
2265
Francois Gaffie716e1432019-01-14 16:58:59 +01002266 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002267
Francois Gaffie716e1432019-01-14 16:58:59 +01002268 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2269 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2270 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002271 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002272 ALOGW("%s could not find input mix for attr %s",
2273 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002274 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002275 }
jiabinc1de2df2019-05-07 14:26:40 -07002276 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2277 String8(attr->tags + strlen("addr=")),
2278 AUDIO_FORMAT_DEFAULT);
2279 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002280 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002281 __func__, attributes.source, attributes.tags);
2282 status = BAD_VALUE;
2283 goto error;
2284 }
2285
Kevin Rocard25f9b052019-02-27 15:08:54 -08002286 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2287 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2288 } else {
2289 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2290 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002291 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002292 if (explicitRoutingDevice != nullptr) {
2293 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002294 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002295 // Prevent from storing invalid requested device id in clients
2296 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002297 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002298 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2299 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002300 }
François Gaffie11d30102018-11-02 16:09:09 +01002301 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002302 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002303 status = BAD_VALUE;
2304 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002305 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002306 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2307 *inputType = API_INPUT_MIX_CAPTURE;
2308 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002309 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2310 // there is an external policy, but this input is attached to a mix of recorders,
2311 // meaning it receives audio injected into the framework, so the recorder doesn't
2312 // know about it and is therefore considered "legacy"
2313 *inputType = API_INPUT_LEGACY;
2314 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002315 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002316 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002317 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002318 } else {
2319 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002320 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002321
Eric Laurent599c7582015-12-07 18:05:55 -08002322 }
2323
François Gaffiec005e562018-11-06 15:04:49 +01002324 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002325 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002326 status = INVALID_OPERATION;
2327 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002328 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002329
Eric Laurent8f42ea12018-08-08 09:08:25 -07002330exit:
2331
François Gaffiec005e562018-11-06 15:04:49 +01002332 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2333 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002334
Francois Gaffie716e1432019-01-14 16:58:59 +01002335 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002336 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002337 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002338
Mikhail Naganov2996f672019-04-18 12:29:59 -07002339 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002340 requestedDeviceId, attributes.source, flags,
2341 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002342 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002343 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002344
2345 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2346 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002347
Eric Laurent599c7582015-12-07 18:05:55 -08002348 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002349
2350error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002351 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002352}
2353
2354
François Gaffie11d30102018-11-02 16:09:09 +01002355audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002356 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002357 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002358 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002359 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002360 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002361{
2362 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002363 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002364 bool isSoundTrigger = false;
2365
François Gaffiec005e562018-11-06 15:04:49 +01002366 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002367 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2368 if (index >= 0) {
2369 input = mSoundTriggerSessions.valueFor(session);
2370 isSoundTrigger = true;
2371 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2372 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2373 } else {
2374 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002375 }
François Gaffiec005e562018-11-06 15:04:49 +01002376 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002377 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002378 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002379 }
2380
Carter Hsua3abb402021-10-26 11:11:20 +08002381 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2382 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2383 }
2384
Andy Hungf129b032015-04-07 13:45:50 -07002385 // find a compatible input profile (not necessarily identical in parameters)
2386 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002387 // sampling rate and flags may be updated by getInputProfile
2388 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2389 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002390 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002391 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002392 audio_input_flags_t profileFlags = flags;
2393 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002394 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002395 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002396 profileFlags);
2397 if (profile != 0) {
2398 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002399 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2400 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002401 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002402 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2403 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002404 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002405 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002406 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002407 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002408 }
Eric Laurente552edb2014-03-10 17:42:56 -07002409 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002410 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002411 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002412 if (samplingRate == 0) {
2413 samplingRate = profileSamplingRate;
2414 }
Eric Laurente552edb2014-03-10 17:42:56 -07002415
Eric Laurent322b4d22015-04-03 15:57:54 -07002416 if (profile->getModuleHandle() == 0) {
2417 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002418 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002419 }
2420
Eric Laurentec376dc2021-04-08 20:41:22 +02002421 // Reuse an already opened input if a client with the same session ID already exists
2422 // on that input
2423 for (size_t i = 0; i < mInputs.size(); i++) {
2424 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2425 if (desc->mProfile != profile) {
2426 continue;
2427 }
2428 RecordClientVector clients = desc->clientsList();
2429 for (const auto &client : clients) {
2430 if (session == client->session()) {
2431 return desc->mIoHandle;
2432 }
2433 }
2434 }
2435
Eric Laurent3974e3b2017-12-07 17:58:43 -08002436 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002437 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002438 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002439 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002440 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002441 continue;
2442 }
2443 // if sound trigger, reuse input if used by other sound trigger on same session
2444 // else
2445 // reuse input if active client app is not in IDLE state
2446 //
2447 RecordClientVector clients = desc->clientsList();
2448 bool doClose = false;
2449 for (const auto& client : clients) {
2450 if (isSoundTrigger != client->isSoundTrigger()) {
2451 continue;
2452 }
2453 if (client->isSoundTrigger()) {
2454 if (session == client->session()) {
2455 return desc->mIoHandle;
2456 }
2457 continue;
2458 }
2459 if (client->active() && client->appState() != APP_STATE_IDLE) {
2460 return desc->mIoHandle;
2461 }
2462 doClose = true;
2463 }
2464 if (doClose) {
2465 closeInput(desc->mIoHandle);
2466 } else {
2467 i++;
2468 }
2469 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002470 }
2471
Eric Laurentfe231122017-11-17 17:48:06 -08002472 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002473
Eric Laurentfe231122017-11-17 17:48:06 -08002474 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2475 lConfig.sample_rate = profileSamplingRate;
2476 lConfig.channel_mask = profileChannelMask;
2477 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002478
François Gaffie11d30102018-11-02 16:09:09 +01002479 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002480
2481 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002482 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002483 (profileSamplingRate != lConfig.sample_rate) ||
2484 !audio_formats_match(profileFormat, lConfig.format) ||
2485 (profileChannelMask != lConfig.channel_mask)) {
2486 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002487 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002488 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002489 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002490 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002491 }
Eric Laurent599c7582015-12-07 18:05:55 -08002492 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002493 }
2494
Eric Laurentc722f302014-12-10 11:21:49 -08002495 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002496
Eric Laurent599c7582015-12-07 18:05:55 -08002497 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002498 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002499
Eric Laurent599c7582015-12-07 18:05:55 -08002500 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002501}
2502
Eric Laurent4eb58f12018-12-07 16:41:02 -08002503status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002504{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002505 ALOGV("%s portId %d", __FUNCTION__, portId);
2506
2507 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2508 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002509 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002510 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002511 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002512 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002513 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 if (client->active()) {
2515 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2516 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002517 }
2518
Eric Laurent8f42ea12018-08-08 09:08:25 -07002519 audio_session_t session = client->session();
2520
Eric Laurent4eb58f12018-12-07 16:41:02 -08002521 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002522
Eric Laurent4eb58f12018-12-07 16:41:02 -08002523 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002524
Eric Laurent4eb58f12018-12-07 16:41:02 -08002525 status_t status = inputDesc->start();
2526 if (status != NO_ERROR) {
2527 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002528 }
Eric Laurente552edb2014-03-10 17:42:56 -07002529
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002530 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002531 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002532 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002533
Eric Laurent8f42ea12018-08-08 09:08:25 -07002534 // indicate active capture to sound trigger service if starting capture from a mic on
2535 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002536 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002537 if (device != nullptr) {
2538 status = setInputDevice(input, device, true /* force */);
2539 } else {
2540 ALOGW("%s no new input device can be found for descriptor %d",
2541 __FUNCTION__, inputDesc->getId());
2542 status = BAD_VALUE;
2543 }
Eric Laurente552edb2014-03-10 17:42:56 -07002544
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002545 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002546 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002547 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002548 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002549 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2550 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002551 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002552 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002553
François Gaffie11d30102018-11-02 16:09:09 +01002554 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2555 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002557 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002558 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002559
Eric Laurent8f42ea12018-08-08 09:08:25 -07002560 // automatically enable the remote submix output when input is started if not
2561 // used by a policy mix of type MIX_TYPE_RECORDERS
2562 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002563 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002564 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002565 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002566 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002567 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2568 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002569 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002570 if (address != "") {
2571 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2572 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002573 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002574 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002575 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002576 } else if (status != NO_ERROR) {
2577 // Restore client activity state.
2578 inputDesc->setClientActive(client, false);
2579 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002580 }
2581
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002582 ALOGV("%s input %d source = %d status = %d exit",
2583 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002584
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002585 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002586}
2587
Eric Laurent8fc147b2018-07-22 19:13:55 -07002588status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002589{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002590 ALOGV("%s portId %d", __FUNCTION__, portId);
2591
2592 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2593 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002594 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002595 return BAD_VALUE;
2596 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002597 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002598 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599 if (!client->active()) {
2600 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002601 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002602 }
Carter Hsue6139d52021-07-08 10:30:20 +08002603 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002604 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002605
Eric Laurent8f42ea12018-08-08 09:08:25 -07002606 inputDesc->stop();
2607 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002608 auto current_source = inputDesc->source();
2609 setInputDevice(input, getNewInputDevice(inputDesc),
2610 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002611 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002612 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002614 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002615 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2616 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002617 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002618 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002619
2620 // automatically disable the remote submix output when input is stopped if not
2621 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002622 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002623 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002624 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002626 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2627 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002628 }
2629 if (address != "") {
2630 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2631 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002632 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 }
2634 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002635 resetInputDevice(input);
2636
2637 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2638 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002639 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2640 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002641 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002642 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002643 }
2644 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002645 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002646 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002647}
2648
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002650{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651 ALOGV("%s portId %d", __FUNCTION__, portId);
2652
2653 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2654 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002655 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002656 return;
2657 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002658 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002659 audio_io_handle_t input = inputDesc->mIoHandle;
2660
Eric Laurent8f42ea12018-08-08 09:08:25 -07002661 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002662
Andy Hung39efb7a2018-09-26 15:39:28 -07002663 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002664
Andy Hung39efb7a2018-09-26 15:39:28 -07002665 if (inputDesc->getClientCount() > 0) {
2666 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002667 return;
2668 }
2669
Eric Laurent05b90f82014-08-27 15:32:29 -07002670 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002671 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002672 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002673}
2674
Eric Laurent8f42ea12018-08-08 09:08:25 -07002675void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002676{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002678
2679 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002680 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681 }
2682}
2683
Eric Laurent8f42ea12018-08-08 09:08:25 -07002684void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2685{
2686 stopInput(portId);
2687 releaseInput(portId);
2688}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002689
Eric Laurent0dd51852019-04-19 18:18:58 -07002690void AudioPolicyManager::checkCloseInputs() {
2691 // After connecting or disconnecting an input device, close input if:
2692 // - it has no client (was just opened to check profile) OR
2693 // - none of its supported devices are connected anymore OR
2694 // - one of its clients cannot be routed to one of its supported
2695 // devices anymore. Otherwise update device selection
2696 std::vector<audio_io_handle_t> inputsToClose;
2697 for (size_t i = 0; i < mInputs.size(); i++) {
2698 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2699 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002700 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002701 inputsToClose.push_back(mInputs.keyAt(i));
2702 } else {
2703 bool close = false;
2704 for (const auto& client : input->clientsList()) {
2705 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002706 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002707 if (!input->supportedDevices().contains(device)) {
2708 close = true;
2709 break;
2710 }
2711 }
2712 if (close) {
2713 inputsToClose.push_back(mInputs.keyAt(i));
2714 } else {
2715 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2716 }
2717 }
2718 }
2719
2720 for (const audio_io_handle_t handle : inputsToClose) {
2721 ALOGV("%s closing input %d", __func__, handle);
2722 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002723 }
Eric Laurentd4692962014-05-05 18:13:44 -07002724}
2725
François Gaffie251c7f02018-11-07 10:41:08 +01002726void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002727{
2728 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002729 if (indexMin < 0 || indexMax < 0) {
2730 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2731 return;
2732 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002733 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002734
2735 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002736 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2737 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002738 continue;
2739 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002740 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002741 }
Eric Laurente552edb2014-03-10 17:42:56 -07002742}
2743
Eric Laurente0720872014-03-11 09:30:41 -07002744status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002745 int index,
2746 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002747{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002748 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002749 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2750 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2751 return NO_ERROR;
2752 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002753 ALOGV("%s: stream %s attributes=%s", __func__,
2754 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002755 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002756}
2757
Eric Laurente0720872014-03-11 09:30:41 -07002758status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002759 int *index,
2760 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002761{
François Gaffiec005e562018-11-06 15:04:49 +01002762 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2763 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002764 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002765 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002766 deviceTypes = mEngine->getOutputDevicesForStream(
2767 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002768 }
jiabin9a3361e2019-10-01 09:38:30 -07002769 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002770}
2771
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002772status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002773 int index,
2774 audio_devices_t device)
2775{
2776 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002777 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2778 if (group == VOLUME_GROUP_NONE) {
2779 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002780 return BAD_VALUE;
2781 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002782 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002783 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002784 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002785 VolumeSource vs = toVolumeSource(group);
2786 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2787
2788 status = setVolumeCurveIndex(index, device, curves);
2789 if (status != NO_ERROR) {
2790 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2791 return status;
2792 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002793
jiabin9a3361e2019-10-01 09:38:30 -07002794 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002795 auto curCurvAttrs = curves.getAttributes();
2796 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2797 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002798 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002799 } else if (!curves.getStreamTypes().empty()) {
2800 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002801 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002802 } else {
2803 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2804 return BAD_VALUE;
2805 }
jiabin9a3361e2019-10-01 09:38:30 -07002806 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2807 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002808
François Gaffiecfe17322018-11-07 13:41:29 +01002809 // update volume on all outputs and streams matching the following:
2810 // - The requested stream (or a stream matching for volume control) is active on the output
2811 // - The device (or devices) selected by the engine for this stream includes
2812 // the requested device
2813 // - For non default requested device, currently selected device on the output is either the
2814 // requested device or one of the devices selected by the engine for this stream
2815 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2816 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002817 for (size_t i = 0; i < mOutputs.size(); i++) {
2818 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002819 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002820
jiabin9a3361e2019-10-01 09:38:30 -07002821 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2822 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002823 }
François Gaffieed91f582020-01-31 10:35:37 +01002824 if (!(desc->isActive(vs) || isInCall())) {
2825 continue;
2826 }
2827 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2828 curDevices.find(device) == curDevices.end()) {
2829 continue;
2830 }
2831 bool applyVolume = false;
2832 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2833 curSrcDevices.insert(device);
2834 applyVolume = (curSrcDevices.find(
2835 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2836 } else {
2837 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2838 }
2839 if (!applyVolume) {
2840 continue; // next output
2841 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002842 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2843 // If a higher priority strategy is active, and the output is routed to a device with a
2844 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002845 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002846 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002847 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2848 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2849 false /*preferredDevice*/);
2850 if (activeClients.empty()) {
2851 continue;
2852 }
2853 bool isPreempted = false;
2854 bool isHigherPriority = productStrategy < strategy;
2855 for (const auto &client : activeClients) {
2856 if (isHigherPriority && (client->volumeSource() != vs)) {
2857 ALOGV("%s: Strategy=%d (\nrequester:\n"
2858 " group %d, volumeGroup=%d attributes=%s)\n"
2859 " higher priority source active:\n"
2860 " volumeGroup=%d attributes=%s) \n"
2861 " on output %zu, bailing out", __func__, productStrategy,
2862 group, group, toString(attributes).c_str(),
2863 client->volumeSource(), toString(client->attributes()).c_str(), i);
2864 applyVolume = false;
2865 isPreempted = true;
2866 break;
2867 }
2868 // However, continue for loop to ensure no higher prio clients running on output
2869 if (client->volumeSource() == vs) {
2870 applyVolume = true;
2871 }
2872 }
2873 if (isPreempted || applyVolume) {
2874 break;
2875 }
2876 }
2877 if (!applyVolume) {
2878 continue; // next output
2879 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002880 }
François Gaffieed91f582020-01-31 10:35:37 +01002881 //FIXME: workaround for truncated touch sounds
2882 // delayed volume change for system stream to be removed when the problem is
2883 // handled by system UI
2884 status_t volStatus = checkAndSetVolume(
2885 curves, vs, index, desc, curDevices,
2886 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2887 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2888 if (volStatus != NO_ERROR) {
2889 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002890 }
2891 }
François Gaffiecfe17322018-11-07 13:41:29 +01002892 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2893 return status;
2894}
2895
François Gaffieaaac0fd2018-11-22 17:56:39 +01002896status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002897 audio_devices_t device,
2898 IVolumeCurves &volumeCurves)
2899{
2900 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2901 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002902 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2903 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002904 (index > volumeCurves.getVolumeIndexMax())) {
2905 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2906 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2907 return BAD_VALUE;
2908 }
2909 if (!audio_is_output_device(device)) {
2910 return BAD_VALUE;
2911 }
2912
2913 // Force max volume if stream cannot be muted
2914 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2915
François Gaffieaaac0fd2018-11-22 17:56:39 +01002916 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002917 volumeCurves.addCurrentVolumeIndex(device, index);
2918 return NO_ERROR;
2919}
2920
2921status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2922 int &index,
2923 audio_devices_t device)
2924{
2925 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2926 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002927 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002928 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002929 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2930 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002931 }
jiabin9a3361e2019-10-01 09:38:30 -07002932 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002933}
2934
2935status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2936 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002937 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002938{
jiabin9a3361e2019-10-01 09:38:30 -07002939 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002940 return BAD_VALUE;
2941 }
jiabin9a3361e2019-10-01 09:38:30 -07002942 index = curves.getVolumeIndex(deviceTypes);
2943 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002944 return NO_ERROR;
2945}
2946
2947status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2948 int &index)
2949{
2950 index = getVolumeCurves(attr).getVolumeIndexMin();
2951 return NO_ERROR;
2952}
2953
2954status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2955 int &index)
2956{
2957 index = getVolumeCurves(attr).getVolumeIndexMax();
2958 return NO_ERROR;
2959}
2960
Eric Laurent36829f92017-04-07 19:04:42 -07002961audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002962{
2963 // select one output among several suitable for global effects.
2964 // The priority is as follows:
2965 // 1: An offloaded output. If the effect ends up not being offloadable,
2966 // AudioFlinger will invalidate the track and the offloaded output
2967 // will be closed causing the effect to be moved to a PCM output.
2968 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002969 // 3: The primary output
2970 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002971
François Gaffiec005e562018-11-06 15:04:49 +01002972 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2973 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002974 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002975
Eric Laurent36829f92017-04-07 19:04:42 -07002976 if (outputs.size() == 0) {
2977 return AUDIO_IO_HANDLE_NONE;
2978 }
Eric Laurente552edb2014-03-10 17:42:56 -07002979
Eric Laurent36829f92017-04-07 19:04:42 -07002980 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2981 bool activeOnly = true;
2982
2983 while (output == AUDIO_IO_HANDLE_NONE) {
2984 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2985 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2986 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2987
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002988 for (audio_io_handle_t output : outputs) {
2989 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002990 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002991 continue;
2992 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002993 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2994 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002995 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002996 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002997 }
2998 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002999 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003000 }
3001 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003002 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003003 }
3004 }
3005 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3006 output = outputOffloaded;
3007 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3008 output = outputDeepBuffer;
3009 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3010 output = outputPrimary;
3011 } else {
3012 output = outputs[0];
3013 }
3014 activeOnly = false;
3015 }
3016
3017 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003018 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003019 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3020 mMusicEffectOutput = output;
3021 }
3022
3023 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003024 return output;
3025}
3026
Eric Laurent36829f92017-04-07 19:04:42 -07003027audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3028{
3029 return selectOutputForMusicEffects();
3030}
3031
Eric Laurente0720872014-03-11 09:30:41 -07003032status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003033 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003034 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003035 int session,
3036 int id)
3037{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003038 if (session != AUDIO_SESSION_DEVICE) {
3039 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003040 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003041 index = mInputs.indexOfKey(io);
3042 if (index < 0) {
3043 ALOGW("registerEffect() unknown io %d", io);
3044 return INVALID_OPERATION;
3045 }
Eric Laurente552edb2014-03-10 17:42:56 -07003046 }
3047 }
François Gaffiec005e562018-11-06 15:04:49 +01003048 return mEffects.registerEffect(desc, io, session, id,
3049 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3050 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003051}
3052
Eric Laurentc241b0d2018-11-28 09:08:49 -08003053status_t AudioPolicyManager::unregisterEffect(int id)
3054{
3055 if (mEffects.getEffect(id) == nullptr) {
3056 return INVALID_OPERATION;
3057 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003058 if (mEffects.isEffectEnabled(id)) {
3059 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3060 setEffectEnabled(id, false);
3061 }
3062 return mEffects.unregisterEffect(id);
3063}
3064
3065status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3066{
3067 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3068 if (effect == nullptr) {
3069 return INVALID_OPERATION;
3070 }
3071
3072 status_t status = mEffects.setEffectEnabled(id, enabled);
3073 if (status == NO_ERROR) {
3074 mInputs.trackEffectEnabled(effect, enabled);
3075 }
3076 return status;
3077}
3078
Eric Laurent6c796322019-04-09 14:13:17 -07003079
3080status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3081{
3082 mEffects.moveEffects(ids, io);
3083 return NO_ERROR;
3084}
3085
Eric Laurentc75307b2015-03-17 15:29:32 -07003086bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3087{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003088 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003089}
3090
3091bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3092{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003093 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003094}
3095
Eric Laurente0720872014-03-11 09:30:41 -07003096bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003097{
3098 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003099 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003100 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003101 return true;
3102 }
3103 }
3104 return false;
3105}
3106
Eric Laurent275e8e92014-11-30 15:14:47 -08003107// Register a list of custom mixes with their attributes and format.
3108// When a mix is registered, corresponding input and output profiles are
3109// added to the remote submix hw module. The profile contains only the
3110// parameters (sampling rate, format...) specified by the mix.
3111// The corresponding input remote submix device is also connected.
3112//
3113// When a remote submix device is connected, the address is checked to select the
3114// appropriate profile and the corresponding input or output stream is opened.
3115//
3116// When capture starts, getInputForAttr() will:
3117// - 1 look for a mix matching the address passed in attribtutes tags if any
3118// - 2 if none found, getDeviceForInputSource() will:
3119// - 2.1 look for a mix matching the attributes source
3120// - 2.2 if none found, default to device selection by policy rules
3121// At this time, the corresponding output remote submix device is also connected
3122// and active playback use cases can be transferred to this mix if needed when reconnecting
3123// after AudioTracks are invalidated
3124//
3125// When playback starts, getOutputForAttr() will:
3126// - 1 look for a mix matching the address passed in attribtutes tags if any
3127// - 2 if none found, look for a mix matching the attributes usage
3128// - 3 if none found, default to device and output selection by policy rules.
3129
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003130status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003131{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003132 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3133 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003134 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003135 sp<HwModule> rSubmixModule;
3136 // examine each mix's route type
3137 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003138 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003139 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3140 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3141 ALOGE("Unsupported Policy Mix %zu of %zu: "
3142 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3143 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003144 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003145 break;
3146 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003147 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3148 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003149 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003150 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3151 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003152 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003153 rSubmixModule = mHwModules.getModuleFromName(
3154 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3155 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003156 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003157 i);
3158 res = INVALID_OPERATION;
3159 break;
3160 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003161 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003162
Eric Laurent97ac8712018-07-27 18:59:02 -07003163 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003164 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003165 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003166 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003167 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3168 } else {
3169 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3170 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003171 }
François Gaffie036e1e92015-03-19 10:16:24 +01003172
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003173 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003174 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003175 res = INVALID_OPERATION;
3176 break;
3177 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003178 audio_config_t outputConfig = mix.mFormat;
3179 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003180 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3181 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003182 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3183 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003184 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003185 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003186 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003187 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003188
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003189 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003190 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3191 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3192 ALOGE("Failed to set remote submix device available, type %u, address %s",
3193 mix.mDeviceType, address.string());
3194 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003195 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003196 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3197 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003198 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003199 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003200 i, mixes.size(), type, address.string());
3201
3202 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3203 mix.mDeviceType, mix.mDeviceAddress,
3204 String8(), AUDIO_FORMAT_DEFAULT);
3205 if (device == nullptr) {
3206 res = INVALID_OPERATION;
3207 break;
3208 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003209
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003210 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003211 // First try to find an already opened output supporting the device
3212 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003213 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003214
Eric Laurentc529cf62020-04-17 18:19:10 -07003215 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003216 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003217 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3218 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003219 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003220 } else {
3221 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003222 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003223 }
3224 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003225 // If no output found, try to find a direct output profile supporting the device
3226 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3227 sp<HwModule> module = mHwModules[i];
3228 for (size_t j = 0;
3229 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3230 j++) {
3231 sp<IOProfile> profile = module->getOutputProfiles()[j];
3232 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3233 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3234 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3235 address.string());
3236 res = INVALID_OPERATION;
3237 } else {
3238 foundOutput = true;
3239 }
3240 }
3241 }
3242 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003243 if (res != NO_ERROR) {
3244 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003245 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003246 res = INVALID_OPERATION;
3247 break;
3248 } else if (!foundOutput) {
3249 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003250 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003251 res = INVALID_OPERATION;
3252 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003253 } else {
3254 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003255 }
Eric Laurentc722f302014-12-10 11:21:49 -08003256 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003257 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003258 if (res != NO_ERROR) {
3259 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003260 } else if (checkOutputs) {
3261 checkForDeviceAndOutputChanges();
3262 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003263 }
3264 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003265}
3266
3267status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3268{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003269 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003270 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003271 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003272 sp<HwModule> rSubmixModule;
3273 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003274 for (const auto& mix : mixes) {
3275 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003276
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003277 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003278 rSubmixModule = mHwModules.getModuleFromName(
3279 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3280 if (rSubmixModule == 0) {
3281 res = INVALID_OPERATION;
3282 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003283 }
3284 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003285
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003286 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003287
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003288 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003289 res = INVALID_OPERATION;
3290 continue;
3291 }
3292
Kevin Rocard04ed0462019-05-02 17:53:24 -07003293 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3294 if (getDeviceConnectionState(device, address.string()) ==
3295 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3296 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3297 address.string(), "remote-submix",
3298 AUDIO_FORMAT_DEFAULT);
3299 if (res != OK) {
3300 ALOGE("Error making RemoteSubmix device unavailable for mix "
3301 "with type %d, address %s", device, address.string());
3302 }
3303 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003304 }
jiabin5740f082019-08-19 15:08:30 -07003305 rSubmixModule->removeOutputProfile(address.c_str());
3306 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003307
Kevin Rocard153f92d2018-12-18 18:33:28 -08003308 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003309 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003310 res = INVALID_OPERATION;
3311 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003312 } else {
3313 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003314 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003315 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003316 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003317 if (res == NO_ERROR && checkOutputs) {
3318 checkForDeviceAndOutputChanges();
3319 updateCallAndOutputRouting();
3320 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003321 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003322}
3323
Mikhail Naganov100f0122018-11-29 11:22:16 -08003324void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3325{
3326 size_t i = 0;
3327 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3328 for (const auto& fmt : mManualSurroundFormats) {
3329 if (i++ != 0) dst->append(", ");
3330 std::string sfmt;
3331 FormatConverter::toString(fmt, sfmt);
3332 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3333 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3334 }
3335}
3336
Eric Laurentc529cf62020-04-17 18:19:10 -07003337// Returns true if all devices types match the predicate and are supported by one HW module
3338bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003339 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003340 std::function<bool(audio_devices_t)> predicate,
3341 const char *context) {
3342 for (size_t i = 0; i < devices.size(); i++) {
3343 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003344 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003345 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003346 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003347 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003348 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003349 return false;
3350 }
3351 }
3352 return true;
3353}
3354
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003355status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003356 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003357 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003358 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3359 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003360 }
3361 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003362 if (res != NO_ERROR) {
3363 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3364 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003365 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003366
3367 checkForDeviceAndOutputChanges();
3368 updateCallAndOutputRouting();
3369
3370 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003371}
3372
3373status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3374 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003375 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3376 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003377 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003378 __FUNCTION__, uid);
3379 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003380 }
3381
Eric Laurentc529cf62020-04-17 18:19:10 -07003382 checkForDeviceAndOutputChanges();
3383 updateCallAndOutputRouting();
3384
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003385 return res;
3386}
3387
Eric Laurent2517af32020-11-25 15:31:27 +01003388
jiabin0a488932020-08-07 17:32:40 -07003389status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3390 device_role_t role,
3391 const AudioDeviceTypeAddrVector &devices) {
3392 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3393 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003394
Eric Laurentc529cf62020-04-17 18:19:10 -07003395 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003396 return BAD_VALUE;
3397 }
jiabin0a488932020-08-07 17:32:40 -07003398 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003399 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003400 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3401 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003402 return status;
3403 }
3404
3405 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003406
3407 bool forceVolumeReeval = false;
3408 // FIXME: workaround for truncated touch sounds
3409 // to be removed when the problem is handled by system UI
3410 uint32_t delayMs = 0;
3411 if (strategy == mCommunnicationStrategy) {
3412 forceVolumeReeval = true;
3413 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3414 updateInputRouting();
3415 }
3416 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003417
3418 return NO_ERROR;
3419}
3420
3421void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3422{
3423 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003424 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003425 // Only apply special touch sound delay once
3426 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003427 }
3428 for (size_t i = 0; i < mOutputs.size(); i++) {
3429 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3430 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3431 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3432 // As done in setDeviceConnectionState, we could also fix default device issue by
3433 // preventing the force re-routing in case of default dev that distinguishes on address.
3434 // Let's give back to engine full device choice decision however.
3435 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003436 // Only apply special touch sound delay once
3437 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003438 }
3439 if (forceVolumeReeval && !newDevices.isEmpty()) {
3440 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3441 }
3442 }
3443}
3444
Eric Laurent2517af32020-11-25 15:31:27 +01003445void AudioPolicyManager::updateInputRouting() {
3446 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303447 // Skip for hotword recording as the input device switch
3448 // is handled within sound trigger HAL
3449 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3450 continue;
3451 }
Eric Laurent2517af32020-11-25 15:31:27 +01003452 auto newDevice = getNewInputDevice(activeDesc);
3453 // Force new input selection if the new device can not be reached via current input
3454 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3455 setInputDevice(activeDesc->mIoHandle, newDevice);
3456 } else {
3457 closeInput(activeDesc->mIoHandle);
3458 }
3459 }
3460}
3461
jiabin0a488932020-08-07 17:32:40 -07003462status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3463 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003464{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003465 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003466
jiabin0a488932020-08-07 17:32:40 -07003467 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003468 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003469 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3470 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003471 return status;
3472 }
3473
3474 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003475
3476 bool forceVolumeReeval = false;
3477 // FIXME: workaround for truncated touch sounds
3478 // to be removed when the problem is handled by system UI
3479 uint32_t delayMs = 0;
3480 if (strategy == mCommunnicationStrategy) {
3481 forceVolumeReeval = true;
3482 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3483 updateInputRouting();
3484 }
3485 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003486
3487 return NO_ERROR;
3488}
3489
jiabin0a488932020-08-07 17:32:40 -07003490status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3491 device_role_t role,
3492 AudioDeviceTypeAddrVector &devices) {
3493 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003494}
3495
Jiabin Huang3b98d322020-09-03 17:54:16 +00003496status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3497 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3498 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3499 dumpAudioDeviceTypeAddrVector(devices).c_str());
3500
Mikhail Naganov55773032020-10-01 15:08:13 -07003501 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003502 return BAD_VALUE;
3503 }
3504 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3505 ALOGW_IF(status != NO_ERROR,
3506 "Engine could not set preferred devices %s for audio source %d role %d",
3507 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3508
3509 return status;
3510}
3511
3512status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3513 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3514 ALOGV("%s() audioSource=%d role=%d %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 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3521 ALOGW_IF(status != NO_ERROR,
3522 "Engine could not add preferred devices %s for audio source %d role %d",
3523 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3524
Eric Laurent2517af32020-11-25 15:31:27 +01003525 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003526 return status;
3527}
3528
3529status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3530 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3531{
3532 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3533 dumpAudioDeviceTypeAddrVector(devices).c_str());
3534
Mikhail Naganov55773032020-10-01 15:08:13 -07003535 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003536 return BAD_VALUE;
3537 }
3538
3539 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3540 audioSource, role, devices);
3541 ALOGW_IF(status != NO_ERROR,
3542 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3543
Eric Laurent2517af32020-11-25 15:31:27 +01003544 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003545 return status;
3546}
3547
3548status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3549 device_role_t role) {
3550 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3551
3552 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3553 ALOGW_IF(status != NO_ERROR,
3554 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3555
Eric Laurent2517af32020-11-25 15:31:27 +01003556 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003557 return status;
3558}
3559
3560status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3561 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3562 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3563}
3564
Oscar Azucena90e77632019-11-27 17:12:28 -08003565status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003566 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003567 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003568 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3569 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003570 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003571 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3572 if (status != NO_ERROR) {
3573 ALOGE("%s() could not set device affinity for userId %d",
3574 __FUNCTION__, userId);
3575 return status;
3576 }
3577
3578 // reevaluate outputs for all devices
3579 checkForDeviceAndOutputChanges();
3580 updateCallAndOutputRouting();
3581
3582 return NO_ERROR;
3583}
3584
3585status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003586 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003587 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3588 if (status != NO_ERROR) {
3589 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3590 __FUNCTION__, userId);
3591 return status;
3592 }
3593
3594 // reevaluate outputs for all devices
3595 checkForDeviceAndOutputChanges();
3596 updateCallAndOutputRouting();
3597
3598 return NO_ERROR;
3599}
3600
Andy Hungc29d82b2018-10-05 12:23:17 -07003601void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003602{
Andy Hungc29d82b2018-10-05 12:23:17 -07003603 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003604 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003605 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003606 std::string stateLiteral;
3607 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003608 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003609 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3610 "communications", "media", "record", "dock", "system",
3611 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3612 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3613 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003614 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3615 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3616 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3617 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3618 dst->append(" (MANUAL: ");
3619 dumpManualSurroundFormats(dst);
3620 dst->append(")");
3621 }
3622 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003623 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003624 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3625 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003626 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003627 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003628
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003629 dst->append("\n");
3630 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3631 dst->append("\n");
3632 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003633 mHwModulesAll.dump(dst);
3634 mOutputs.dump(dst);
3635 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003636 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003637 mAudioPatches.dump(dst);
3638 mPolicyMixes.dump(dst);
3639 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003640
Kevin Rocardb99cc752019-03-21 20:52:24 -07003641 dst->appendFormat(" AllowedCapturePolicies:\n");
3642 for (auto& policy : mAllowedCapturePolicies) {
3643 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3644 }
3645
François Gaffiec005e562018-11-06 15:04:49 +01003646 dst->appendFormat("\nPolicy Engine dump:\n");
3647 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003648}
3649
3650status_t AudioPolicyManager::dump(int fd)
3651{
3652 String8 result;
3653 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003654 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003655 return NO_ERROR;
3656}
3657
Kevin Rocardb99cc752019-03-21 20:52:24 -07003658status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3659{
3660 mAllowedCapturePolicies[uid] = capturePolicy;
3661 return NO_ERROR;
3662}
3663
Eric Laurente552edb2014-03-10 17:42:56 -07003664// This function checks for the parameters which can be offloaded.
3665// This can be enhanced depending on the capability of the DSP and policy
3666// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003667audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003668{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003669 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003670 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003671 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003672 offloadInfo.format,
3673 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3674 offloadInfo.has_video);
3675
jiabin2b9d5a12021-12-10 01:06:29 +00003676 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003677 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003678 }
3679
3680 // See if there is a profile to support this.
3681 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003682 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003683 offloadInfo.sample_rate,
3684 offloadInfo.format,
3685 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003686 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3687 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003688 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3689 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3690 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003691 if (profile == nullptr) {
3692 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3693 }
3694 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3695 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3696 }
3697 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003698}
3699
Michael Chana94fbb22018-04-24 14:31:19 +10003700bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3701 const audio_attributes_t& attributes) {
3702 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003703 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003704 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3705 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003706 config.sample_rate,
3707 config.format,
3708 config.channel_mask,
3709 output_flags,
3710 true /* directOnly */);
3711 ALOGV("%s() profile %sfound with name: %s, "
3712 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3713 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003714 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003715 config.sample_rate, config.format, config.channel_mask, output_flags);
3716 return (profile != 0);
3717}
3718
jiabin2b9d5a12021-12-10 01:06:29 +00003719bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3720 bool durationIgnored) {
3721 if (mMasterMono) {
3722 return false; // no offloading if mono is set.
3723 }
3724
3725 // Check if offload has been disabled
3726 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3727 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3728 return false;
3729 }
3730
3731 // Check if stream type is music, then only allow offload as of now.
3732 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3733 {
3734 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3735 return false;
3736 }
3737
3738 //TODO: enable audio offloading with video when ready
3739 const bool allowOffloadWithVideo =
3740 property_get_bool("audio.offload.video", false /* default_value */);
3741 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3742 ALOGV("%s: has_video == true, returning false", __func__);
3743 return false;
3744 }
3745
3746 //If duration is less than minimum value defined in property, return false
3747 const int min_duration_secs = property_get_int32(
3748 "audio.offload.min.duration.secs", -1 /* default_value */);
3749 if (!durationIgnored) {
3750 if (min_duration_secs >= 0) {
3751 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3752 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3753 __func__, min_duration_secs);
3754 return false;
3755 }
3756 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3757 ALOGV("%s: Offload denied by duration < default min(=%u)",
3758 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3759 return false;
3760 }
3761 }
3762
3763 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3764 // creating an offloaded track and tearing it down immediately after start when audioflinger
3765 // detects there is an active non offloadable effect.
3766 // FIXME: We should check the audio session here but we do not have it in this context.
3767 // This may prevent offloading in rare situations where effects are left active by apps
3768 // in the background.
3769 if (mEffects.isNonOffloadableEffectEnabled()) {
3770 return false;
3771 }
3772
3773 return true;
3774}
3775
3776audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3777 const audio_config_t *config) {
3778 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3779 offloadInfo.format = config->format;
3780 offloadInfo.sample_rate = config->sample_rate;
3781 offloadInfo.channel_mask = config->channel_mask;
3782 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3783 offloadInfo.has_video = false;
3784 offloadInfo.is_streaming = false;
3785 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3786
3787 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3788 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3789 audio_flags_to_audio_output_flags(attr->flags, &flags);
3790 // only retain flags that will drive compressed offload or passthrough
3791 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3792 if (offloadPossible) {
3793 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3794 }
3795 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3796
jiabinc8f7dfc2022-01-06 18:42:08 +00003797 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003798 for (const auto& hwModule : mHwModules) {
3799 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003800 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003801 config->sample_rate, nullptr /*updatedSamplingRate*/,
3802 config->format, nullptr /*updatedFormat*/,
3803 config->channel_mask, nullptr /*updatedChannelMask*/,
3804 flags)) {
3805 continue;
3806 }
3807 // reject profiles not corresponding to a device currently available
3808 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3809 continue;
3810 }
3811 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3812 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003813 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003814 != AUDIO_DIRECT_NOT_SUPPORTED) {
3815 // Already reports offload gapless supported. No need to report offload support.
3816 continue;
3817 }
3818 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3819 != AUDIO_OUTPUT_FLAG_NONE) {
3820 // If offload gapless is reported, no need to report offload support.
3821 directMode = (audio_direct_mode_t) ((directMode &
3822 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3823 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3824 } else {
3825 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3826 }
3827 } else {
3828 directMode = (audio_direct_mode_t) (directMode |
3829 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3830 }
3831 }
3832 }
3833 return directMode;
3834}
3835
Dorin Drimusf2196d82022-01-03 12:11:18 +01003836status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3837 AudioProfileVector& audioProfilesVector) {
3838 AudioDeviceTypeAddrVector devices;
3839 status_t status = getDevicesForAttributes(*attr, &devices);
3840 if (status != OK) {
3841 return status;
3842 }
3843 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3844 if (devices.empty()) {
3845 return OK; // no output devices for the attributes
3846 }
3847
3848 for (const auto& hwModule : mHwModules) {
3849 for (const auto& curProfile : hwModule->getOutputProfiles()) {
3850 if (!curProfile->asAudioPort()->isDirectOutput()) {
3851 continue;
3852 }
3853 // Allow only profiles that support all the available and routed devices
3854 DeviceVector supportedDevices = curProfile->getSupportedDevices();
3855 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
3856 != devices.size()) {
3857 continue;
3858 }
3859
3860 const auto audioProfiles = curProfile->asAudioPort()->getAudioProfiles();
3861 ALOGV("%s: found direct profile (%s) with %zu audio profiles.",
3862 __func__, curProfile->getTagName().c_str(), audioProfiles.size());
3863 for (const auto& audioProfile : audioProfiles) {
3864 if (audioProfile->isValid() && !audioProfilesVector.contains(audioProfile)
3865 // TODO - why do we have same PCM format with both dynamic and non dynamic format
3866 && audioProfile->isDynamicFormat()) {
3867 ALOGV("%s: adding audio profile with encoding (%d).",
3868 __func__, audioProfile->getFormat());
3869 audioProfilesVector.add(audioProfile);
3870 }
3871 }
3872 }
3873 }
3874 return NO_ERROR;
3875}
3876
Eric Laurent6a94d692014-05-20 11:18:06 -07003877status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3878 audio_port_type_t type,
3879 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003880 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003881 unsigned int *generation)
3882{
jiabin19cdba52020-11-24 11:28:58 -08003883 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3884 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003885 return BAD_VALUE;
3886 }
3887 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003888 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003889 *num_ports = 0;
3890 }
3891
3892 size_t portsWritten = 0;
3893 size_t portsMax = *num_ports;
3894 *num_ports = 0;
3895 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003896 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3897 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003898 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003899 for (const auto& dev : mAvailableOutputDevices) {
3900 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003901 continue;
3902 }
3903 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003904 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003905 }
3906 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003907 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003908 }
3909 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003910 for (const auto& dev : mAvailableInputDevices) {
3911 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003912 continue;
3913 }
3914 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003915 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003916 }
3917 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003918 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003919 }
3920 }
3921 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3922 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3923 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3924 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3925 }
3926 *num_ports += mInputs.size();
3927 }
3928 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003929 size_t numOutputs = 0;
3930 for (size_t i = 0; i < mOutputs.size(); i++) {
3931 if (!mOutputs[i]->isDuplicated()) {
3932 numOutputs++;
3933 if (portsWritten < portsMax) {
3934 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3935 }
3936 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003937 }
Eric Laurent84c70242014-06-23 08:46:27 -07003938 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003939 }
3940 }
3941 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003942 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003943 return NO_ERROR;
3944}
3945
jiabin19cdba52020-11-24 11:28:58 -08003946status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003947{
Eric Laurent99fcae42018-05-17 16:59:18 -07003948 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3949 return BAD_VALUE;
3950 }
3951 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3952 if (dev != 0) {
3953 dev->toAudioPort(port);
3954 return NO_ERROR;
3955 }
3956 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3957 if (dev != 0) {
3958 dev->toAudioPort(port);
3959 return NO_ERROR;
3960 }
3961 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3962 if (out != 0) {
3963 out->toAudioPort(port);
3964 return NO_ERROR;
3965 }
3966 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3967 if (in != 0) {
3968 in->toAudioPort(port);
3969 return NO_ERROR;
3970 }
3971 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003972}
3973
François Gaffieafd4cea2019-11-18 15:50:22 +01003974status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3975 audio_patch_handle_t *handle,
3976 uid_t uid, uint32_t delayMs,
3977 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003978{
François Gaffieafd4cea2019-11-18 15:50:22 +01003979 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 if (handle == NULL || patch == NULL) {
3981 return BAD_VALUE;
3982 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003983 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003984
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003985 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003986 return BAD_VALUE;
3987 }
3988 // only one source per audio patch supported for now
3989 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 return INVALID_OPERATION;
3991 }
Eric Laurent874c42872014-08-08 15:13:39 -07003992
3993 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 return INVALID_OPERATION;
3995 }
Eric Laurent874c42872014-08-08 15:13:39 -07003996 for (size_t i = 0; i < patch->num_sinks; i++) {
3997 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3998 return INVALID_OPERATION;
3999 }
4000 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004001
4002 sp<AudioPatch> patchDesc;
4003 ssize_t index = mAudioPatches.indexOfKey(*handle);
4004
François Gaffieafd4cea2019-11-18 15:50:22 +01004005 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4006 patch->sources[0].role,
4007 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004008#if LOG_NDEBUG == 0
4009 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004010 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4011 patch->sinks[i].role,
4012 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004013 }
4014#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004015
4016 if (index >= 0) {
4017 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004018 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4019 __func__, mUidCached, patchDesc->getUid(), uid);
4020 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004021 return INVALID_OPERATION;
4022 }
4023 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004024 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 }
4026
4027 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004028 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004029 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004030 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004031 return BAD_VALUE;
4032 }
Eric Laurent84c70242014-06-23 08:46:27 -07004033 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4034 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004035 if (patchDesc != 0) {
4036 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004037 ALOGV("%s source id differs for patch current id %d new id %d",
4038 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004039 return BAD_VALUE;
4040 }
4041 }
Eric Laurent874c42872014-08-08 15:13:39 -07004042 DeviceVector devices;
4043 for (size_t i = 0; i < patch->num_sinks; i++) {
4044 // Only support mix to devices connection
4045 // TODO add support for mix to mix connection
4046 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004047 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004048 return INVALID_OPERATION;
4049 }
4050 sp<DeviceDescriptor> devDesc =
4051 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4052 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004053 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004054 return BAD_VALUE;
4055 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004056
François Gaffie11d30102018-11-02 16:09:09 +01004057 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004058 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004059 NULL, // updatedSamplingRate
4060 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004061 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004062 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004063 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004064 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004065 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004066 return INVALID_OPERATION;
4067 }
4068 devices.add(devDesc);
4069 }
4070 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004071 return INVALID_OPERATION;
4072 }
Eric Laurent874c42872014-08-08 15:13:39 -07004073
Eric Laurent6a94d692014-05-20 11:18:06 -07004074 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004075 ALOGV("%s setting device %s on output %d",
4076 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004077 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004078 index = mAudioPatches.indexOfKey(*handle);
4079 if (index >= 0) {
4080 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004081 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004082 }
4083 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004084 patchDesc->setUid(uid);
4085 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004086 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004087 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004088 return INVALID_OPERATION;
4089 }
4090 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4091 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4092 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004093 // only one sink supported when connecting an input device to a mix
4094 if (patch->num_sinks > 1) {
4095 return INVALID_OPERATION;
4096 }
François Gaffie53615e22015-03-19 09:24:12 +01004097 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004098 if (inputDesc == NULL) {
4099 return BAD_VALUE;
4100 }
4101 if (patchDesc != 0) {
4102 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4103 return BAD_VALUE;
4104 }
4105 }
François Gaffie11d30102018-11-02 16:09:09 +01004106 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004107 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004108 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004109 return BAD_VALUE;
4110 }
4111
François Gaffie11d30102018-11-02 16:09:09 +01004112 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004113 patch->sinks[0].sample_rate,
4114 NULL, /*updatedSampleRate*/
4115 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004116 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004117 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004118 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004119 // FIXME for the parameter type,
4120 // and the NONE
4121 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004122 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 return INVALID_OPERATION;
4124 }
4125 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004126 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004127 device->toString().c_str(), inputDesc->mIoHandle);
4128 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004129 index = mAudioPatches.indexOfKey(*handle);
4130 if (index >= 0) {
4131 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004132 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004133 }
4134 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004135 patchDesc->setUid(uid);
4136 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004138 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004139 return INVALID_OPERATION;
4140 }
4141 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4142 // device to device connection
4143 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004144 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004145 return BAD_VALUE;
4146 }
4147 }
François Gaffie11d30102018-11-02 16:09:09 +01004148 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004149 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004150 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004151 return BAD_VALUE;
4152 }
Eric Laurent874c42872014-08-08 15:13:39 -07004153
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 //update source and sink with our own data as the data passed in the patch may
4155 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004156 PatchBuilder patchBuilder;
4157 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004158
4159 // if first sink is to MSD, establish single MSD patch
4160 if (getMsdAudioOutDevices().contains(
4161 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4162 ALOGV("%s patching to MSD", __FUNCTION__);
4163 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4164 goto installPatch;
4165 }
4166
François Gaffieafd4cea2019-11-18 15:50:22 +01004167 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4168 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004169
Eric Laurent874c42872014-08-08 15:13:39 -07004170 for (size_t i = 0; i < patch->num_sinks; i++) {
4171 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004172 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004173 return INVALID_OPERATION;
4174 }
François Gaffie11d30102018-11-02 16:09:09 +01004175 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004176 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004177 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004178 return BAD_VALUE;
4179 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004180 audio_port_config sinkPortConfig = {};
4181 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4182 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004183
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004184 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4185 // volume management purpose (tracking activity)
4186 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4187 // in config XML to reach the sink so that is can be declared as available.
4188 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4189 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4190 if (sourceDesc != nullptr) {
4191 // take care of dynamic routing for SwOutput selection,
4192 audio_attributes_t attributes = sourceDesc->attributes();
4193 audio_stream_type_t stream = sourceDesc->stream();
4194 audio_attributes_t resultAttr;
4195 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4196 config.sample_rate = sourceDesc->config().sample_rate;
4197 config.channel_mask = sourceDesc->config().channel_mask;
4198 config.format = sourceDesc->config().format;
4199 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4200 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4201 bool isRequestedDeviceForExclusiveUse = false;
4202 output_type_t outputType;
4203 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4204 &stream, sourceDesc->uid(), &config, &flags,
4205 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4206 nullptr, &outputType);
4207 if (output == AUDIO_IO_HANDLE_NONE) {
4208 ALOGV("%s no output for device %s",
4209 __FUNCTION__, sinkDevice->toString().c_str());
4210 return INVALID_OPERATION;
4211 }
4212 outputDesc = mOutputs.valueFor(output);
4213 if (outputDesc->isDuplicated()) {
4214 ALOGE("%s output is duplicated", __func__);
4215 return INVALID_OPERATION;
4216 }
4217 sourceDesc->setSwOutput(outputDesc);
4218 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004219 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004220 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004221 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004222 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004223 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4224 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004225 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4226 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004227 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4228 (sourceDesc != nullptr &&
4229 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004230 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004231 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004232 return INVALID_OPERATION;
4233 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004234 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004235 SortedVector<audio_io_handle_t> outputs =
4236 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4237 // if the sink device is reachable via an opened output stream, request to
4238 // go via this output stream by adding a second source to the patch
4239 // description
4240 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004241 if (output != AUDIO_IO_HANDLE_NONE) {
4242 outputDesc = mOutputs.valueFor(output);
4243 if (outputDesc->isDuplicated()) {
4244 ALOGV("%s output for device %s is duplicated",
4245 __FUNCTION__, sinkDevice->toString().c_str());
4246 return INVALID_OPERATION;
4247 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004248 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004249 }
4250 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004251 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004252 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004253 // for volume control, we may need a valid stream
4254 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4255 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4256 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004257 }
Eric Laurent83b88082014-06-20 18:31:16 -07004258 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004259 }
4260 // TODO: check from routing capabilities in config file and other conflicting patches
4261
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004262installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004263 status_t status = installPatch(
4264 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004265 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004266 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004267 return INVALID_OPERATION;
4268 }
4269 } else {
4270 return BAD_VALUE;
4271 }
4272 } else {
4273 return BAD_VALUE;
4274 }
4275 return NO_ERROR;
4276}
4277
4278status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4279 uid_t uid)
4280{
4281 ALOGV("releaseAudioPatch() patch %d", handle);
4282
4283 ssize_t index = mAudioPatches.indexOfKey(handle);
4284
4285 if (index < 0) {
4286 return BAD_VALUE;
4287 }
4288 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004289 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4290 __func__, mUidCached, patchDesc->getUid(), uid);
4291 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 return INVALID_OPERATION;
4293 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004294 return releaseAudioPatchInternal(handle);
4295}
Eric Laurent6a94d692014-05-20 11:18:06 -07004296
François Gaffieafd4cea2019-11-18 15:50:22 +01004297status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4298 uint32_t delayMs)
4299{
4300 ALOGV("%s patch %d", __func__, handle);
4301 if (mAudioPatches.indexOfKey(handle) < 0) {
4302 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4303 return BAD_VALUE;
4304 }
4305 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004306 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004309 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004310 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004311 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 return BAD_VALUE;
4313 }
4314
François Gaffie11d30102018-11-02 16:09:09 +01004315 setOutputDevices(outputDesc,
4316 getNewOutputDevices(outputDesc, true /*fromCache*/),
4317 true,
4318 0,
4319 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004320 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4321 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004322 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004324 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004325 return BAD_VALUE;
4326 }
4327 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004328 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004329 true,
4330 NULL);
4331 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004332 status_t status =
4333 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4334 ALOGV("%s patch panel returned %d patchHandle %d",
4335 __func__, status, patchDesc->getAfHandle());
4336 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004337 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004338 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004339 // SW Bridge
4340 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4341 sp<SwAudioOutputDescriptor> outputDesc =
4342 mOutputs.getOutputFromId(patch->sources[1].id);
4343 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004344 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4345 // releaseOutput has already called closeOuput in case of direct output
4346 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004347 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004348 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4349 // force SwOutput patch removal as AF counter part patch has already gone.
4350 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4351 removeAudioPatch(outputDesc->getPatchHandle());
4352 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004353 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4354 setOutputDevices(outputDesc,
4355 getNewOutputDevices(outputDesc, true /*fromCache*/),
4356 true, /*force*/
4357 0,
4358 NULL);
4359 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004360 } else {
4361 return BAD_VALUE;
4362 }
4363 } else {
4364 return BAD_VALUE;
4365 }
4366 return NO_ERROR;
4367}
4368
4369status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4370 struct audio_patch *patches,
4371 unsigned int *generation)
4372{
François Gaffie53615e22015-03-19 09:24:12 +01004373 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004374 return BAD_VALUE;
4375 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004376 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004377 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004378}
4379
Eric Laurente1715a42014-05-20 11:30:42 -07004380status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004381{
Eric Laurente1715a42014-05-20 11:30:42 -07004382 ALOGV("setAudioPortConfig()");
4383
4384 if (config == NULL) {
4385 return BAD_VALUE;
4386 }
4387 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4388 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004389 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4390 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004391 }
4392
Eric Laurenta121f902014-06-03 13:32:54 -07004393 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004394 if (config->type == AUDIO_PORT_TYPE_MIX) {
4395 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004396 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004397 if (outputDesc == NULL) {
4398 return BAD_VALUE;
4399 }
Eric Laurent84c70242014-06-23 08:46:27 -07004400 ALOG_ASSERT(!outputDesc->isDuplicated(),
4401 "setAudioPortConfig() called on duplicated output %d",
4402 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004403 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004404 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004405 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004406 if (inputDesc == NULL) {
4407 return BAD_VALUE;
4408 }
Eric Laurenta121f902014-06-03 13:32:54 -07004409 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004410 } else {
4411 return BAD_VALUE;
4412 }
4413 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4414 sp<DeviceDescriptor> deviceDesc;
4415 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4416 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4417 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4418 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4419 } else {
4420 return BAD_VALUE;
4421 }
4422 if (deviceDesc == NULL) {
4423 return BAD_VALUE;
4424 }
Eric Laurenta121f902014-06-03 13:32:54 -07004425 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004426 } else {
4427 return BAD_VALUE;
4428 }
4429
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004430 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004431 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4432 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004433 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004434 audioPortConfig->toAudioPortConfig(&newConfig, config);
4435 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004436 }
Eric Laurenta121f902014-06-03 13:32:54 -07004437 if (status != NO_ERROR) {
4438 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004439 }
Eric Laurente1715a42014-05-20 11:30:42 -07004440
4441 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004442}
4443
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004444void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4445{
Eric Laurentd60560a2015-04-10 11:31:20 -07004446 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004447 clearAudioPatches(uid);
4448 clearSessionRoutes(uid);
4449}
4450
Eric Laurent6a94d692014-05-20 11:18:06 -07004451void AudioPolicyManager::clearAudioPatches(uid_t uid)
4452{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004453 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004455 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004456 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 }
4458 }
4459}
4460
François Gaffiec005e562018-11-06 15:04:49 +01004461void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004462{
François Gaffiec005e562018-11-06 15:04:49 +01004463 // Take the first attributes following the product strategy as it is used to retrieve the routed
4464 // device. All attributes wihin a strategy follows the same "routing strategy"
4465 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4466 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004467 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004468 for (size_t j = 0; j < mOutputs.size(); j++) {
4469 if (mOutputs.keyAt(j) == ouptutToSkip) {
4470 continue;
4471 }
4472 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004473 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004474 continue;
4475 }
4476 // If the default device for this strategy is on another output mix,
4477 // invalidate all tracks in this strategy to force re connection.
4478 // Otherwise select new device on the output mix.
4479 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004480 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4481 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004482 }
4483 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004484 setOutputDevices(
4485 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004486 }
4487 }
4488}
4489
4490void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4491{
4492 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004493 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004494 for (size_t i = 0; i < mOutputs.size(); i++) {
4495 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004496 for (const auto& client : outputDesc->getClientIterable()) {
4497 if (client->hasPreferredDevice() && client->uid() == uid) {
4498 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004499 auto clientStrategy = client->strategy();
4500 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4501 end(affectedStrategies)) {
4502 continue;
4503 }
4504 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004505 }
4506 }
4507 }
4508 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004509 for (const auto& strategy : affectedStrategies) {
4510 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004511 }
4512
4513 // remove input routes associated with this uid
4514 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004515 for (size_t i = 0; i < mInputs.size(); i++) {
4516 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004517 for (const auto& client : inputDesc->getClientIterable()) {
4518 if (client->hasPreferredDevice() && client->uid() == uid) {
4519 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4520 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004521 }
4522 }
4523 }
4524 // reroute inputs if necessary
4525 SortedVector<audio_io_handle_t> inputsToClose;
4526 for (size_t i = 0; i < mInputs.size(); i++) {
4527 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004528 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004529 inputsToClose.add(inputDesc->mIoHandle);
4530 }
4531 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004532 for (const auto& input : inputsToClose) {
4533 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004534 }
4535}
4536
Eric Laurentd60560a2015-04-10 11:31:20 -07004537void AudioPolicyManager::clearAudioSources(uid_t uid)
4538{
4539 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004540 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4541 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004542 stopAudioSource(mAudioSources.keyAt(i));
4543 }
4544 }
4545}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004546
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004547status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4548 audio_io_handle_t *ioHandle,
4549 audio_devices_t *device)
4550{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004551 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4552 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004553 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004554 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004555
François Gaffiedf372692015-03-19 10:43:27 +01004556 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004557}
4558
Eric Laurentd60560a2015-04-10 11:31:20 -07004559status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004560 const audio_attributes_t *attributes,
4561 audio_port_handle_t *portId,
4562 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004563{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004564 ALOGV("%s", __FUNCTION__);
4565 *portId = AUDIO_PORT_HANDLE_NONE;
4566
4567 if (source == NULL || attributes == NULL || portId == NULL) {
4568 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4569 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004570 return BAD_VALUE;
4571 }
4572
Eric Laurentd60560a2015-04-10 11:31:20 -07004573 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4574 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004575 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4576 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004577 return INVALID_OPERATION;
4578 }
4579
François Gaffie11d30102018-11-02 16:09:09 +01004580 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004581 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004582 String8(source->ext.device.address),
4583 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004584 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004585 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004586 return BAD_VALUE;
4587 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004588
jiabin4ef93452019-09-10 14:29:54 -07004589 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004590
François Gaffieaaac0fd2018-11-22 17:56:39 +01004591 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004592 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004593 mEngine->getStreamTypeForAttributes(*attributes),
4594 mEngine->getProductStrategyForAttributes(*attributes),
4595 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004596
4597 status_t status = connectAudioSource(sourceDesc);
4598 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004599 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004600 }
4601 return status;
4602}
4603
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004604status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004605{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004606 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004607
4608 // make sure we only have one patch per source.
4609 disconnectAudioSource(sourceDesc);
4610
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004611 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004612 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4613 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4614 sourceDesc->srcDevice()->type(),
4615 String8(sourceDesc->srcDevice()->address().c_str()),
4616 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004617 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004618 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004619 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004620 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004621 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4622 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4623 return INVALID_OPERATION;
4624 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004625 PatchBuilder patchBuilder;
4626 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4627 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4628 status_t status =
4629 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4630 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4631 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4632 return INVALID_OPERATION;
4633 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004634 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004635 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4636 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4637 if (swOutput != 0) {
4638 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004639 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004640 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004641 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004642 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004643 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004644 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004645 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004646 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004647 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004648 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004649 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004650 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4651 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004652 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004653 if (delayMs != 0) {
4654 usleep(delayMs * 1000);
4655 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 } else {
4657 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4658 if (hwOutputDesc != 0) {
4659 // create Hwoutput and add to mHwOutputs
4660 } else {
4661 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4662 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004663 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004664 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004665
4666FailureSourceActive:
4667 swOutput->stop();
4668 releaseOutput(sourceDesc->portId());
4669FailureSourceAdded:
4670 sourceDesc->setSwOutput(nullptr);
4671FailureReleasePatch:
4672 releaseAudioPatchInternal(handle);
4673 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004674}
4675
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004676status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004677{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004678 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4679 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004680 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004681 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004682 return BAD_VALUE;
4683 }
4684 status_t status = disconnectAudioSource(sourceDesc);
4685
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004686 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004687 return status;
4688}
4689
Andy Hung2ddee192015-12-18 17:34:44 -08004690status_t AudioPolicyManager::setMasterMono(bool mono)
4691{
4692 if (mMasterMono == mono) {
4693 return NO_ERROR;
4694 }
4695 mMasterMono = mono;
4696 // if enabling mono we close all offloaded devices, which will invalidate the
4697 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4698 // for recreating the new AudioTrack as non-offloaded PCM.
4699 //
4700 // If disabling mono, we leave all tracks as is: we don't know which clients
4701 // and tracks are able to be recreated as offloaded. The next "song" should
4702 // play back offloaded.
4703 if (mMasterMono) {
4704 Vector<audio_io_handle_t> offloaded;
4705 for (size_t i = 0; i < mOutputs.size(); ++i) {
4706 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4707 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4708 offloaded.push(desc->mIoHandle);
4709 }
4710 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004711 for (const auto& handle : offloaded) {
4712 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004713 }
4714 }
4715 // update master mono for all remaining outputs
4716 for (size_t i = 0; i < mOutputs.size(); ++i) {
4717 updateMono(mOutputs.keyAt(i));
4718 }
4719 return NO_ERROR;
4720}
4721
4722status_t AudioPolicyManager::getMasterMono(bool *mono)
4723{
4724 *mono = mMasterMono;
4725 return NO_ERROR;
4726}
4727
Eric Laurentac9cef52017-06-09 15:46:26 -07004728float AudioPolicyManager::getStreamVolumeDB(
4729 audio_stream_type_t stream, int index, audio_devices_t device)
4730{
jiabin9a3361e2019-10-01 09:38:30 -07004731 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004732}
4733
jiabin81772902018-04-02 17:52:27 -07004734status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4735 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004736 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004737{
Kriti Dang6537def2021-03-02 13:46:59 +01004738 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4739 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004740 return BAD_VALUE;
4741 }
Kriti Dang6537def2021-03-02 13:46:59 +01004742 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4743 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004744
4745 size_t formatsWritten = 0;
4746 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004747
Kriti Dang6537def2021-03-02 13:46:59 +01004748 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004749 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4750 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004751 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004752 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004753 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004754 bool formatEnabled = true;
4755 switch (forceUse) {
4756 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004757 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004758 break;
4759 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4760 formatEnabled = false;
4761 break;
4762 default: // AUTO or ALWAYS => true
4763 break;
jiabin81772902018-04-02 17:52:27 -07004764 }
4765 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4766 }
jiabin81772902018-04-02 17:52:27 -07004767 }
4768 return NO_ERROR;
4769}
4770
Kriti Dang6537def2021-03-02 13:46:59 +01004771status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4772 audio_format_t *surroundFormats) {
4773 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4774 return BAD_VALUE;
4775 }
4776 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4777 __func__, *numSurroundFormats, surroundFormats);
4778
4779 size_t formatsWritten = 0;
4780 size_t formatsMax = *numSurroundFormats;
4781 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4782
4783 // Return formats from all device profiles that have already been resolved by
4784 // checkOutputsForDevice().
4785 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4786 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4787 audio_devices_t deviceType = device->type();
4788 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4789 // returns formats reported by HDMI devices.
4790 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4791 continue;
4792 }
4793 // Formats reported by sink devices
4794 std::unordered_set<audio_format_t> formatset;
4795 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4796 formatset.insert(it->second.begin(), it->second.end());
4797 }
4798
4799 // Formats hard-coded in the in policy configuration file (if any).
4800 FormatVector encodedFormats = device->encodedFormats();
4801 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4802 // Filter the formats which are supported by the vendor hardware.
4803 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4804 if (mConfig.getSurroundFormats().count(*it) != 0) {
4805 formats.insert(*it);
4806 } else {
4807 for (const auto& pair : mConfig.getSurroundFormats()) {
4808 if (pair.second.count(*it) != 0) {
4809 formats.insert(pair.first);
4810 break;
4811 }
4812 }
4813 }
4814 }
4815 }
4816 *numSurroundFormats = formats.size();
4817 for (const auto& format: formats) {
4818 if (formatsWritten < formatsMax) {
4819 surroundFormats[formatsWritten++] = format;
4820 }
4821 }
4822 return NO_ERROR;
4823}
4824
jiabin81772902018-04-02 17:52:27 -07004825status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4826{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004827 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004828 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4829 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004830 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004831 return BAD_VALUE;
4832 }
4833
Mikhail Naganov100f0122018-11-29 11:22:16 -08004834 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4835 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004836 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004837 return INVALID_OPERATION;
4838 }
4839
Mikhail Naganov100f0122018-11-29 11:22:16 -08004840 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004841 return NO_ERROR;
4842 }
4843
Mikhail Naganov100f0122018-11-29 11:22:16 -08004844 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004845 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004846 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004847 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004848 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004849 }
4850 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004851 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004852 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004853 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004854 }
4855 }
4856
4857 sp<SwAudioOutputDescriptor> outputDesc;
4858 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004859 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4860 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004861 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4862 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004863 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004864 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004865 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4866 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4867 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004868 name.c_str(),
4869 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004870 if (status != NO_ERROR) {
4871 continue;
4872 }
4873 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4874 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4875 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004876 name.c_str(),
4877 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004878 profileUpdated |= (status == NO_ERROR);
4879 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004880 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004881 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004882 AUDIO_DEVICE_IN_HDMI);
4883 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4884 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004885 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004886 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004887 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4888 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4889 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004890 name.c_str(),
4891 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004892 if (status != NO_ERROR) {
4893 continue;
4894 }
4895 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4896 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4897 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004898 name.c_str(),
4899 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004900 profileUpdated |= (status == NO_ERROR);
4901 }
4902
jiabin81772902018-04-02 17:52:27 -07004903 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004904 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004905 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004906 }
4907
4908 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4909}
4910
Eric Laurent5ada82e2019-08-29 17:53:54 -07004911void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004912{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004913 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004914 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004915 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004916 }
4917}
4918
jiabin6012f912018-11-02 17:06:30 -07004919bool AudioPolicyManager::isHapticPlaybackSupported()
4920{
4921 for (const auto& hwModule : mHwModules) {
4922 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4923 for (const auto &outProfile : outputProfiles) {
4924 struct audio_port audioPort;
4925 outProfile->toAudioPort(&audioPort);
4926 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4927 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4928 return true;
4929 }
4930 }
4931 }
4932 }
4933 return false;
4934}
4935
Eric Laurent8340e672019-11-06 11:01:08 -08004936bool AudioPolicyManager::isCallScreenModeSupported()
4937{
4938 return getConfig().isCallScreenModeSupported();
4939}
4940
4941
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004942status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004943{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004944 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004945 if (!sourceDesc->isConnected()) {
4946 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4947 return NO_ERROR;
4948 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004949 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4950 if (swOutput != 0) {
4951 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004952 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004953 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004954 }
jiabinbce0c1d2020-10-05 11:20:18 -07004955 if (releaseOutput(sourceDesc->portId())) {
4956 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4957 // no need to release audio patch here but just return NO_ERROR.
4958 return NO_ERROR;
4959 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004960 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004961 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004962 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004963 // close Hwoutput and remove from mHwOutputs
4964 } else {
4965 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4966 }
4967 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004968 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4969 sourceDesc->disconnect();
4970 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004971}
4972
François Gaffiec005e562018-11-06 15:04:49 +01004973sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4974 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004975{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004976 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004977 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004978 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004979 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004980 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4981 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004982 source = sourceDesc;
4983 break;
4984 }
4985 }
4986 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004987}
4988
Eric Laurent39095982021-08-24 18:29:27 +02004989/* static */
4990bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
4991 switch (channels) {
4992 case AUDIO_CHANNEL_OUT_5POINT1:
4993 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
4994 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
4995 case AUDIO_CHANNEL_OUT_7POINT1:
4996 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
4997 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
4998 return true;
4999 default:
5000 return false;
5001 }
5002}
5003
Eric Laurentb4f42a92022-01-17 17:37:31 +01005004bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005005 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005006 const AudioDeviceTypeAddrVector &devices,
5007 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005008{
5009 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5010 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005011 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005012 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005013 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5014 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5015 return false;
5016 }
5017 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5018 return false;
5019 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005020 }
5021
5022 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005023 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5024 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005025 // to the specified devices must exist.
5026 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005027 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005028 if (profile == nullptr) {
5029 return false;
5030 }
5031
5032 // The caller can have the audio config criteria ignored by either passing a null ptr or
5033 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005034 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005035 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005036 // If the spatializer output is already opened, only channel masks included in the
5037 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005038
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005039 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005040 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005041 return false;
5042 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005043 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5044 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005045 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005046 != config->channel_mask) {
5047 return false;
5048 }
5049 }
5050 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005051 return true;
5052}
5053
5054void AudioPolicyManager::checkVirtualizerClientRoutes() {
5055 std::set<audio_stream_type_t> streamsToInvalidate;
5056 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005057 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5058 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005059 audio_attributes_t attr = client->attributes();
5060 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5061 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5062 audio_config_base_t clientConfig = client->config();
5063 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005064 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005065 && canBeSpatializedInt(&attr, &config,
5066 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005067 streamsToInvalidate.insert(client->stream());
5068 }
5069 }
5070 }
5071
5072 for (audio_stream_type_t stream : streamsToInvalidate) {
5073 mpClientInterface->invalidateStream(stream);
5074 }
5075}
5076
Eric Laurentfa0f6742021-08-17 18:39:44 +02005077status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005078 const audio_attributes_t *attr,
5079 audio_io_handle_t *output) {
5080 *output = AUDIO_IO_HANDLE_NONE;
5081
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005082 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5083 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5084 audio_config_t *configPtr = nullptr;
5085 audio_config_t config;
5086 if (mixerConfig != nullptr) {
5087 config = audio_config_initializer(mixerConfig);
5088 configPtr = &config;
5089 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005090 if (!canBeSpatializedInt(
5091 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005092 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005093 return BAD_VALUE;
5094 }
5095
5096 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005097 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005098 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005099 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005100 return BAD_VALUE;
5101 }
5102
Eric Laurent39095982021-08-24 18:29:27 +02005103 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5104 && configPtr != nullptr
5105 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5106 *output = mSpatializerOutput->mIoHandle;
5107 ALOGV("%s returns current spatializer output %d", __func__, *output);
5108 return NO_ERROR;
5109 }
5110 mSpatializerOutput.clear();
5111 for (size_t i = 0; i < mOutputs.size(); i++) {
5112 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5113 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005114 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005115 mSpatializerOutput = desc;
5116 break;
5117 }
5118 }
5119 if (mSpatializerOutput == nullptr) {
5120 ALOGW("%s no opened spatializer output for profile %s",
5121 __func__, profile->getName().c_str());
5122 return BAD_VALUE;
5123 }
5124
5125 if (configPtr != nullptr
5126 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5127 audio_config_base_t savedMixerConfig = {
5128 .sample_rate = mSpatializerOutput->getSamplingRate(),
5129 .format = mSpatializerOutput->getFormat(),
5130 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5131 };
5132 DeviceVector savedDevices = mSpatializerOutput->devices();
5133
Eric Laurentb4f42a92022-01-17 17:37:31 +01005134 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5135 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005136
Eric Laurentb4f42a92022-01-17 17:37:31 +01005137 closeOutput(mSpatializerOutput->mIoHandle);
5138 //from now on mSpatializerOutput is null
5139
5140 sp<SwAudioOutputDescriptor> desc =
5141 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5142 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005143 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005144 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5145 if (desc == nullptr) {
5146 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005147 } else {
5148 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005149 }
5150 mPreviousOutputs = mOutputs;
5151 mpClientInterface->onAudioPortListUpdate();
5152 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005153 ALOGW("%s could not open spatializer output with requested config", __func__);
5154 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005155 }
Eric Laurent39095982021-08-24 18:29:27 +02005156 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005157 mPreviousOutputs = mOutputs;
5158 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005159 }
5160
5161 checkVirtualizerClientRoutes();
5162
Eric Laurent39095982021-08-24 18:29:27 +02005163 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005164 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005165 return NO_ERROR;
5166}
5167
Eric Laurentfa0f6742021-08-17 18:39:44 +02005168status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5169 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005170 return INVALID_OPERATION;
5171 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005172 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005173 return BAD_VALUE;
5174 }
Eric Laurent39095982021-08-24 18:29:27 +02005175
Eric Laurentfa0f6742021-08-17 18:39:44 +02005176 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005177
5178 checkVirtualizerClientRoutes();
5179
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005180 return NO_ERROR;
5181}
5182
Eric Laurente552edb2014-03-10 17:42:56 -07005183// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005184// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005185// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005186uint32_t AudioPolicyManager::nextAudioPortGeneration()
5187{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005188 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005189}
5190
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005191static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005192 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5193 !audioPolicyXmlConfigFile.empty()) {
5194 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5195 if (ret == NO_ERROR) {
5196 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005197 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005198 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005199 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005200 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005201}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005202
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005203AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5204 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005205 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005206 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005207 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005208 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005209 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005210 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005211 mAudioPortGeneration(1),
5212 mBeaconMuteRefCount(0),
5213 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005214 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005215 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005216 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005217 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005218{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005219}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005220
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005221AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5222 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5223{
5224 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005225}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005226
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005227void AudioPolicyManager::loadConfig() {
5228 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005229 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005230 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005231 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005232}
5233
5234status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005235 {
5236 auto engLib = EngineLibrary::load(
5237 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5238 if (!engLib) {
5239 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5240 return NO_INIT;
5241 }
5242 mEngine = engLib->createEngine();
5243 if (mEngine == nullptr) {
5244 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5245 return NO_INIT;
5246 }
François Gaffie2110e042015-03-24 08:41:51 +01005247 }
5248 mEngine->setObserver(this);
5249 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005250 if (status != NO_ERROR) {
5251 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5252 return status;
5253 }
François Gaffie2110e042015-03-24 08:41:51 +01005254
Eric Laurent1d69c872021-01-11 18:53:01 +01005255 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5256 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5257
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005258 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005259 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005260 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005261
Eric Laurent3a4311c2014-03-17 12:00:47 -07005262 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005263 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5264 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5265 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005266 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005267 }
jiabin9ff780e2018-03-19 18:19:52 -07005268 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005269 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005270 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005271 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005272 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005273 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005274 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005275 }
5276 }
5277 }
Eric Laurente552edb2014-03-10 17:42:56 -07005278
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005279 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005280
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005281 // Silence ALOGV statements
5282 property_set("log.tag." LOG_TAG, "D");
5283
Eric Laurente552edb2014-03-10 17:42:56 -07005284 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005285 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005286}
5287
Eric Laurente0720872014-03-11 09:30:41 -07005288AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005289{
Eric Laurente552edb2014-03-10 17:42:56 -07005290 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005291 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005292 }
5293 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005294 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005295 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005296 mAvailableOutputDevices.clear();
5297 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005298 mOutputs.clear();
5299 mInputs.clear();
5300 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005301 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005302 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005303}
5304
Eric Laurente0720872014-03-11 09:30:41 -07005305status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005306{
Eric Laurent87ffa392015-05-22 10:32:38 -07005307 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005308}
5309
Eric Laurente552edb2014-03-10 17:42:56 -07005310// ---
5311
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005312void AudioPolicyManager::onNewAudioModulesAvailable()
5313{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005314 DeviceVector newDevices;
5315 onNewAudioModulesAvailableInt(&newDevices);
5316 if (!newDevices.empty()) {
5317 nextAudioPortGeneration();
5318 mpClientInterface->onAudioPortListUpdate();
5319 }
5320}
5321
5322void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5323{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005324 for (const auto& hwModule : mHwModulesAll) {
5325 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5326 continue;
5327 }
5328 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5329 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5330 ALOGW("could not open HW module %s", hwModule->getName());
5331 continue;
5332 }
5333 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005334 // open all output streams needed to access attached devices.
5335 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005336 // This also validates mAvailableOutputDevices list
5337 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5338 if (!outProfile->canOpenNewIo()) {
5339 ALOGE("Invalid Output profile max open count %u for profile %s",
5340 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5341 continue;
5342 }
5343 if (!outProfile->hasSupportedDevices()) {
5344 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5345 continue;
5346 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005347 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5348 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005349 mTtsOutputAvailable = true;
5350 }
5351
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005352 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5353 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5354 sp<DeviceDescriptor> supportedDevice = 0;
5355 if (supportedDevices.contains(mDefaultOutputDevice)) {
5356 supportedDevice = mDefaultOutputDevice;
5357 } else {
5358 // choose first device present in profile's SupportedDevices also part of
5359 // mAvailableOutputDevices.
5360 if (availProfileDevices.isEmpty()) {
5361 continue;
5362 }
5363 supportedDevice = availProfileDevices.itemAt(0);
5364 }
5365 if (!mOutputDevicesAll.contains(supportedDevice)) {
5366 continue;
5367 }
5368 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5369 mpClientInterface);
5370 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005371 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5372 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005373 AUDIO_STREAM_DEFAULT,
5374 AUDIO_OUTPUT_FLAG_NONE, &output);
5375 if (status != NO_ERROR) {
5376 ALOGW("Cannot open output stream for devices %s on hw module %s",
5377 supportedDevice->toString().c_str(), hwModule->getName());
5378 continue;
5379 }
5380 for (const auto &device : availProfileDevices) {
5381 // give a valid ID to an attached device once confirmed it is reachable
5382 if (!device->isAttached()) {
5383 device->attach(hwModule);
5384 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005385 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005386 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005387 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5388 }
5389 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005390 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005391 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5392 mPrimaryOutput = outputDesc;
5393 }
Eric Laurent39095982021-08-24 18:29:27 +02005394 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005395 outputDesc->close();
5396 } else {
5397 addOutput(output, outputDesc);
5398 setOutputDevices(outputDesc,
5399 DeviceVector(supportedDevice),
5400 true,
5401 0,
5402 NULL);
5403 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005404 }
5405 // open input streams needed to access attached devices to validate
5406 // mAvailableInputDevices list
5407 for (const auto& inProfile : hwModule->getInputProfiles()) {
5408 if (!inProfile->canOpenNewIo()) {
5409 ALOGE("Invalid Input profile max open count %u for profile %s",
5410 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5411 continue;
5412 }
5413 if (!inProfile->hasSupportedDevices()) {
5414 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5415 continue;
5416 }
5417 // chose first device present in profile's SupportedDevices also part of
5418 // available input devices
5419 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5420 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5421 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005422 ALOGV("%s: Input device list is empty! for profile %s",
5423 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005424 continue;
5425 }
5426 sp<AudioInputDescriptor> inputDesc =
5427 new AudioInputDescriptor(inProfile, mpClientInterface);
5428
5429 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5430 status_t status = inputDesc->open(nullptr,
5431 availProfileDevices.itemAt(0),
5432 AUDIO_SOURCE_MIC,
5433 AUDIO_INPUT_FLAG_NONE,
5434 &input);
5435 if (status != NO_ERROR) {
5436 ALOGW("Cannot open input stream for device %s on hw module %s",
5437 availProfileDevices.toString().c_str(),
5438 hwModule->getName());
5439 continue;
5440 }
5441 for (const auto &device : availProfileDevices) {
5442 // give a valid ID to an attached device once confirmed it is reachable
5443 if (!device->isAttached()) {
5444 device->attach(hwModule);
5445 device->importAudioPortAndPickAudioProfile(inProfile, true);
5446 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005447 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005448 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5449 }
5450 }
5451 inputDesc->close();
5452 }
5453 }
5454}
5455
Eric Laurent98e38192018-02-15 18:31:53 -08005456void AudioPolicyManager::addOutput(audio_io_handle_t output,
5457 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005458{
Eric Laurent1c333e22014-05-20 10:48:17 -07005459 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005460 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005461 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005462 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005464}
5465
François Gaffie53615e22015-03-19 09:24:12 +01005466void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5467{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005468 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5469 ALOGV("%s: removing primary output", __func__);
5470 mPrimaryOutput = nullptr;
5471 }
François Gaffie53615e22015-03-19 09:24:12 +01005472 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005473 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005474}
5475
Eric Laurent98e38192018-02-15 18:31:53 -08005476void AudioPolicyManager::addInput(audio_io_handle_t input,
5477 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005478{
Eric Laurent1c333e22014-05-20 10:48:17 -07005479 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005480 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005481}
Eric Laurente552edb2014-03-10 17:42:56 -07005482
François Gaffie11d30102018-11-02 16:09:09 +01005483status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005484 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005485 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005486{
François Gaffie11d30102018-11-02 16:09:09 +01005487 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005488 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005489 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005490
François Gaffie11d30102018-11-02 16:09:09 +01005491 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005492 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005493 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005494 }
Eric Laurente552edb2014-03-10 17:42:56 -07005495
Eric Laurent3b73df72014-03-11 09:06:29 -07005496 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005497 // first call getAudioPort to get the supported attributes from the HAL
5498 struct audio_port_v7 port = {};
5499 device->toAudioPort(&port);
5500 status_t status = mpClientInterface->getAudioPort(&port);
5501 if (status == NO_ERROR) {
5502 device->importAudioPort(port);
5503 }
5504
5505 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005506 for (size_t i = 0; i < mOutputs.size(); i++) {
5507 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005508 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005509 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005510 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5511 mOutputs.keyAt(i), device->toString().c_str());
5512 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005513 }
5514 }
5515 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005516 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005517 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005518 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5519 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005520 if (profile->supportsDevice(device)) {
5521 profiles.add(profile);
5522 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5523 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005524 }
5525 }
5526 }
5527
Eric Laurent7b279bb2015-12-14 10:18:23 -08005528 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005529
Eric Laurente552edb2014-03-10 17:42:56 -07005530 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005531 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005532 return BAD_VALUE;
5533 }
5534
5535 // open outputs for matching profiles if needed. Direct outputs are also opened to
5536 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5537 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005538 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005539
5540 // nothing to do if one output is already opened for this profile
5541 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005542 for (j = 0; j < outputs.size(); j++) {
5543 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005544 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005545 // matching profile: save the sample rates, format and channel masks supported
5546 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005547 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005548 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005549 }
Eric Laurente552edb2014-03-10 17:42:56 -07005550 break;
5551 }
5552 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005553 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005554 continue;
5555 }
5556
Eric Laurent3974e3b2017-12-07 17:58:43 -08005557 if (!profile->canOpenNewIo()) {
5558 ALOGW("Max Output number %u already opened for this profile %s",
5559 profile->maxOpenCount, profile->getTagName().c_str());
5560 continue;
5561 }
5562
Eric Laurent83efe1c2017-07-09 16:51:08 -07005563 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005564 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005565 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5566 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005567 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005568 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005569 profiles.removeAt(profile_index);
5570 profile_index--;
5571 } else {
5572 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005573 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005574 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005575 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5576 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005577 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005578 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005579
François Gaffie11d30102018-11-02 16:09:09 +01005580 if (device_distinguishes_on_address(deviceType)) {
5581 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5582 device->toString().c_str());
5583 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5584 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005585 }
Eric Laurente552edb2014-03-10 17:42:56 -07005586 ALOGV("checkOutputsForDevice(): adding output %d", output);
5587 }
5588 }
5589
5590 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005591 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005592 return BAD_VALUE;
5593 }
Eric Laurentd4692962014-05-05 18:13:44 -07005594 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005595 // check if one opened output is not needed any more after disconnecting one device
5596 for (size_t i = 0; i < mOutputs.size(); i++) {
5597 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005598 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005599 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005600 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005601 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005602 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005603 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005604 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5605 mOutputs.keyAt(i));
5606 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005607 }
Eric Laurente552edb2014-03-10 17:42:56 -07005608 }
5609 }
Eric Laurentd4692962014-05-05 18:13:44 -07005610 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005611 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005612 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5613 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005614 if (!profile->supportsDevice(device)) {
5615 continue;
5616 }
5617 ALOGV("checkOutputsForDevice(): "
5618 "clearing direct output profile %zu on module %s",
5619 j, hwModule->getName());
5620 profile->clearAudioProfiles();
5621 if (!profile->hasDynamicAudioProfile()) {
5622 continue;
5623 }
5624 // When a device is disconnected, if there is an IOProfile that contains dynamic
5625 // profiles and supports the disconnected device, call getAudioPort to repopulate
5626 // the capabilities of the devices that is supported by the IOProfile.
5627 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5628 if (supportedDevice == device ||
5629 !mAvailableOutputDevices.contains(supportedDevice)) {
5630 continue;
5631 }
5632 struct audio_port_v7 port;
5633 supportedDevice->toAudioPort(&port);
5634 status_t status = mpClientInterface->getAudioPort(&port);
5635 if (status == NO_ERROR) {
5636 supportedDevice->importAudioPort(port);
5637 }
Eric Laurente552edb2014-03-10 17:42:56 -07005638 }
5639 }
5640 }
5641 }
5642 return NO_ERROR;
5643}
5644
François Gaffie11d30102018-11-02 16:09:09 +01005645status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005646 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005647{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005648 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005649
François Gaffie11d30102018-11-02 16:09:09 +01005650 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005651 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005652 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005653 }
5654
Eric Laurentd4692962014-05-05 18:13:44 -07005655 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005656 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005657 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005658 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005659 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005660 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005661 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005662 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005663
François Gaffie11d30102018-11-02 16:09:09 +01005664 if (profile->supportsDevice(device)) {
5665 profiles.add(profile);
5666 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5667 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005668 }
5669 }
5670 }
5671
Eric Laurent0dd51852019-04-19 18:18:58 -07005672 if (profiles.isEmpty()) {
5673 ALOGW("%s: No input profile available for device %s",
5674 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005675 return BAD_VALUE;
5676 }
5677
5678 // open inputs for matching profiles if needed. Direct inputs are also opened to
5679 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5680 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5681
Eric Laurent1c333e22014-05-20 10:48:17 -07005682 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005683
Eric Laurentd4692962014-05-05 18:13:44 -07005684 // nothing to do if one input is already opened for this profile
5685 size_t input_index;
5686 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5687 desc = mInputs.valueAt(input_index);
5688 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005689 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005690 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005691 }
Eric Laurentd4692962014-05-05 18:13:44 -07005692 break;
5693 }
5694 }
5695 if (input_index != mInputs.size()) {
5696 continue;
5697 }
5698
Eric Laurent3974e3b2017-12-07 17:58:43 -08005699 if (!profile->canOpenNewIo()) {
5700 ALOGW("Max Input number %u already opened for this profile %s",
5701 profile->maxOpenCount, profile->getTagName().c_str());
5702 continue;
5703 }
5704
Eric Laurentfe231122017-11-17 17:48:06 -08005705 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005706 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005707 status_t status = desc->open(nullptr,
5708 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005709 AUDIO_SOURCE_MIC,
5710 AUDIO_INPUT_FLAG_NONE,
5711 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005712
Eric Laurentcf2c0212014-07-25 16:20:43 -07005713 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005714 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005715 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005716 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005717 mpClientInterface->setParameters(input, String8(param));
5718 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005719 }
François Gaffie11d30102018-11-02 16:09:09 +01005720 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005721 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005722 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005723 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005724 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005725 }
5726
Eric Laurent0dd51852019-04-19 18:18:58 -07005727 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005728 addInput(input, desc);
5729 }
5730 } // endif input != 0
5731
Eric Laurentcf2c0212014-07-25 16:20:43 -07005732 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005733 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005734 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005735 profiles.removeAt(profile_index);
5736 profile_index--;
5737 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005738 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005739 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005740 }
Eric Laurentd4692962014-05-05 18:13:44 -07005741 ALOGV("checkInputsForDevice(): adding input %d", input);
5742 }
5743 } // end scan profiles
5744
5745 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005746 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005747 return BAD_VALUE;
5748 }
5749 } else {
5750 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005751 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005752 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005753 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005754 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005755 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005756 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005757 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005758 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5759 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005760 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005761 }
5762 }
5763 }
5764 } // end disconnect
5765
5766 return NO_ERROR;
5767}
5768
5769
Eric Laurente0720872014-03-11 09:30:41 -07005770void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005771{
5772 ALOGV("closeOutput(%d)", output);
5773
François Gaffie1c878552018-11-22 16:53:21 +01005774 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5775 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005776 ALOGW("closeOutput() unknown output %d", output);
5777 return;
5778 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005779 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005780 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005781
Eric Laurente552edb2014-03-10 17:42:56 -07005782 // look for duplicated outputs connected to the output being removed.
5783 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005784 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5785 if (dupOutput->isDuplicated() &&
5786 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5787 sp<SwAudioOutputDescriptor> remainingOutput =
5788 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005789 // As all active tracks on duplicated output will be deleted,
5790 // and as they were also referenced on the other output, the reference
5791 // count for their stream type must be adjusted accordingly on
5792 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005793 const bool wasActive = remainingOutput->isActive();
5794 // Note: no-op on the closing output where all clients has already been set inactive
5795 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005796 // stop() will be a no op if the output is still active but is needed in case all
5797 // active streams refcounts where cleared above
5798 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005799 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005800 }
Eric Laurente552edb2014-03-10 17:42:56 -07005801 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5802 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5803
5804 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005805 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005806 }
5807 }
5808
Eric Laurent05b90f82014-08-27 15:32:29 -07005809 nextAudioPortGeneration();
5810
François Gaffie1c878552018-11-22 16:53:21 +01005811 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005812 if (index >= 0) {
5813 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005814 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5815 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005816 mAudioPatches.removeItemsAt(index);
5817 mpClientInterface->onAudioPatchListUpdate();
5818 }
5819
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005820 if (closingOutputWasActive) {
5821 closingOutput->stop();
5822 }
François Gaffie1c878552018-11-22 16:53:21 +01005823 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005824
François Gaffie53615e22015-03-19 09:24:12 +01005825 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005826 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005827 if (closingOutput == mSpatializerOutput) {
5828 mSpatializerOutput.clear();
5829 }
Dean Wheatley3023b382018-08-09 07:42:40 +10005830
5831 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5832 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005833 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005834 bool directOutputOpen = false;
5835 for (size_t i = 0; i < mOutputs.size(); i++) {
5836 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5837 directOutputOpen = true;
5838 break;
5839 }
5840 }
5841 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005842 ALOGV("no direct outputs open, reset MSD patches");
5843 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5844 // how output devices for patching are resolved. Avoid by caching and reusing the
5845 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5846 // devices to patch to. This may be complicated by the fact that devices may become
5847 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005848 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005849 }
5850 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005851}
5852
5853void AudioPolicyManager::closeInput(audio_io_handle_t input)
5854{
5855 ALOGV("closeInput(%d)", input);
5856
5857 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5858 if (inputDesc == NULL) {
5859 ALOGW("closeInput() unknown input %d", input);
5860 return;
5861 }
5862
Eric Laurent6a94d692014-05-20 11:18:06 -07005863 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005864
François Gaffie11d30102018-11-02 16:09:09 +01005865 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005866 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005867 if (index >= 0) {
5868 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005869 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5870 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005871 mAudioPatches.removeItemsAt(index);
5872 mpClientInterface->onAudioPatchListUpdate();
5873 }
5874
Eric Laurentfe231122017-11-17 17:48:06 -08005875 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005876 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005877
François Gaffie11d30102018-11-02 16:09:09 +01005878 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5879 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005880 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005881 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005882 }
Eric Laurente552edb2014-03-10 17:42:56 -07005883}
5884
François Gaffie11d30102018-11-02 16:09:09 +01005885SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5886 const DeviceVector &devices,
5887 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005888{
5889 SortedVector<audio_io_handle_t> outputs;
5890
François Gaffie11d30102018-11-02 16:09:09 +01005891 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005892 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005893 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005894 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005895 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005896 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005897 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005898 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005899 outputs.add(openOutputs.keyAt(i));
5900 }
5901 }
5902 return outputs;
5903}
5904
Mikhail Naganov37977152018-07-11 15:54:44 -07005905void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5906{
5907 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5908 // output is suspended before any tracks are moved to it
5909 checkA2dpSuspend();
5910 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005911 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005912 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005913 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005914 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005915 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5916 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5917 // configuration changes will ultimately be rerouted correctly. We can still avoid
5918 // unnecessary rerouting by caching and reusing the arguments to
5919 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5920 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005921 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005922 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005923 // an event that changed routing likely occurred, inform upper layers
5924 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005925}
5926
François Gaffiec005e562018-11-06 15:04:49 +01005927bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5928 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005929{
François Gaffiec005e562018-11-06 15:04:49 +01005930 return mEngine->getProductStrategyForAttributes(lAttr) ==
5931 mEngine->getProductStrategyForAttributes(rAttr);
5932}
5933
Francois Gaffieff1eb522020-05-06 18:37:04 +02005934void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5935{
5936 for (size_t i = 0; i < mAudioSources.size(); i++) {
5937 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5938 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005939 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5940 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005941 connectAudioSource(sourceDesc);
5942 }
5943 }
5944}
5945
5946void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5947{
5948 for (size_t i = 0; i < mAudioSources.size(); i++) {
5949 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5950 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5951 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5952 disconnectAudioSource(sourceDesc);
5953 }
5954 }
5955}
5956
François Gaffiec005e562018-11-06 15:04:49 +01005957void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5958{
5959 auto psId = mEngine->getProductStrategyForAttributes(attr);
5960
5961 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5962 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005963
François Gaffie11d30102018-11-02 16:09:09 +01005964 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5965 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005966
Eric Laurentc209fe42020-06-05 18:11:23 -07005967 uint32_t maxLatency = 0;
5968 bool invalidate = false;
5969 // take into account dynamic audio policies related changes: if a client is now associated
5970 // to a different policy mix than at creation time, invalidate corresponding stream
5971 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5972 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5973 if (desc->isDuplicated()) {
5974 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005975 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005976 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5977 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5978 continue;
5979 }
5980 sp<AudioPolicyMix> primaryMix;
5981 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5982 client->flags(), primaryMix, nullptr);
5983 if (status != OK) {
5984 continue;
5985 }
yucliuf4de36d2020-09-14 14:57:56 -07005986 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005987 invalidate = true;
5988 if (desc->isStrategyActive(psId)) {
5989 maxLatency = desc->latency();
5990 }
5991 break;
5992 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005993 }
5994 }
5995
Eric Laurentc209fe42020-06-05 18:11:23 -07005996 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005997 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5998 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005999 for (audio_io_handle_t srcOut : srcOutputs) {
6000 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006001 if (desc == nullptr) continue;
6002
6003 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006004 maxLatency = desc->latency();
6005 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006006
6007 if (invalidate) continue;
6008
6009 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006010 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006011 // a client on a non direct outputs has necessarily a linear PCM format
6012 // so we can call selectOutput() safely
6013 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6014 client->flags(),
6015 client->config().format,
6016 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006017 client->config().sample_rate,
6018 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006019 if (newOutput != srcOut) {
6020 invalidate = true;
6021 break;
6022 }
6023 } else {
6024 sp<IOProfile> profile = getProfileForOutput(newDevices,
6025 client->config().sample_rate,
6026 client->config().format,
6027 client->config().channel_mask,
6028 client->flags(),
6029 true /* directOnly */);
6030 if (profile != desc->mProfile) {
6031 invalidate = true;
6032 break;
6033 }
6034 }
6035 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006036 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006037
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006038 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006039 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006040 std::to_string(srcOutputs[0]).c_str(),
6041 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006042 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006043 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006044 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006045 if (desc == nullptr) continue;
6046
6047 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006048 setStrategyMute(psId, true, desc);
6049 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006050 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006051 }
François Gaffiec005e562018-11-06 15:04:49 +01006052 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006053 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006054 connectAudioSource(source);
6055 }
Eric Laurente552edb2014-03-10 17:42:56 -07006056 }
6057
François Gaffiec005e562018-11-06 15:04:49 +01006058 // Move effects associated to this stream from previous output to new output
6059 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006060 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006061 }
François Gaffiec005e562018-11-06 15:04:49 +01006062 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006063 if (invalidate) {
6064 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6065 mpClientInterface->invalidateStream(stream);
6066 }
Eric Laurente552edb2014-03-10 17:42:56 -07006067 }
6068 }
6069}
6070
Eric Laurente0720872014-03-11 09:30:41 -07006071void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006072{
François Gaffiec005e562018-11-06 15:04:49 +01006073 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6074 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6075 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006076 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006077 }
Eric Laurente552edb2014-03-10 17:42:56 -07006078}
6079
Kevin Rocard153f92d2018-12-18 18:33:28 -08006080void AudioPolicyManager::checkSecondaryOutputs() {
6081 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006082 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006083 for (size_t i = 0; i < mOutputs.size(); i++) {
6084 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6085 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006086 sp<AudioPolicyMix> primaryMix;
6087 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006088 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006089 client->flags(), primaryMix, &secondaryMixes);
6090 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6091 for (auto &secondaryMix : secondaryMixes) {
6092 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6093 if (outputDesc != nullptr &&
6094 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6095 secondaryDescs.push_back(outputDesc);
6096 }
6097 }
6098
jiabin10a03f12021-05-07 23:46:28 +00006099 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006100 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006101 } else if (!std::equal(
6102 client->getSecondaryOutputs().begin(),
6103 client->getSecondaryOutputs().end(),
6104 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006105 if (!audio_is_linear_pcm(client->config().format)) {
6106 // If the format is not PCM, the tracks should be invalidated to get correct
6107 // behavior when the secondary output is changed.
6108 streamsToInvalidate.insert(client->stream());
6109 } else {
6110 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6111 std::vector<audio_io_handle_t> secondaryOutputIds;
6112 for (const auto &secondaryDesc: secondaryDescs) {
6113 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6114 weakSecondaryDescs.push_back(secondaryDesc);
6115 }
6116 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6117 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006118 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006119 }
6120 }
6121 }
jiabin10a03f12021-05-07 23:46:28 +00006122 if (!trackSecondaryOutputs.empty()) {
6123 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6124 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006125 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006126 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006127 mpClientInterface->invalidateStream(stream);
6128 }
6129}
6130
Eric Laurent2517af32020-11-25 15:31:27 +01006131bool AudioPolicyManager::isScoRequestedForComm() const {
6132 AudioDeviceTypeAddrVector devices;
6133 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6134 for (const auto &device : devices) {
6135 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6136 return true;
6137 }
6138 }
6139 return false;
6140}
6141
Eric Laurente0720872014-03-11 09:30:41 -07006142void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006143{
François Gaffie53615e22015-03-19 09:24:12 +01006144 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006145 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006146 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006147 return;
6148 }
6149
Eric Laurent3a4311c2014-03-17 12:00:47 -07006150 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006151 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6152 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006153 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006154
6155 // if suspended, restore A2DP output if:
6156 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006157 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006158 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006159 //
Eric Laurentf732e072016-08-03 19:30:28 -07006160 // if not suspended, suspend A2DP output if:
6161 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006162 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006163 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006164 //
6165 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006166 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006167 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006168 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006169 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006170
6171 mpClientInterface->restoreOutput(a2dpOutput);
6172 mA2dpSuspended = false;
6173 }
6174 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006175 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006176 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006177 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006178 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006179
6180 mpClientInterface->suspendOutput(a2dpOutput);
6181 mA2dpSuspended = true;
6182 }
6183 }
6184}
6185
François Gaffie11d30102018-11-02 16:09:09 +01006186DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6187 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006188{
François Gaffie11d30102018-11-02 16:09:09 +01006189 DeviceVector devices;
6190
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006191 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006192 if (index >= 0) {
6193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006194 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006195 ALOGV("%s device %s forced by patch %d", __func__,
6196 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6197 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006198 }
6199 }
6200
Dean Wheatley514b4312020-06-17 21:45:00 +10006201 // Do not retrieve engine device for outputs through MSD
6202 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6203 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6204 return outputDesc->devices();
6205 }
6206
Eric Laurent97ac8712018-07-27 18:59:02 -07006207 // Honor explicit routing requests only if no client using default routing is active on this
6208 // input: a specific app can not force routing for other apps by setting a preferred device.
6209 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006210 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006211 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006212 if (device != nullptr) {
6213 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006214 }
6215
François Gaffiea807ef92018-11-05 10:44:33 +01006216 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6217 // of setForceUse / Default Bus device here
6218 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6219 if (device != nullptr) {
6220 return DeviceVector(device);
6221 }
6222
François Gaffiec005e562018-11-06 15:04:49 +01006223 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6224 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6225 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306226 auto hasStreamActive = [&](auto stream) {
6227 return hasStream(streams, stream) && isStreamActive(stream, 0);
6228 };
Eric Laurent484e9272018-06-07 17:29:23 -07006229
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306230 auto doGetOutputDevicesForVoice = [&]() {
6231 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6232 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6233 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006234 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6235 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306236 };
6237
6238 // With low-latency playing on speaker, music on WFD, when the first low-latency
6239 // output is stopped, getNewOutputDevices checks for a product strategy
6240 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006241 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306242 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6243 // stream is associated to the output descriptor.
6244 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6245 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6246 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6247 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006248 // Retrieval of devices for voice DL is done on primary output profile, cannot
6249 // check the route (would force modifying configuration file for this profile)
6250 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6251 break;
6252 }
Eric Laurente552edb2014-03-10 17:42:56 -07006253 }
François Gaffiec005e562018-11-06 15:04:49 +01006254 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006255 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006256}
6257
François Gaffie11d30102018-11-02 16:09:09 +01006258sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6259 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006260{
François Gaffie11d30102018-11-02 16:09:09 +01006261 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006262
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006263 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006264 if (index >= 0) {
6265 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006266 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006267 ALOGV("getNewInputDevice() device %s forced by patch %d",
6268 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6269 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006270 }
6271 }
6272
Eric Laurent97ac8712018-07-27 18:59:02 -07006273 // Honor explicit routing requests only if no client using default routing is active on this
6274 // input: a specific app can not force routing for other apps by setting a preferred device.
6275 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006276 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6277 if (device != nullptr) {
6278 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006279 }
6280
Eric Laurentdc95a252018-04-12 12:46:56 -07006281 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006282 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006283 audio_attributes_t attributes;
6284 uid_t uid;
6285 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6286 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006287 attributes = topClient->attributes();
6288 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006289 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006290 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6291 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006292 }
6293
Francois Gaffie716e1432019-01-14 16:58:59 +01006294 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6295 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006296 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006297 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006298 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006299 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006300
Eric Laurente552edb2014-03-10 17:42:56 -07006301 return device;
6302}
6303
Eric Laurent794fde22016-03-11 09:50:45 -08006304bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6305 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006306 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006307}
6308
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006309DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006310 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006311 // getOutputDevicesForStream's behavior for invalid streams.
6312 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6313 // device for music stream), but we want to return the empty set.
6314 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006315 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006316 }
François Gaffie11d30102018-11-02 16:09:09 +01006317 DeviceVector activeDevices;
6318 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006319 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6320 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006321 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006322 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006323 }
François Gaffiec005e562018-11-06 15:04:49 +01006324 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006325 devices.merge(curDevices);
6326 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006327 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006328 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006329 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006330 }
6331 }
Eric Laurente552edb2014-03-10 17:42:56 -07006332 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006333
Eric Laurentb0688d62018-08-14 15:49:18 -07006334 // Favor devices selected on active streams if any to report correct device in case of
6335 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006336 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006337 devices = activeDevices;
6338 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006339 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6340 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006341 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006342 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006343 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006344 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006345 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006346 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006347}
6348
Dorin Drimusf2196d82022-01-03 12:11:18 +01006349// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006350status_t AudioPolicyManager::getDevicesForAttributes(
6351 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6352 if (devices == nullptr) {
6353 return BAD_VALUE;
6354 }
6355 // check dynamic policies but only for primary descriptors (secondary not used for audible
6356 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006357 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006358 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006359 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006360 if (status != OK) {
6361 return status;
6362 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006363 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6364 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6365 devices->push_back(device);
6366 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006367 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006368 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6369 for (const auto& device : curDevices) {
6370 devices->push_back(device->getDeviceTypeAddr());
6371 }
6372 return NO_ERROR;
6373}
6374
Eric Laurente0720872014-03-11 09:30:41 -07006375void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006376 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006377 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006378 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006379 updateDevicesAndOutputs();
6380 break;
6381 default:
6382 break;
6383 }
6384}
6385
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006386uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006387
6388 // skip beacon mute management if a dedicated TTS output is available
6389 if (mTtsOutputAvailable) {
6390 return 0;
6391 }
6392
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006393 switch(event) {
6394 case STARTING_OUTPUT:
6395 mBeaconMuteRefCount++;
6396 break;
6397 case STOPPING_OUTPUT:
6398 if (mBeaconMuteRefCount > 0) {
6399 mBeaconMuteRefCount--;
6400 }
6401 break;
6402 case STARTING_BEACON:
6403 mBeaconPlayingRefCount++;
6404 break;
6405 case STOPPING_BEACON:
6406 if (mBeaconPlayingRefCount > 0) {
6407 mBeaconPlayingRefCount--;
6408 }
6409 break;
6410 }
6411
6412 if (mBeaconMuteRefCount > 0) {
6413 // any playback causes beacon to be muted
6414 return setBeaconMute(true);
6415 } else {
6416 // no other playback: unmute when beacon starts playing, mute when it stops
6417 return setBeaconMute(mBeaconPlayingRefCount == 0);
6418 }
6419}
6420
6421uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6422 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6423 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6424 // keep track of muted state to avoid repeating mute/unmute operations
6425 if (mBeaconMuted != mute) {
6426 // mute/unmute AUDIO_STREAM_TTS on all outputs
6427 ALOGV("\t muting %d", mute);
6428 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006429 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006430 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006431 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006432 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006433 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006434 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006435 maxLatency = latency;
6436 }
6437 }
6438 mBeaconMuted = mute;
6439 return maxLatency;
6440 }
6441 return 0;
6442}
6443
Eric Laurente0720872014-03-11 09:30:41 -07006444void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006445{
François Gaffiec005e562018-11-06 15:04:49 +01006446 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006447 mPreviousOutputs = mOutputs;
6448}
6449
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006450uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006451 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006452 uint32_t delayMs)
6453{
6454 // mute/unmute strategies using an incompatible device combination
6455 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6456 // if unmuting, unmute only after the specified delay
6457 if (outputDesc->isDuplicated()) {
6458 return 0;
6459 }
6460
6461 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006462 DeviceVector devices = outputDesc->devices();
6463 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006464
François Gaffiec005e562018-11-06 15:04:49 +01006465 auto productStrategies = mEngine->getOrderedProductStrategies();
6466 for (const auto &productStrategy : productStrategies) {
6467 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6468 DeviceVector curDevices =
6469 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6470 curDevices = curDevices.filter(outputDesc->supportedDevices());
6471 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006472 bool doMute = false;
6473
François Gaffiec005e562018-11-06 15:04:49 +01006474 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006475 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006476 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6477 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006478 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006479 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006480 }
Eric Laurent99401132014-05-07 19:48:15 -07006481 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006482 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006483 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006484 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006485 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006486 continue;
6487 }
François Gaffiec005e562018-11-06 15:04:49 +01006488 ALOGVV("%s() %s (curDevice %s)", __func__,
6489 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6490 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6491 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006492 if (mute) {
6493 // FIXME: should not need to double latency if volume could be applied
6494 // immediately by the audioflinger mixer. We must account for the delay
6495 // between now and the next time the audioflinger thread for this output
6496 // will process a buffer (which corresponds to one buffer size,
6497 // usually 1/2 or 1/4 of the latency).
6498 if (muteWaitMs < desc->latency() * 2) {
6499 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006500 }
6501 }
6502 }
6503 }
6504 }
6505 }
6506
Eric Laurent99401132014-05-07 19:48:15 -07006507 // temporary mute output if device selection changes to avoid volume bursts due to
6508 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006509 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006510 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006511
Eric Laurentdc462862016-07-19 12:29:53 -07006512 if (muteWaitMs < tempMuteWaitMs) {
6513 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006514 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006515
6516 // If recommended duration is defined, replace temporary mute duration to avoid
6517 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6518 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6519 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6520 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6521 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6522
François Gaffieaaac0fd2018-11-22 17:56:39 +01006523 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6524 // make sure that we do not start the temporary mute period too early in case of
6525 // delayed device change
6526 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6527 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006528 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006529 }
6530 }
6531
Eric Laurente552edb2014-03-10 17:42:56 -07006532 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6533 if (muteWaitMs > delayMs) {
6534 muteWaitMs -= delayMs;
6535 usleep(muteWaitMs * 1000);
6536 return muteWaitMs;
6537 }
6538 return 0;
6539}
6540
François Gaffie11d30102018-11-02 16:09:09 +01006541uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6542 const DeviceVector &devices,
6543 bool force,
6544 int delayMs,
6545 audio_patch_handle_t *patchHandle,
6546 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006547{
François Gaffie11d30102018-11-02 16:09:09 +01006548 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006549 uint32_t muteWaitMs;
6550
6551 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006552 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6553 nullptr /* patchHandle */, requiresMuteCheck);
6554 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6555 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006556 return muteWaitMs;
6557 }
Eric Laurente552edb2014-03-10 17:42:56 -07006558
6559 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006560 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006561 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006562
François Gaffie11d30102018-11-02 16:09:09 +01006563 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6564
6565 if (!filteredDevices.isEmpty()) {
6566 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006567 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006568
6569 // if the outputs are not materially active, there is no need to mute.
6570 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006571 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006572 } else {
6573 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6574 muteWaitMs = 0;
6575 }
Eric Laurente552edb2014-03-10 17:42:56 -07006576
Eric Laurent79ea9582020-06-11 18:49:24 -07006577 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6578 // output profile or if new device is not supported AND previous device(s) is(are) still
6579 // available (otherwise reset device must be done on the output)
6580 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6581 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6582 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6583 // restore previous device after evaluating strategy mute state
6584 outputDesc->setDevices(prevDevices);
6585 return muteWaitMs;
6586 }
6587
Eric Laurente552edb2014-03-10 17:42:56 -07006588 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006589 // the requested device is AUDIO_DEVICE_NONE
6590 // OR the requested device is the same as current device
6591 // AND force is not specified
6592 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006593 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006594 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006595 !force && outputDesc->getPatchHandle() != 0) {
6596 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6597 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006598 return muteWaitMs;
6599 }
6600
François Gaffie11d30102018-11-02 16:09:09 +01006601 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006602
Eric Laurente552edb2014-03-10 17:42:56 -07006603 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006604 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006605 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006606 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006607 PatchBuilder patchBuilder;
6608 patchBuilder.addSource(outputDesc);
6609 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6610 for (const auto &filteredDevice : filteredDevices) {
6611 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006612 }
6613
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006614 // Add half reported latency to delayMs when muteWaitMs is null in order
6615 // to avoid disordered sequence of muting volume and changing devices.
6616 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6617 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006618 }
Eric Laurente552edb2014-03-10 17:42:56 -07006619
6620 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006621 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006622
6623 return muteWaitMs;
6624}
6625
Eric Laurentc75307b2015-03-17 15:29:32 -07006626status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006627 int delayMs,
6628 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006629{
Eric Laurent6a94d692014-05-20 11:18:06 -07006630 ssize_t index;
6631 if (patchHandle) {
6632 index = mAudioPatches.indexOfKey(*patchHandle);
6633 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006634 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006635 }
6636 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006637 return INVALID_OPERATION;
6638 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006639 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006640 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006641 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006642 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006643 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006644 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006645 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006646 return status;
6647}
6648
6649status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006650 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006651 bool force,
6652 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006653{
6654 status_t status = NO_ERROR;
6655
Eric Laurent1f2f2232014-06-02 12:01:23 -07006656 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006657 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6658 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006659
François Gaffie11d30102018-11-02 16:09:09 +01006660 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006661 PatchBuilder patchBuilder;
6662 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006663 // AUDIO_SOURCE_HOTWORD is for internal use only:
6664 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006665 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6666 auto result = usecase;
6667 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6668 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6669 }
6670 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006671 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006672 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006673 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006674 }
6675 }
6676 return status;
6677}
6678
Eric Laurent6a94d692014-05-20 11:18:06 -07006679status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6680 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006681{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006682 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006683 ssize_t index;
6684 if (patchHandle) {
6685 index = mAudioPatches.indexOfKey(*patchHandle);
6686 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006687 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006688 }
6689 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006690 return INVALID_OPERATION;
6691 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006692 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006693 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006694 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006695 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006696 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006697 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006698 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006699 return status;
6700}
6701
François Gaffie11d30102018-11-02 16:09:09 +01006702sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006703 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006704 audio_format_t& format,
6705 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006706 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006707{
6708 // Choose an input profile based on the requested capture parameters: select the first available
6709 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006710 //
6711 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6712 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006713
Glenn Kasten730b9262018-03-29 15:01:26 -07006714 sp<IOProfile> firstInexact;
6715 uint32_t updatedSamplingRate = 0;
6716 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6717 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006718 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006719 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006720 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006721 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006722 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006723 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006724 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006725 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006726 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006727 &channelMask /*updatedChannelMask*/,
6728 // FIXME ugly cast
6729 (audio_output_flags_t) flags,
6730 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006731 return profile;
6732 }
François Gaffie11d30102018-11-02 16:09:09 +01006733 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006734 samplingRate,
6735 &updatedSamplingRate,
6736 format,
6737 &updatedFormat,
6738 channelMask,
6739 &updatedChannelMask,
6740 // FIXME ugly cast
6741 (audio_output_flags_t) flags,
6742 false /*exactMatchRequiredForInputFlags*/)) {
6743 firstInexact = profile;
6744 }
6745
Eric Laurente552edb2014-03-10 17:42:56 -07006746 }
6747 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006748 if (firstInexact != nullptr) {
6749 samplingRate = updatedSamplingRate;
6750 format = updatedFormat;
6751 channelMask = updatedChannelMask;
6752 return firstInexact;
6753 }
Eric Laurente552edb2014-03-10 17:42:56 -07006754 return NULL;
6755}
6756
François Gaffieaaac0fd2018-11-22 17:56:39 +01006757float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6758 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006759 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006760 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006761{
jiabin9a3361e2019-10-01 09:38:30 -07006762 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006763
6764 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6765 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6766 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6767 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006768 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6769 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6770 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6771 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006772 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006773
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006774 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006775 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6776 mOutputs.isActive(ringVolumeSrc, 0)) {
6777 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006778 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006779 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006780 }
6781
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006782 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006783 if ((volumeSource != callVolumeSrc && (isInCall() ||
6784 mOutputs.isActiveLocally(callVolumeSrc))) &&
6785 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6786 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6787 volumeSource == alarmVolumeSrc ||
6788 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6789 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6790 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006791 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006792 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006793 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006794 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006795 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006796 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006797 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6798 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6799 // programmatically muted.
6800 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6801 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6802 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006803 bool exemptFromCapping =
6804 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6805 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006806 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6807 volumeSource, volumeDb);
6808 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006809 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6810 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6811 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006812 }
6813 }
Eric Laurente552edb2014-03-10 17:42:56 -07006814 // if a headset is connected, apply the following rules to ring tones and notifications
6815 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006816 // - always attenuate notifications volume by 6dB
6817 // - attenuate ring tones volume by 6dB unless music is not playing and
6818 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006819 // - if music is playing, always limit the volume to current music volume,
6820 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006821 if (!Intersection(deviceTypes,
6822 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6823 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006824 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6825 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006826 ((volumeSource == alarmVolumeSrc ||
6827 volumeSource == ringVolumeSrc) ||
6828 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6829 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6830 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6831 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6832 curves.canBeMuted()) {
6833
Eric Laurente552edb2014-03-10 17:42:56 -07006834 // when the phone is ringing we must consider that music could have been paused just before
6835 // by the music application and behave as if music was active if the last music track was
6836 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006837 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006838 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006839 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006840 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006841 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6842 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006843 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006844 float musicVolDb = computeVolume(musicCurves,
6845 musicVolumeSrc,
6846 musicCurves.getVolumeIndex(musicDevice),
6847 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006848 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6849 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6850 if (volumeDb > minVolDb) {
6851 volumeDb = minVolDb;
6852 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006853 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006854 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6855 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6856 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006857 // on A2DP, also ensure notification volume is not too low compared to media when
6858 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006859 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006860 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006861 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6862 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006863 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6864 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006865 }
6866 }
jiabin9a3361e2019-10-01 09:38:30 -07006867 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006868 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006869 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006870 }
6871 }
6872
François Gaffie43c73442018-11-08 08:21:55 +01006873 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006874}
6875
Eric Laurent3839bc02018-07-10 18:33:34 -07006876int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006877 VolumeSource fromVolumeSource,
6878 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006879{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006880 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006881 return srcIndex;
6882 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006883 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6884 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006885 float minSrc = (float)srcCurves.getVolumeIndexMin();
6886 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6887 float minDst = (float)dstCurves.getVolumeIndexMin();
6888 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006889
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006890 // preserve mute request or correct range
6891 if (srcIndex < minSrc) {
6892 if (srcIndex == 0) {
6893 return 0;
6894 }
6895 srcIndex = minSrc;
6896 } else if (srcIndex > maxSrc) {
6897 srcIndex = maxSrc;
6898 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006899 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6900}
6901
François Gaffieaaac0fd2018-11-22 17:56:39 +01006902status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6903 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006904 int index,
6905 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006906 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006907 int delayMs,
6908 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006909{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006910 // do not change actual attributes volume if the attributes is muted
6911 if (outputDesc->isMuted(volumeSource)) {
6912 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6913 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006914 return NO_ERROR;
6915 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006916 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6917 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6918 bool isVoiceVolSrc = callVolSrc == volumeSource;
6919 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6920
Eric Laurent2517af32020-11-25 15:31:27 +01006921 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006922 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006923 // if sco and call follow same curves, bypass forceUseForComm
6924 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006925 ((isVoiceVolSrc && isScoRequested) ||
6926 (isBtScoVolSrc && !isScoRequested))) {
6927 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6928 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006929 // Do not return an error here as AudioService will always set both voice call
6930 // and bluetooth SCO volumes due to stream aliasing.
6931 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006932 }
jiabin9a3361e2019-10-01 09:38:30 -07006933 if (deviceTypes.empty()) {
6934 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006935 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006936
jiabin9a3361e2019-10-01 09:38:30 -07006937 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6938 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006939 // Force VoIP volume to max for bluetooth SCO device except if muted
6940 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006941 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006942 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006943 }
jiabin9a3361e2019-10-01 09:38:30 -07006944 outputDesc->setVolume(
6945 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006946
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006947 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006948 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006949 // 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 +01006950 if (isVoiceVolSrc) {
6951 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006952 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006953 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006954 }
Eric Laurent18fba842016-03-31 14:41:26 -07006955 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006956 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6957 mLastVoiceVolume = voiceVolume;
6958 }
6959 }
Eric Laurente552edb2014-03-10 17:42:56 -07006960 return NO_ERROR;
6961}
6962
Eric Laurentc75307b2015-03-17 15:29:32 -07006963void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006964 const DeviceTypeSet& deviceTypes,
6965 int delayMs,
6966 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006967{
jiabincd510522020-01-22 09:40:55 -08006968 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006969 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6970 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6971 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006972 curves.getVolumeIndex(deviceTypes),
6973 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006974 }
6975}
6976
François Gaffiec005e562018-11-06 15:04:49 +01006977void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6978 bool on,
6979 const sp<AudioOutputDescriptor>& outputDesc,
6980 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006981 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006982{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006983 std::vector<VolumeSource> sourcesToMute;
6984 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6985 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6986 toString(attributes).c_str(), on, outputDesc->getId());
6987 VolumeSource source = toVolumeSource(attributes);
6988 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6989 sourcesToMute.push_back(source);
6990 }
Eric Laurente552edb2014-03-10 17:42:56 -07006991 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006992 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006993 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006994 }
6995
Eric Laurente552edb2014-03-10 17:42:56 -07006996}
6997
François Gaffieaaac0fd2018-11-22 17:56:39 +01006998void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6999 bool on,
7000 const sp<AudioOutputDescriptor>& outputDesc,
7001 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007002 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007003{
jiabin9a3361e2019-10-01 09:38:30 -07007004 if (deviceTypes.empty()) {
7005 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007006 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007007 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007008 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007009 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007010 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007011 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
7012 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7013 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007014 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007015 }
7016 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007017 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7018 // ignored
7019 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007020 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007021 if (!outputDesc->isMuted(volumeSource)) {
7022 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007023 return;
7024 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007025 if (outputDesc->decMuteCount(volumeSource) == 0) {
7026 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007027 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007028 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007029 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007030 delayMs);
7031 }
7032 }
7033}
7034
François Gaffie53615e22015-03-19 09:24:12 +01007035bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7036{
François Gaffiec005e562018-11-06 15:04:49 +01007037 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007038 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7039 return true;
7040 }
7041
7042 // has known usage?
7043 switch (paa->usage) {
7044 case AUDIO_USAGE_UNKNOWN:
7045 case AUDIO_USAGE_MEDIA:
7046 case AUDIO_USAGE_VOICE_COMMUNICATION:
7047 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7048 case AUDIO_USAGE_ALARM:
7049 case AUDIO_USAGE_NOTIFICATION:
7050 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7051 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7052 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7053 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7054 case AUDIO_USAGE_NOTIFICATION_EVENT:
7055 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7056 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7057 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7058 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007059 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007060 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007061 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007062 case AUDIO_USAGE_EMERGENCY:
7063 case AUDIO_USAGE_SAFETY:
7064 case AUDIO_USAGE_VEHICLE_STATUS:
7065 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007066 break;
7067 default:
7068 return false;
7069 }
7070 return true;
7071}
7072
François Gaffie2110e042015-03-24 08:41:51 +01007073audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7074{
7075 return mEngine->getForceUse(usage);
7076}
7077
7078bool AudioPolicyManager::isInCall()
7079{
7080 return isStateInCall(mEngine->getPhoneState());
7081}
7082
7083bool AudioPolicyManager::isStateInCall(int state)
7084{
7085 return is_state_in_call(state);
7086}
7087
Eric Laurent74b71512019-11-06 17:21:57 -08007088bool AudioPolicyManager::isCallAudioAccessible()
7089{
7090 audio_mode_t mode = mEngine->getPhoneState();
7091 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007092 || (mode == AUDIO_MODE_CALL_SCREEN)
7093 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007094}
7095
Eric Laurentd60560a2015-04-10 11:31:20 -07007096void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7097{
7098 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007099 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007100 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007101 sourceDesc->sinkDevice()->equals(deviceDesc))
7102 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007103 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007104 }
7105 }
7106
7107 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7108 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7109 bool release = false;
7110 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7111 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7112 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7113 source->ext.device.type == deviceDesc->type()) {
7114 release = true;
7115 }
7116 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007117 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007118 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7119 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7120 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007121 sink->ext.device.type == deviceDesc->type() &&
7122 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7123 || strncmp(sink->ext.device.address, address,
7124 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007125 release = true;
7126 }
7127 }
7128 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007129 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7130 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007131 }
7132 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007133
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007134 mInputs.clearSessionRoutesForDevice(deviceDesc);
7135
Francois Gaffie716e1432019-01-14 16:58:59 +01007136 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007137}
7138
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007139void AudioPolicyManager::modifySurroundFormats(
7140 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007141 std::unordered_set<audio_format_t> enforcedSurround(
7142 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007143 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7144 for (const auto& pair : mConfig.getSurroundFormats()) {
7145 allSurround.insert(pair.first);
7146 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7147 }
Phil Burk09bc4612016-02-24 15:58:15 -08007148
7149 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7150 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007151 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007152 // This is the resulting set of formats depending on the surround mode:
7153 // 'all surround' = allSurround
7154 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7155 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7156 // 'manual surround' = mManualSurroundFormats
7157 // AUTO: formats v 'enforced surround'
7158 // ALWAYS: formats v 'all surround' v 'enforced surround'
7159 // NEVER: formats ^ 'non-surround'
7160 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007161
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007162 std::unordered_set<audio_format_t> formatSet;
7163 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7164 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007165 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007166 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007167 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007168 formatSet.insert(*formatIter);
7169 }
7170 }
7171 } else {
7172 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7173 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007174 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007175
jiabin81772902018-04-02 17:52:27 -07007176 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007177 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007178 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7179 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7180 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007181 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007182 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7183 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7184 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007185 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007186 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007187 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007188 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007189 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007190 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007191}
7192
jiabin06e4bab2019-07-29 10:13:34 -07007193void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7194 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007195 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7196 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7197
7198 // If NEVER, then remove support for channelMasks > stereo.
7199 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007200 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7201 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007202 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007203 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007204 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007205 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007206 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007207 }
7208 }
jiabin81772902018-04-02 17:52:27 -07007209 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7210 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7211 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007212 bool supports5dot1 = false;
7213 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007214 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007215 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7216 supports5dot1 = true;
7217 break;
7218 }
7219 }
7220 // If not then add 5.1 support.
7221 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007222 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007223 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007224 }
Phil Burk09bc4612016-02-24 15:58:15 -08007225 }
7226}
7227
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007228void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007229 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007230 AudioProfileVector &profiles)
7231{
7232 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007233 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007234
François Gaffie112b0af2015-11-19 16:13:25 +01007235 // Format MUST be checked first to update the list of AudioProfile
7236 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007237 reply = mpClientInterface->getParameters(
7238 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007239 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007240 AudioParameter repliedParameters(reply);
7241 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007242 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007243 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7244 return;
7245 }
Phil Burk09bc4612016-02-24 15:58:15 -08007246 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007247 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007248 if (device == AUDIO_DEVICE_OUT_HDMI
7249 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007250 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007251 }
jiabin3e277cc2019-09-10 14:27:34 -07007252 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007253 }
François Gaffie112b0af2015-11-19 16:13:25 +01007254
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007255 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007256 ChannelMaskSet channelMasks;
7257 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007258 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007259 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007260
7261 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007262 reply = mpClientInterface->getParameters(
7263 ioHandle,
7264 requestedParameters.toString() + ";" +
7265 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007266 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007267 AudioParameter repliedParameters(reply);
7268 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007269 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007270 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007271 }
7272 }
7273 if (profiles.hasDynamicChannelsFor(format)) {
7274 reply = mpClientInterface->getParameters(ioHandle,
7275 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007276 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007277 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007278 AudioParameter repliedParameters(reply);
7279 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007280 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007281 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007282 if (device == AUDIO_DEVICE_OUT_HDMI
7283 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007284 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007285 }
François Gaffie112b0af2015-11-19 16:13:25 +01007286 }
7287 }
jiabin3e277cc2019-09-10 14:27:34 -07007288 addDynamicAudioProfileAndSort(
7289 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007290 }
7291}
Eric Laurentd60560a2015-04-10 11:31:20 -07007292
Mikhail Naganovdc769682018-05-04 15:34:08 -07007293status_t AudioPolicyManager::installPatch(const char *caller,
7294 audio_patch_handle_t *patchHandle,
7295 AudioIODescriptorInterface *ioDescriptor,
7296 const struct audio_patch *patch,
7297 int delayMs)
7298{
7299 ssize_t index = mAudioPatches.indexOfKey(
7300 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7301 *patchHandle : ioDescriptor->getPatchHandle());
7302 sp<AudioPatch> patchDesc;
7303 status_t status = installPatch(
7304 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7305 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007306 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007307 }
7308 return status;
7309}
7310
7311status_t AudioPolicyManager::installPatch(const char *caller,
7312 ssize_t index,
7313 audio_patch_handle_t *patchHandle,
7314 const struct audio_patch *patch,
7315 int delayMs,
7316 uid_t uid,
7317 sp<AudioPatch> *patchDescPtr)
7318{
7319 sp<AudioPatch> patchDesc;
7320 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7321 if (index >= 0) {
7322 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007323 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007324 }
7325
7326 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7327 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7328 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7329 if (status == NO_ERROR) {
7330 if (index < 0) {
7331 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007332 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007333 } else {
7334 patchDesc->mPatch = *patch;
7335 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007336 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007337 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007338 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007339 }
7340 nextAudioPortGeneration();
7341 mpClientInterface->onAudioPatchListUpdate();
7342 }
7343 if (patchDescPtr) *patchDescPtr = patchDesc;
7344 return status;
7345}
7346
jiabinbce0c1d2020-10-05 11:20:18 -07007347bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7348{
7349 const TrackClientVector activeClients = output->getActiveClients();
7350 if (activeClients.empty()) {
7351 return true;
7352 }
7353 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7354 if (index < 0) {
7355 ALOGE("%s, no audio patch found while there are active clients on output %d",
7356 __func__, output->getId());
7357 return false;
7358 }
7359 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7360 DeviceVector routedDevices;
7361 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7362 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7363 patchDesc->mPatch.sinks[i].id);
7364 if (device == nullptr) {
7365 ALOGE("%s, no audio device found with id(%d)",
7366 __func__, patchDesc->mPatch.sinks[i].id);
7367 return false;
7368 }
7369 routedDevices.add(device);
7370 }
7371 for (const auto& client : activeClients) {
7372 // TODO: b/175343099 only travel the valid client
7373 sp<DeviceDescriptor> preferredDevice =
7374 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7375 if (mEngine->getOutputDevicesForAttributes(
7376 client->attributes(), preferredDevice, false) == routedDevices) {
7377 return false;
7378 }
7379 }
7380 return true;
7381}
7382
7383sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007384 const sp<IOProfile>& profile, const DeviceVector& devices,
7385 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007386{
7387 for (const auto& device : devices) {
7388 // TODO: This should be checking if the profile supports the device combo.
7389 if (!profile->supportsDevice(device)) {
7390 return nullptr;
7391 }
7392 }
7393 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7394 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007395 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007396 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7397 if (status != NO_ERROR) {
7398 return nullptr;
7399 }
7400
7401 // Here is where the out_set_parameters() for card & device gets called
7402 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7403 const audio_devices_t deviceType = device->type();
7404 const String8 &address = String8(device->address().c_str());
7405 if (!address.isEmpty()) {
7406 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7407 mpClientInterface->setParameters(output, String8(param));
7408 free(param);
7409 }
7410 updateAudioProfiles(device, output, profile->getAudioProfiles());
7411 if (!profile->hasValidAudioProfile()) {
7412 ALOGW("%s() missing param", __func__);
7413 desc->close();
7414 return nullptr;
7415 } else if (profile->hasDynamicAudioProfile()) {
7416 desc->close();
7417 output = AUDIO_IO_HANDLE_NONE;
7418 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7419 profile->pickAudioProfile(
7420 config.sample_rate, config.channel_mask, config.format);
7421 config.offload_info.sample_rate = config.sample_rate;
7422 config.offload_info.channel_mask = config.channel_mask;
7423 config.offload_info.format = config.format;
7424
Eric Laurentb4f42a92022-01-17 17:37:31 +01007425 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007426 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7427 if (status != NO_ERROR) {
7428 return nullptr;
7429 }
7430 }
7431
7432 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007433
jiabinbce0c1d2020-10-05 11:20:18 -07007434 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7435 sp<AudioPolicyMix> policyMix;
7436 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7437 policyMix->setOutput(desc);
7438 desc->mPolicyMix = policyMix;
7439 } else {
7440 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7441 address.string());
7442 }
7443
Eric Laurentb4f42a92022-01-17 17:37:31 +01007444 } else if (hasPrimaryOutput() && profile->getModule()
7445 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7446 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7447 // no duplicated output for:
7448 // - direct outputs
7449 // - outputs used by dynamic policy mixes
7450 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007451 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7452
7453 //TODO: configure audio effect output stage here
7454
7455 // open a duplicating output thread for the new output and the primary output
7456 sp<SwAudioOutputDescriptor> dupOutputDesc =
7457 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7458 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7459 if (status == NO_ERROR) {
7460 // add duplicated output descriptor
7461 addOutput(duplicatedOutput, dupOutputDesc);
7462 } else {
7463 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7464 mPrimaryOutput->mIoHandle, output);
7465 desc->close();
7466 removeOutput(output);
7467 nextAudioPortGeneration();
7468 return nullptr;
7469 }
7470 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007471 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7472 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7473 mPrimaryOutput = desc;
7474 }
jiabinbce0c1d2020-10-05 11:20:18 -07007475 return desc;
7476}
7477
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007478} // namespace android