blob: a836799339f7be15de8a47850a0ffe232b6e10e7 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabinf042b9b2021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070041#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070043#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070044#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070045#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070046#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070047#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070048#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <utils/Log.h>
50
Eric Laurentd4692962014-05-05 18:13:44 -070051#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010052#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurent3b73df72014-03-11 09:06:29 -070054namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070055
Svet Ganov33761132021-05-13 22:51:08 +000056using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070057
Eric Laurentdc462862016-07-19 12:29:53 -070058//FIXME: workaround for truncated touch sounds
59// to be removed when the problem is handled by system UI
60#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070061
62// Largest difference in dB on earpiece in call between the voice volume and another
63// media / notification / system volume.
64constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
65
Mikhail Naganov15be9d22017-11-08 14:18:13 +110066// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110067static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
68 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110069 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
70// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110071static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110072 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
73 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
74 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
75
jiabin06e4bab2019-07-29 10:13:34 -070076template <typename T>
77bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
78{
79 if (left.size() != right.size()) {
80 return false;
81 }
82 for (size_t index = 0; index < right.size(); index++) {
83 if (left[index] != right[index]) {
84 return false;
85 }
86 }
87 return true;
88}
89
90template <typename T>
91bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
92{
93 return !(left == right);
94}
95
Eric Laurente552edb2014-03-10 17:42:56 -070096// ----------------------------------------------------------------------------
97// AudioPolicyInterface implementation
98// ----------------------------------------------------------------------------
99
Eric Laurente0720872014-03-11 09:30:41 -0700100status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -0800101 audio_policy_dev_state_t state,
102 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800103 const char *device_name,
104 audio_format_t encodedFormat)
Eric Laurente552edb2014-03-10 17:42:56 -0700105{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800106 status_t status = setDeviceConnectionStateInt(device, state, device_address,
107 device_name, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
François Gaffie11d30102018-11-02 16:09:09 +0100112void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
113 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200114{
jiabince9f20e2019-09-12 16:29:15 -0700115 AudioParameter param(String8(device->address().c_str()));
François Gaffie44481e72016-04-20 07:49:57 +0200116 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganovf23fcf62019-07-08 15:28:43 -0700117 AudioParameter::keyDeviceConnect : AudioParameter::keyDeviceDisconnect);
François Gaffie11d30102018-11-02 16:09:09 +0100118 param.addInt(key, device->type());
François Gaffie44481e72016-04-20 07:49:57 +0200119 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
120}
121
François Gaffie11d30102018-11-02 16:09:09 +0100122status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800123 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -0800124 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800125 const char *device_name,
126 audio_format_t encodedFormat)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800127{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800128 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
129 deviceType, state, device_address, device_name, encodedFormat);
Eric Laurente552edb2014-03-10 17:42:56 -0700130
131 // connect/disconnect only 1 device at a time
François Gaffie11d30102018-11-02 16:09:09 +0100132 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -0700133
François Gaffie11d30102018-11-02 16:09:09 +0100134 sp<DeviceDescriptor> device =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800135 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
Francois Gaffie716e1432019-01-14 16:58:59 +0100136 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700137 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
138}
Paul McLeane743a472015-01-28 11:07:31 -0800139
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700140status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
141 audio_policy_dev_state_t state)
142{
Eric Laurente552edb2014-03-10 17:42:56 -0700143 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700144 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700145 SortedVector <audio_io_handle_t> outputs;
146
François Gaffie11d30102018-11-02 16:09:09 +0100147 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700148
Eric Laurente552edb2014-03-10 17:42:56 -0700149 // save a copy of the opened output descriptors before any output is opened or closed
150 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
151 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700152 switch (state)
153 {
154 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800155 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100157 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700158 return INVALID_OPERATION;
159 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800160 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700161 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700162
Eric Laurente552edb2014-03-10 17:42:56 -0700163 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200164 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700165 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700166 }
167
François Gaffie44481e72016-04-20 07:49:57 +0200168 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
169 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100170 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200171
François Gaffie11d30102018-11-02 16:09:09 +0100172 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
173 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200174
Francois Gaffie716e1432019-01-14 16:58:59 +0100175 mHwModules.cleanUpForDevice(device);
176
François Gaffie11d30102018-11-02 16:09:09 +0100177 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700178 return INVALID_OPERATION;
179 }
François Gaffie2110e042015-03-24 08:41:51 +0100180
jiabin1c4794b2020-05-05 10:08:05 -0700181 // Populate encapsulation information when a output device is connected.
182 device->setEncapsulationInfoFromHal(mpClientInterface);
183
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700184 // outputs should never be empty here
185 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
186 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100187 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800188
Eric Laurent3ae5f312015-02-03 17:12:08 -0800189 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700191 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100193 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700194 return INVALID_OPERATION;
195 }
196
François Gaffie11d30102018-11-02 16:09:09 +0100197 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700198
Paul McLeane743a472015-01-28 11:07:31 -0800199 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100200 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100203 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700204
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100205 mOutputs.clearSessionRoutesForDevice(device);
206
François Gaffie11d30102018-11-02 16:09:09 +0100207 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100208
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800209 // Reset active device codec
210 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
211
Kriti Dangef6be8f2020-11-05 11:58:19 +0100212 // remove device from mReportedFormatsMap cache
213 mReportedFormatsMap.erase(device);
214
Eric Laurente552edb2014-03-10 17:42:56 -0700215 } break;
216
217 default:
François Gaffie11d30102018-11-02 16:09:09 +0100218 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700219 return BAD_VALUE;
220 }
221
Eric Laurent736a1022019-03-27 18:28:46 -0700222 // Propagate device availability to Engine
223 setEngineDeviceConnectionState(device, state);
224
Eric Laurentae970022019-01-29 14:25:04 -0800225 // No need to evaluate playback routing when connecting a remote submix
226 // output device used by a dynamic policy of type recorder as no
227 // playback use case is affected.
228 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700229 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800230 for (audio_io_handle_t output : outputs) {
231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800232 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
233 if (policyMix != nullptr
234 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700235 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800236 doCheckForDeviceAndOutputChanges = false;
237 break;
238 }
239 }
240 }
241
242 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700243 // outputs must be closed after checkOutputForAllStrategies() is executed
244 if (!outputs.isEmpty()) {
245 for (audio_io_handle_t output : outputs) {
246 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100247 // close unused outputs after device disconnection or direct outputs that have
248 // been opened by checkOutputsForDevice() to query dynamic parameters
Mikhail Naganov37977152018-07-11 15:54:44 -0700249 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
250 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurentae970022019-01-29 14:25:04 -0800251 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200252 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700253 closeOutput(output);
254 }
Eric Laurente552edb2014-03-10 17:42:56 -0700255 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700256 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
257 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700258 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700259 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800260 };
261
262 if (doCheckForDeviceAndOutputChanges) {
263 checkForDeviceAndOutputChanges(checkCloseOutputs);
264 } else {
265 checkCloseOutputs();
266 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100267 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700268 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100269 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700270 const DeviceVector activeMediaDevices =
271 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700273 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530274 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
275 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100276 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700277 // do not force device change on duplicated output because if device is 0, it will
278 // also force a device 0 for the two outputs it is duplicated to which may override
279 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100280 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100281 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700283 // always force when disconnecting (a non-duplicated device)
284 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100285 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700286 }
jiabinbce0c1d2020-10-05 11:20:18 -0700287 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000288 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700289 desc->supportsDevicesForPlayback(activeMediaDevices)) {
290 // Reopen the output to query the dynamic profiles when there is not active
291 // clients or all active clients will be rerouted. Otherwise, set the flag
292 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
293 // can be reopened to query dynamic profiles when all clients are inactive.
294 if (areAllActiveTracksRerouted(desc)) {
295 outputsToReopen.push_back(mOutputs.keyAt(i));
296 } else {
297 desc->mPendingReopenToQueryProfiles = true;
298 }
299 }
300 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
301 // Clear the flag that previously set for re-querying profiles.
302 desc->mPendingReopenToQueryProfiles = false;
303 }
304 }
305 for (const auto& output : outputsToReopen) {
306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
307 closeOutput(output);
308 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310
Eric Laurentd60560a2015-04-10 11:31:20 -0700311 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100312 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700313 }
314
Eric Laurent72aa32f2014-05-30 18:51:48 -0700315 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700316 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700317 } // end if is output device
318
Eric Laurente552edb2014-03-10 17:42:56 -0700319 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700320 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100321 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700322 switch (state)
323 {
324 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700325 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700328 return INVALID_OPERATION;
329 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700330
331 if (mAvailableInputDevices.add(device) < 0) {
332 return NO_MEMORY;
333 }
334
François Gaffie44481e72016-04-20 07:49:57 +0200335 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
336 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100337 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200338
Eric Laurent0dd51852019-04-19 18:18:58 -0700339 if (checkInputsForDevice(device, state) != NO_ERROR) {
340 mAvailableInputDevices.remove(device);
341
François Gaffie11d30102018-11-02 16:09:09 +0100342 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100343
344 mHwModules.cleanUpForDevice(device);
345
Eric Laurentd4692962014-05-05 18:13:44 -0700346 return INVALID_OPERATION;
347 }
348
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100354 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700355 return INVALID_OPERATION;
356 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700357
François Gaffie11d30102018-11-02 16:09:09 +0100358 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700359
360 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100361 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700362
François Gaffie11d30102018-11-02 16:09:09 +0100363 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700364
365 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100366
367 // remove device from mReportedFormatsMap cache
368 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700369 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700370
371 default:
François Gaffie11d30102018-11-02 16:09:09 +0100372 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700373 return BAD_VALUE;
374 }
375
Eric Laurent736a1022019-03-27 18:28:46 -0700376 // Propagate device availability to Engine
377 setEngineDeviceConnectionState(device, state);
378
Eric Laurent0dd51852019-04-19 18:18:58 -0700379 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700380 // As the input device list can impact the output device selection, update
381 // getDeviceForStrategy() cache
382 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700383
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100384 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200385 // Reconnect Audio Source
386 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
387 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
388 checkAudioSourceForAttributes(attributes);
389 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700390 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100391 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700392 }
393
Eric Laurentb52c1522014-05-20 11:27:36 -0700394 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700395 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700396 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700397
François Gaffie11d30102018-11-02 16:09:09 +0100398 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700399 return BAD_VALUE;
400}
401
Eric Laurent736a1022019-03-27 18:28:46 -0700402void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
403 audio_policy_dev_state_t state) {
404
405 // the Engine does not have to know about remote submix devices used by dynamic audio policies
406 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
407 return;
408 }
409 mEngine->setDeviceConnectionState(device, state);
410}
411
412
Eric Laurente0720872014-03-11 09:30:41 -0700413audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100414 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700415{
Eric Laurent634b7142016-04-20 13:48:02 -0700416 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800417 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
418 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700419 (strlen(device_address) != 0)/*matchAddress*/);
420
421 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100422 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700423 device, device_address);
424 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
425 }
François Gaffie53615e22015-03-19 09:24:12 +0100426
Eric Laurent3a4311c2014-03-17 12:00:47 -0700427 DeviceVector *deviceVector;
428
Eric Laurente552edb2014-03-10 17:42:56 -0700429 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700430 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700431 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700432 deviceVector = &mAvailableInputDevices;
433 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100434 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700435 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700436 }
Eric Laurent634b7142016-04-20 13:48:02 -0700437
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800438 return (deviceVector->getDevice(
439 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700440 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800441}
442
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800443status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
444 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800445 const char *device_name,
446 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800447{
448 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700449 String8 reply;
450 AudioParameter param;
451 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800452
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800453 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
454 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800455
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800456 // connect/disconnect only 1 device at a time
457 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
458
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800459 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700460 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800461 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800462 // Nothing to do: device is not connected
463 return NO_ERROR;
464 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800465 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800466
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700467 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 // configure codecs.
469 // Handle two specific cases by sending a set parameter to
470 // configure A2DP codecs. No need to toggle device state.
471 // Case 1: A2DP active device switches from primary to primary
472 // module
473 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200474 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700475 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800476 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
477 if (availablePrimaryOutputDevices().contains(devDesc) &&
478 (module != 0 && module->getHandle() == primaryHandle)) {
479 reply = mpClientInterface->getParameters(
480 AUDIO_IO_HANDLE_NONE,
481 String8(AudioParameter::keyReconfigA2dpSupported));
482 AudioParameter repliedParameters(reply);
483 repliedParameters.getInt(
484 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
485 if (isReconfigA2dpSupported) {
486 const String8 key(AudioParameter::keyReconfigA2dp);
487 param.add(key, String8("true"));
488 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
489 devDesc->setEncodedFormat(encodedFormat);
490 return NO_ERROR;
491 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700492 }
493 }
cnx421bd2dcc42020-07-11 14:58:44 +0800494 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
495 for (size_t i = 0; i < mOutputs.size(); i++) {
496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
497 // mute media strategies and delay device switch by the largest
498 // This avoid sending the music tail into the earpiece or headset.
499 setStrategyMute(musicStrategy, true, desc);
500 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
501 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
502 nullptr, true /*fromCache*/).types());
503 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504 // Toggle the device state: UNAVAILABLE -> AVAILABLE
505 // This will force reading again the device configuration
506 status = setDeviceConnectionState(device,
507 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800508 device_address, device_name,
509 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510 if (status != NO_ERROR) {
511 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
512 status);
513 return status;
514 }
515
516 status = setDeviceConnectionState(device,
517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 if (status != NO_ERROR) {
520 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
521 status);
522 return status;
523 }
524
525 return NO_ERROR;
526}
527
Pattye4981552021-11-04 21:01:03 +0800528status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
529 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800530{
Pattye4981552021-11-04 21:01:03 +0800531 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800532 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800533 std::unordered_set<audio_format_t> formatSet;
534 sp<HwModule> primaryModule =
535 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700536 if (primaryModule == nullptr) {
537 ALOGE("%s() unable to get primary module", __func__);
538 return NO_INIT;
539 }
Pattye4981552021-11-04 21:01:03 +0800540
541 DeviceTypeSet audioDeviceSet;
542
543 switch(device) {
544 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
545 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
546 break;
547 case AUDIO_DEVICE_OUT_BLE_HEADSET:
548 audioDeviceSet = getAudioDeviceOutAllBleSet();
549 break;
550 default:
551 ALOGE("%s() device type 0x%08x not supported", __func__, device);
552 return BAD_VALUE;
553 }
554
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattye4981552021-11-04 21:01:03 +0800556 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800557 for (const auto& device : declaredDevices) {
558 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800559 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800560 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800561 return status;
562}
563
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100564DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
565{
566 DeviceVector rxSinkdevices{};
567 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
568 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
569 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
570 auto rxSinkDevice = rxSinkdevices.itemAt(0);
571 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
572 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
573 // retrieve Rx Source device descriptor
574 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
575 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
576
577 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
578 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
579 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
580 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
581 return DeviceVector(rxSinkDevice);
582 }
583 }
584 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
585 // the device returned is not necessarily reachable via this output
586 // (filter later by setOutputDevices())
587 return getNewOutputDevices(mPrimaryOutput, fromCache);
588}
589
590status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
591{
592 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
593 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
594 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
595 }
596 return INVALID_OPERATION;
597}
598
599status_t AudioPolicyManager::updateCallRoutingInternal(
600 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700601{
602 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100603 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700604 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700605 if(!hasPrimaryOutput() ||
606 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100607 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700608 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100609 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100610
Francois Gaffie716e1432019-01-14 16:58:59 +0100611 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100612 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100614
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100615 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100616 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700617
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200618 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700619 // release TX patch if any
620 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100621 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700622 mCallTxPatch.clear();
623 }
624
François Gaffie9eb18552018-11-05 10:33:26 +0100625 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700626 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100627 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700628 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100629 // retrieve Rx Source and Tx Sink device descriptors
630 sp<DeviceDescriptor> rxSourceDevice =
631 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
632 String8(),
633 AUDIO_FORMAT_DEFAULT);
634 sp<DeviceDescriptor> txSinkDevice =
635 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
636 String8(),
637 AUDIO_FORMAT_DEFAULT);
638
639 // RX and TX Telephony device are declared by Primary Audio HAL
640 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
641 (telephonyRxModule->getHalVersionMajor() >= 3)) {
642 if (rxSourceDevice == 0 || txSinkDevice == 0) {
643 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100644 ALOGE("%s() no telephony Tx and/or RX device", __func__);
645 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100646 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100647 // createAudioPatchInternal now supports both HW / SW bridging
648 createRxPatch = true;
649 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100650 } else {
651 // If the RX device is on the primary HW module, then use legacy routing method for
652 // voice calls via setOutputDevice() on primary output.
653 // Otherwise, create two audio patches for TX and RX path.
654 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
655 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700656 // If the TX device is also on the primary HW module, setOutputDevice() will take care
657 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100658 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
659 (txSinkDevice != 0);
660 }
661 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
662 // Otherwise, create two audio patches for TX and RX path.
663 if (!createRxPatch) {
664 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700665 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200666 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800667 // If the TX device is on the primary HW module but RX device is
668 // on other HW module, SinkMetaData of telephony input should handle it
669 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700671 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100672 // terminate active capture if on the same HW module as the call TX source device
673 // FIXME: would be better to refine to only inputs whose profile connects to the
674 // call TX device but this information is not in the audio patch and logic here must be
675 // symmetric to the one in startInput()
676 for (const auto& activeDesc : mInputs.getActiveInputs()) {
677 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
678 closeActiveClients(activeDesc);
679 }
680 }
François Gaffie9eb18552018-11-05 10:33:26 +0100681 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800682 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683 if (waitMs != nullptr) {
684 *waitMs = muteWaitMs;
685 }
686 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800687}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700688
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800689sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100690 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700691 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692
François Gaffie11d30102018-11-02 16:09:09 +0100693 if (device == nullptr) {
694 return nullptr;
695 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100696
697 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800698 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100699 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800700 addSource(mAvailableInputDevices.getDevice(
701 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800702 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100703 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800704 addSink(mAvailableOutputDevices.getDevice(
705 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800706 }
707
François Gaffieafd4cea2019-11-18 15:50:22 +0100708 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
709 status_t status =
710 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
711 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
712 if (status != NO_ERROR || index < 0) {
713 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
714 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800715 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100716 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800717}
718
Mikhail Naganov100f0122018-11-29 11:22:16 -0800719bool AudioPolicyManager::isDeviceOfModule(
720 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
721 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
722 if (module != 0) {
723 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
724 .indexOf(devDesc) != NAME_NOT_FOUND
725 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
726 .indexOf(devDesc) != NAME_NOT_FOUND;
727 }
728 return false;
729}
730
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200731void AudioPolicyManager::connectTelephonyRxAudioSource()
732{
733 disconnectTelephonyRxAudioSource();
734 const struct audio_port_config source = {
735 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
736 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
737 };
738 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
739 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
740 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
741}
742
743void AudioPolicyManager::disconnectTelephonyRxAudioSource()
744{
745 stopAudioSource(mCallRxSourceClientPort);
746 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
747}
748
Eric Laurente0720872014-03-11 09:30:41 -0700749void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700750{
751 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100752 // store previous phone state for management of sonification strategy below
753 int oldState = mEngine->getPhoneState();
754
755 if (mEngine->setPhoneState(state) != NO_ERROR) {
756 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 return;
758 }
François Gaffie2110e042015-03-24 08:41:51 +0100759 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700760 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700761 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700762 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800763 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700764 }
765
François Gaffie2110e042015-03-24 08:41:51 +0100766 /**
767 * Switching to or from incall state or switching between telephony and VoIP lead to force
768 * routing command.
769 */
Eric Laurent74b71512019-11-06 17:21:57 -0800770 bool force = ((isStateInCall(oldState) != isStateInCall(state))
771 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700772
773 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700774 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700775
Eric Laurente552edb2014-03-10 17:42:56 -0700776 int delayMs = 0;
777 if (isStateInCall(state)) {
778 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100779 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
780 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700781 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700782 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700783 // mute media and sonification strategies and delay device switch by the largest
784 // latency of any output where either strategy is active.
785 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100786 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
787 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
788 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700789 (delayMs < (int)desc->latency()*2)) {
790 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700791 }
François Gaffiec005e562018-11-06 15:04:49 +0100792 setStrategyMute(musicStrategy, true, desc);
793 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
794 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
795 nullptr, true /*fromCache*/).types());
796 setStrategyMute(sonificationStrategy, true, desc);
797 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
798 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
799 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700800 }
801 }
802
Eric Laurent87ffa392015-05-22 10:32:38 -0700803 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700804 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100805 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700806 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100807 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
808 // force routing command to audio hardware when ending call
809 // even if no device change is needed
810 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
811 rxDevices = mPrimaryOutput->devices();
812 }
813 if (oldState == AUDIO_MODE_IN_CALL) {
814 disconnectTelephonyRxAudioSource();
815 if (mCallTxPatch != 0) {
816 releaseAudioPatchInternal(mCallTxPatch->getHandle());
817 mCallTxPatch.clear();
818 }
819 }
François Gaffie11d30102018-11-02 16:09:09 +0100820 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700821 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700822 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700823
824 // reevaluate routing on all outputs in case tracks have been started during the call
825 for (size_t i = 0; i < mOutputs.size(); i++) {
826 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100827 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700828 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100829 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700830 }
831 }
832
Eric Laurente552edb2014-03-10 17:42:56 -0700833 if (isStateInCall(state)) {
834 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700835 // force reevaluating accessibility routing when call starts
836 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700837 }
838
839 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100840 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
841 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700842}
843
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700844audio_mode_t AudioPolicyManager::getPhoneState() {
845 return mEngine->getPhoneState();
846}
847
Eric Laurente0720872014-03-11 09:30:41 -0700848void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100849 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700850{
François Gaffie2110e042015-03-24 08:41:51 +0100851 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700852 if (config == mEngine->getForceUse(usage)) {
853 return;
854 }
Eric Laurente552edb2014-03-10 17:42:56 -0700855
François Gaffie2110e042015-03-24 08:41:51 +0100856 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
857 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
858 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700859 }
François Gaffie2110e042015-03-24 08:41:51 +0100860 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
861 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
862 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700863
864 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700865 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800866
Eric Laurent22fcda22019-05-17 16:28:47 -0700867 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
868 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
869 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
870 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
871 }
872
Eric Laurentdc462862016-07-19 12:29:53 -0700873 //FIXME: workaround for truncated touch sounds
874 // to be removed when the problem is handled by system UI
875 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700876 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
877 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
878 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700879
880 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100881 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700882}
883
Eric Laurente0720872014-03-11 09:30:41 -0700884void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700885{
886 ALOGV("setSystemProperty() property %s, value %s", property, value);
887}
888
Michael Chana94fbb22018-04-24 14:31:19 +1000889// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
890// search to profiles for direct outputs.
891sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100892 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000893 uint32_t samplingRate,
894 audio_format_t format,
895 audio_channel_mask_t channelMask,
896 audio_output_flags_t flags,
897 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700898{
Michael Chana94fbb22018-04-24 14:31:19 +1000899 if (directOnly) {
900 // only retain flags that will drive the direct output profile selection
901 // if explicitly requested
902 static const uint32_t kRelevantFlags =
903 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700904 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000905 flags =
906 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
907 }
Eric Laurent861a6282015-05-18 15:40:16 -0700908
909 sp<IOProfile> profile;
910
Mikhail Naganovd4120142017-12-06 15:49:22 -0800911 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800912 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100913 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700914 samplingRate, NULL /*updatedSamplingRate*/,
915 format, NULL /*updatedFormat*/,
916 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700917 flags)) {
918 continue;
919 }
920 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100921 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700922 continue;
923 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800924 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700925 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800926 continue;
927 }
Michael Chana94fbb22018-04-24 14:31:19 +1000928 if (!directOnly) return curProfile;
929 // when searching for direct outputs, if several profiles are compatible, give priority
930 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100931 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700932 continue;
933 }
934 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100935 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700936 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700937 }
Eric Laurente552edb2014-03-10 17:42:56 -0700938 }
939 }
Eric Laurent861a6282015-05-18 15:40:16 -0700940 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700941}
942
Eric Laurentf4e63452017-11-06 19:31:46 +0000943audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -0700944{
François Gaffiec005e562018-11-06 15:04:49 +0100945 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -0800946
947 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
948 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
949 // format, flags, etc. This may result in some discrepancy for functions that utilize
950 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
951 // and AudioSystem::getOutputSamplingRate().
952
François Gaffie11d30102018-11-02 16:09:09 +0100953 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -0700954 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -0700955
François Gaffie11d30102018-11-02 16:09:09 +0100956 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
957 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +0000958 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700959}
960
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700961status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
962 const audio_attributes_t *srcAttr,
963 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700964{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700965 if (srcAttr != NULL) {
966 if (!isValidAttributes(srcAttr)) {
967 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
968 __func__,
969 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
970 srcAttr->tags);
971 return BAD_VALUE;
972 }
973 *dstAttr = *srcAttr;
974 } else {
975 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
976 ALOGE("%s: invalid stream type", __func__);
977 return BAD_VALUE;
978 }
François Gaffiec005e562018-11-06 15:04:49 +0100979 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700980 }
Eric Laurent22fcda22019-05-17 16:28:47 -0700981
982 // Only honor audibility enforced when required. The client will be
983 // forced to reconnect if the forced usage changes.
984 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -0700985 dstAttr->flags = static_cast<audio_flags_mask_t>(
986 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -0700987 }
988
Hongwei Wangbb93dfb2018-10-23 13:54:22 -0700989 return NO_ERROR;
990}
991
Kevin Rocard153f92d2018-12-18 18:33:28 -0800992status_t AudioPolicyManager::getOutputForAttrInt(
993 audio_attributes_t *resultAttr,
994 audio_io_handle_t *output,
995 audio_session_t session,
996 const audio_attributes_t *attr,
997 audio_stream_type_t *stream,
998 uid_t uid,
999 const audio_config_t *config,
1000 audio_output_flags_t *flags,
1001 audio_port_handle_t *selectedDeviceId,
1002 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001003 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001004 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001005{
François Gaffiec005e562018-11-06 15:04:49 +01001006 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001007 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001008 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001009 const sp<DeviceDescriptor> requestedDevice =
1010 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1011
Eric Laurent8a1095a2019-11-08 14:44:16 -08001012 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001013 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1014 if (status != NO_ERROR) {
1015 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001016 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001017 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001018 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001019 }
François Gaffiec005e562018-11-06 15:04:49 +01001020 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001021
François Gaffiec005e562018-11-06 15:04:49 +01001022 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1023 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001024
Kevin Rocard153f92d2018-12-18 18:33:28 -08001025 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1026 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1027 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001028 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11001029 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1030 .channel_mask = config->channel_mask,
1031 .format = config->format,
1032 };
1033 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1034 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001035 if (status != OK) {
1036 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001037 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001038
Kevin Rocard153f92d2018-12-18 18:33:28 -08001039 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001040 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001041
1042 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11001043 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1044 && !audio_is_linear_pcm(config->format)) {
1045 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001046 return BAD_VALUE;
1047 }
1048 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001049 sp<DeviceDescriptor> deviceDesc =
1050 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1051 primaryMix->mDeviceAddress,
1052 AUDIO_FORMAT_DEFAULT);
1053 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001054 bool tryDirectForFlags = policyDesc == nullptr ||
1055 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1056 // if a direct output can be opened to deliver the track's multi-channel content to the
1057 // output rather than being downmixed by the primary output, then use this direct
1058 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1059 // mix.
1060 bool tryDirectForChannelMask = policyDesc != nullptr
1061 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1062 audio_channel_count_from_out_mask(config->channel_mask));
1063 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001064 audio_io_handle_t newOutput;
1065 status = openDirectOutput(
1066 *stream, session, config,
1067 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1068 DeviceVector(deviceDesc), &newOutput);
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001069 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001070 policyDesc = mOutputs.valueFor(newOutput);
1071 primaryMix->setOutput(policyDesc);
Dean Wheatley62dc33b2022-03-04 10:51:36 +11001072 } else if (tryDirectForFlags) {
1073 policyDesc = nullptr;
1074 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001075 }
1076 if (policyDesc != nullptr) {
1077 policyDesc->mPolicyMix = primaryMix;
1078 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001079 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001080
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001081 ALOGV("getOutputForAttr() returns output %d", *output);
1082 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1083 *outputType = API_OUT_MIX_PLAYBACK;
1084 } else {
1085 *outputType = API_OUTPUT_LEGACY;
1086 }
1087 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001088 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001089 }
François Gaffiec005e562018-11-06 15:04:49 +01001090 // Virtual sources must always be dynamicaly or explicitly routed
1091 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1092 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1093 return BAD_VALUE;
1094 }
1095 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1096 // in order to let the choice of the order to future vendor engine
1097 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001098
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001099 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001100 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001101 }
1102
Nadav Barb2f18162018-07-18 13:01:53 +03001103 // Set incall music only if device was explicitly set, and fallback to the device which is
1104 // chosen by the engine if not.
1105 // FIXME: provide a more generic approach which is not device specific and move this back
1106 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001107 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001108 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001109 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001110 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001111 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001112 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001113 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001114 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001115 }
1116 }
1117
François Gaffiec005e562018-11-06 15:04:49 +01001118 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1119 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1120 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001121
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001122 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001123 if (!msdDevices.isEmpty()) {
1124 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001125 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001126 ALOGV("%s() Using MSD devices %s instead of devices %s",
1127 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001128 } else {
1129 *output = AUDIO_IO_HANDLE_NONE;
1130 }
1131 }
1132 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001133 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001134 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001135 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001136 if (*output == AUDIO_IO_HANDLE_NONE) {
1137 return INVALID_OPERATION;
1138 }
Paul McLeanaa981192015-03-21 09:55:15 -07001139
François Gaffiec005e562018-11-06 15:04:49 +01001140 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001141 for (auto &outputDevice : outputDevices) {
1142 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1143 *selectedDeviceId = outputDevice->getId();
1144 break;
1145 }
1146 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001147
Eric Laurent8a1095a2019-11-08 14:44:16 -08001148 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1149 *outputType = API_OUTPUT_TELEPHONY_TX;
1150 } else {
1151 *outputType = API_OUTPUT_LEGACY;
1152 }
1153
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001154 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1155
1156 return NO_ERROR;
1157}
1158
1159status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1160 audio_io_handle_t *output,
1161 audio_session_t session,
1162 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001163 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001164 const audio_config_t *config,
1165 audio_output_flags_t *flags,
1166 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001168 std::vector<audio_io_handle_t> *secondaryOutputs,
1169 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001170{
1171 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1172 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1173 return INVALID_OPERATION;
1174 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001175 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001176 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001177 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001178 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001179 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001180 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001181 const sp<DeviceDescriptor> requestedDevice =
1182 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1183
1184 // Prevent from storing invalid requested device id in clients
1185 const audio_port_handle_t sanitizedRequestedPortId =
1186 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1187 *selectedDeviceId = sanitizedRequestedPortId;
1188
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001189 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001190 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001191 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001192 if (status != NO_ERROR) {
1193 return status;
1194 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001195 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001196 if (secondaryOutputs != nullptr) {
1197 for (auto &secondaryMix : secondaryMixes) {
1198 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1199 if (outputDesc != nullptr &&
1200 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1201 secondaryOutputs->push_back(outputDesc->mIoHandle);
1202 weakSecondaryOutputDescs.push_back(outputDesc);
1203 }
1204 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001206
Eric Laurent8fc147b2018-07-22 19:13:55 -07001207 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001208 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001209 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001210 };
jiabin4ef93452019-09-10 14:29:54 -07001211 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001212
Eric Laurentc209fe42020-06-05 18:11:23 -07001213 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001214 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001215 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001216 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001217 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001218 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001220 std::move(weakSecondaryOutputDescs),
1221 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001222 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001223
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001224 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1225 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001226
Eric Laurente83b55d2014-11-14 10:06:21 -08001227 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001228}
1229
Eric Laurentc529cf62020-04-17 18:19:10 -07001230status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1231 audio_session_t session,
1232 const audio_config_t *config,
1233 audio_output_flags_t flags,
1234 const DeviceVector &devices,
1235 audio_io_handle_t *output) {
1236
1237 *output = AUDIO_IO_HANDLE_NONE;
1238
1239 // skip direct output selection if the request can obviously be attached to a mixed output
1240 // and not explicitly requested
1241 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1242 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1243 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1244 return NAME_NOT_FOUND;
1245 }
1246
1247 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1248 // This prevents creating an offloaded track and tearing it down immediately after start
1249 // when audioflinger detects there is an active non offloadable effect.
1250 // FIXME: We should check the audio session here but we do not have it in this context.
1251 // This may prevent offloading in rare situations where effects are left active by apps
1252 // in the background.
1253 sp<IOProfile> profile;
1254 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1255 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1256 profile = getProfileForOutput(
1257 devices, config->sample_rate, config->format, config->channel_mask,
1258 flags, true /* directOnly */);
1259 }
1260
1261 if (profile == nullptr) {
1262 return NAME_NOT_FOUND;
1263 }
1264
1265 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1266 for (size_t i = 0; i < mOutputs.size(); i++) {
1267 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1268 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1269 // reuse direct output if currently open by the same client
1270 // and configured with same parameters
1271 if ((config->sample_rate == desc->getSamplingRate()) &&
1272 (config->format == desc->getFormat()) &&
1273 (config->channel_mask == desc->getChannelMask()) &&
1274 (session == desc->mDirectClientSession)) {
1275 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001276 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 mOutputs.keyAt(i), session);
1278 *output = mOutputs.keyAt(i);
1279 return NO_ERROR;
1280 }
1281 }
1282 }
1283
1284 if (!profile->canOpenNewIo()) {
1285 return NAME_NOT_FOUND;
1286 }
1287
1288 sp<SwAudioOutputDescriptor> outputDesc =
1289 new SwAudioOutputDescriptor(profile, mpClientInterface);
1290
Michael Chan6fb34492020-12-08 15:44:49 +11001291 // An MSD patch may be using the only output stream that can service this request. Release
1292 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001293 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001294
1295 status_t status = outputDesc->open(config, devices, stream, flags, output);
1296
1297 // only accept an output with the requested parameters
1298 if (status != NO_ERROR ||
1299 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1300 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1301 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1302 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1303 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1304 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1305 config->channel_mask, outputDesc->getChannelMask());
1306 if (*output != AUDIO_IO_HANDLE_NONE) {
1307 outputDesc->close();
1308 }
1309 // fall back to mixer output if possible when the direct output could not be open
1310 if (audio_is_linear_pcm(config->format) &&
1311 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1312 return NAME_NOT_FOUND;
1313 }
1314 *output = AUDIO_IO_HANDLE_NONE;
1315 return BAD_VALUE;
1316 }
1317 outputDesc->mDirectOpenCount = 1;
1318 outputDesc->mDirectClientSession = session;
1319
1320 addOutput(*output, outputDesc);
1321 mPreviousOutputs = mOutputs;
1322 ALOGV("%s returns new direct output %d", __func__, *output);
1323 mpClientInterface->onAudioPortListUpdate();
1324 return NO_ERROR;
1325}
1326
François Gaffie11d30102018-11-02 16:09:09 +01001327audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1328 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001329 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001330 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001331 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001332 audio_output_flags_t *flags,
1333 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001334{
Andy Hungc88b0642018-04-27 15:42:35 -07001335 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001336
jiabine375d412019-02-26 12:54:53 -08001337 // Discard haptic channel mask when forcing muting haptic channels.
1338 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001339 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1340 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001341
Eric Laurente552edb2014-03-10 17:42:56 -07001342 // open a direct output if required by specified parameters
1343 //force direct flag if offload flag is set: offloading implies a direct output stream
1344 // and all common behaviors are driven by checking only the direct flag
1345 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001346 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1347 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001348 }
Nadav Bar766fb022018-01-07 12:18:03 +02001349 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1350 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001351 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001352 // only allow deep buffering for music stream type
1353 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001354 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001355 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001356 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001357 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1358 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001359 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001360 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001361 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001362 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001363 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001364 audio_is_linear_pcm(config->format) &&
1365 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001366 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001367 AUDIO_OUTPUT_FLAG_DIRECT);
1368 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001369 }
Eric Laurente552edb2014-03-10 17:42:56 -07001370
Eric Laurentc529cf62020-04-17 18:19:10 -07001371 audio_config_t directConfig = *config;
1372 directConfig.channel_mask = channelMask;
1373 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1374 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001375 return output;
1376 }
1377
Eric Laurent14cbfca2016-03-17 09:42:16 -07001378 // A request for HW A/V sync cannot fallback to a mixed output because time
1379 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001380 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001381 return AUDIO_IO_HANDLE_NONE;
1382 }
1383
Eric Laurente552edb2014-03-10 17:42:56 -07001384 // ignoring channel mask due to downmix capability in mixer
1385
1386 // open a non direct output
1387
1388 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001389 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001390 // get which output is suitable for the specified stream. The actual
1391 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001392 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001393
Eric Laurent8838a382014-09-08 16:44:28 -07001394 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001395 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001396 output = selectOutput(
1397 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001398 }
François Gaffie11d30102018-11-02 16:09:09 +01001399 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001400 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001401 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001402
Eric Laurente552edb2014-03-10 17:42:56 -07001403 return output;
1404}
1405
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001406sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001407 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1408 mAvailableInputDevices);
1409 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1410}
1411
1412DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1413 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1414 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001415}
1416
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001417const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001418 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001419 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1420 if (msdModule != 0) {
1421 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1422 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1423 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1424 const struct audio_port_config *source = &patch->mPatch.sources[j];
1425 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1426 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001427 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001428 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001429 }
1430 }
1431 }
1432 return msdPatches;
1433}
1434
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001435status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1436 const InputProfileCollection &inputProfiles,
1437 const OutputProfileCollection &outputProfiles,
1438 const sp<DeviceDescriptor> &sourceDevice,
1439 const sp<DeviceDescriptor> &sinkDevice,
1440 AudioProfileVector& sourceProfiles,
1441 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001442 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001443 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001444 return NO_INIT;
1445 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001446 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001447 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001448 return NO_INIT;
1449 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001450 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001451 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1452 inProfile->supportsDevice(sourceDevice)) {
1453 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001454 }
1455 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001456 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001457 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001458 outProfile->supportsDevice(sinkDevice)) {
1459 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001460 }
1461 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001462 return NO_ERROR;
1463}
1464
1465status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1466 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1467 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1468{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001469 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001470 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1471 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1472 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001473 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001474 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1475 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001476 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001477 }
1478 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1479 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1480 sinkConfig->format = bestSinkConfig.format;
1481 // For encoded streams force direct flag to prevent downstream mixing.
1482 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1483 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001484 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1485 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001486 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001487 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1488 // raw and IEC61937 framed streams.
1489 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1490 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1491 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001492 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1493 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1494 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1495 sourceConfig->format = bestSinkConfig.format;
1496 // Copy input stream directly without any processing (e.g. resampling).
1497 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1498 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1499 if (hwAvSync) {
1500 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1501 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1502 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1503 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1504 }
1505 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1506 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1507 sinkConfig->config_mask |= config_mask;
1508 sourceConfig->config_mask |= config_mask;
1509 return NO_ERROR;
1510}
1511
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001512PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1513 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001514{
1515 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001516 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1517 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1518 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1519 if (deviceModule == nullptr) {
1520 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1521 return patchBuilder;
1522 }
1523 const InputProfileCollection inputProfiles = msdIsSource ?
1524 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1525 const OutputProfileCollection outputProfiles = msdIsSource ?
1526 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1527
1528 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1529 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1530 device : getMsdAudioOutDevices().itemAt(0);
1531 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1532
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001533 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1534 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001535 AudioProfileVector sourceProfiles;
1536 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1538 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001539 for (auto hwAvSync : { true, false }) {
1540 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1541 sourceProfiles, sinkProfiles) != NO_ERROR) {
1542 continue;
1543 }
1544 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1545 &sinkConfig) == NO_ERROR) {
1546 // Found a matching config. Re-create PatchBuilder with this config.
1547 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1548 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001549 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001550 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 " supporting PCM format conversion.", __func__);
1552 return patchBuilder;
1553}
1554
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001555status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001556 DeviceVector devices;
1557 if (outputDevices != nullptr && outputDevices->size() > 0) {
1558 devices.add(*outputDevices);
1559 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560 // Use media strategy for unspecified output device. This should only
1561 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1562 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001563 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001564 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001565 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001566 }
Michael Chan6fb34492020-12-08 15:44:49 +11001567 std::vector<PatchBuilder> patchesToCreate;
1568 for (auto i = 0u; i < devices.size(); ++i) {
1569 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001570 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001571 }
1572 // Retain only the MSD patches associated with outputDevices request.
1573 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001574 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001575 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1576 auto retainedPatch = false;
1577 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1578 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1579 patchesToRemove.removeItemsAt(i);
1580 retainedPatch = true;
1581 break;
1582 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001583 }
Michael Chan6fb34492020-12-08 15:44:49 +11001584 if (retainedPatch) {
1585 it = patchesToCreate.erase(it);
1586 continue;
1587 }
1588 ++it;
1589 }
1590 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1591 return NO_ERROR;
1592 }
1593 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1594 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001595 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001596 }
Michael Chan6fb34492020-12-08 15:44:49 +11001597 status_t status = NO_ERROR;
1598 for (const auto &p : patchesToCreate) {
1599 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1600 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1601 char message[256];
1602 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1603 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1604 currStatus == NO_ERROR ? "Success" : "Error",
1605 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1606 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1607 if (currStatus == NO_ERROR) {
1608 ALOGD("%s", message);
1609 } else {
1610 ALOGE("%s", message);
1611 if (status == NO_ERROR) {
1612 status = currStatus;
1613 }
1614 }
1615 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 return status;
1617}
1618
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1620 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001621 for (size_t i = 0; i < msdPatches.size(); i++) {
1622 const auto& patch = msdPatches[i];
1623 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1624 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1625 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1626 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1627 releaseAudioPatch(patch->getHandle(), mUidCached);
1628 break;
1629 }
1630 }
1631 }
1632}
1633
Eric Laurente0720872014-03-11 09:30:41 -07001634audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001635 audio_output_flags_t flags,
1636 audio_format_t format,
1637 audio_channel_mask_t channelMask,
1638 uint32_t samplingRate,
1639 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001640{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001641 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1642 "%s called with format %#x", __func__, format);
1643
jiabinebb6af42020-06-09 17:31:17 -07001644 // Return the output that haptic-generating attached to when 1) session id is specified,
1645 // 2) haptic-generating effect exists for given session id and 3) the output that
1646 // haptic-generating effect attached to is in given outputs.
1647 if (sessionId != AUDIO_SESSION_NONE) {
1648 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1649 sessionId, FX_IID_HAPTICGENERATOR);
1650 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1651 return hapticGeneratingOutput;
1652 }
1653 }
1654
Eric Laurent16c66dd2019-05-01 17:54:10 -07001655 // Flags disqualifying an output: the match must happen before calling selectOutput()
1656 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1657 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1658
1659 // Flags expressing a functional request: must be honored in priority over
1660 // other criteria
1661 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1662 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1663 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1664 // Flags expressing a performance request: have lower priority than serving
1665 // requested sampling rate or channel mask
1666 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1667 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1668 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1669
1670 const audio_output_flags_t functionalFlags =
1671 (audio_output_flags_t)(flags & kFunctionalFlags);
1672 const audio_output_flags_t performanceFlags =
1673 (audio_output_flags_t)(flags & kPerformanceFlags);
1674
1675 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1676
Eric Laurente552edb2014-03-10 17:42:56 -07001677 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001678 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001679 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001680 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001681 // 2: the output with the highest number of requested functional flags
1682 // 3: the output supporting the exact channel mask
1683 // 4: the output with a higher channel count than requested
1684 // 5: the output with a higher sampling rate than requested
1685 // 6: the output with the highest number of requested performance flags
1686 // 7: the output with the bit depth the closest to the requested one
1687 // 8: the primary output
1688 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001689
Eric Laurent16c66dd2019-05-01 17:54:10 -07001690 // matching criteria values in priority order for best matching output so far
1691 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001692
Eric Laurent16c66dd2019-05-01 17:54:10 -07001693 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1694 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1695 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001696
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001697 for (audio_io_handle_t output : outputs) {
1698 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001699 // matching criteria values in priority order for current output
1700 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001701
Eric Laurent16c66dd2019-05-01 17:54:10 -07001702 if (outputDesc->isDuplicated()) {
1703 continue;
1704 }
1705 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1706 continue;
1707 }
Eric Laurent8838a382014-09-08 16:44:28 -07001708
Eric Laurent16c66dd2019-05-01 17:54:10 -07001709 // If haptic channel is specified, use the haptic output if present.
1710 // When using haptic output, same audio format and sample rate are required.
1711 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001712 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001713 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1714 continue;
1715 }
1716 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001717 && format == outputDesc->getFormat()
1718 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001719 currentMatchCriteria[0] = outputHapticChannelCount;
1720 }
1721
1722 // functional flags match
1723 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1724
1725 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001726 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1727 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001728 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1729 channelCount <= outputChannelCount) {
1730 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001731 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1732 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001733 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001734 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001735 currentMatchCriteria[3] = outputChannelCount;
1736 }
1737
1738 // sampling rate match
1739 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001740 samplingRate <= outputDesc->getSamplingRate()) {
1741 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001742 }
1743
1744 // performance flags match
1745 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1746
1747 // format match
1748 if (format != AUDIO_FORMAT_INVALID) {
1749 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001750 PolicyAudioPort::kFormatDistanceMax -
1751 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001752 }
1753
1754 // primary output match
1755 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1756
1757 // compare match criteria by priority then value
1758 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1759 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1760 bestMatchCriteria = currentMatchCriteria;
1761 bestOutput = output;
1762
1763 std::stringstream result;
1764 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1765 std::ostream_iterator<int>(result, " "));
1766 ALOGV("%s new bestOutput %d criteria %s",
1767 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001768 }
1769 }
1770
Eric Laurent16c66dd2019-05-01 17:54:10 -07001771 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001772}
1773
Eric Laurent8fc147b2018-07-22 19:13:55 -07001774status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001775{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001776 ALOGV("%s portId %d", __FUNCTION__, portId);
1777
1778 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1779 if (outputDesc == 0) {
1780 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001781 return BAD_VALUE;
1782 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001783 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001784
Eric Laurent8fc147b2018-07-22 19:13:55 -07001785 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001786 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001787
Eric Laurent733ce942017-12-07 12:18:25 -08001788 status_t status = outputDesc->start();
1789 if (status != NO_ERROR) {
1790 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001791 }
1792
Eric Laurent97ac8712018-07-27 18:59:02 -07001793 uint32_t delayMs;
1794 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001795
1796 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001797 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001798 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001799 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001800 if (delayMs != 0) {
1801 usleep(delayMs * 1000);
1802 }
1803
1804 return status;
1805}
1806
Eric Laurent97ac8712018-07-27 18:59:02 -07001807status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1808 const sp<TrackClientDescriptor>& client,
1809 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001810{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001811 // cannot start playback of STREAM_TTS if any other output is being used
1812 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001813
1814 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001815 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001816 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001817 auto clientStrategy = client->strategy();
1818 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001819 if (stream == AUDIO_STREAM_TTS) {
1820 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001821 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001822 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001823 return INVALID_OPERATION;
1824 } else {
1825 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1826 }
1827 } else {
1828 // some playback other than beacon starts
1829 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1830 }
1831
Eric Laurent77305a62016-07-25 16:39:22 -07001832 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001833 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001834 bool force = !outputDesc->isActive() &&
1835 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001836
François Gaffie11d30102018-11-02 16:09:09 +01001837 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001838 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001839 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001840 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001841 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001842 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001843 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001844 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001845 } else {
1846 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001847 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001848 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1849 AUDIO_FORMAT_DEFAULT);
1850 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1851 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001852 }
1853
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001854 // requiresMuteCheck is false when we can bypass mute strategy.
1855 // It covers a common case when there is no materially active audio
1856 // and muting would result in unnecessary delay and dropped audio.
1857 const uint32_t outputLatencyMs = outputDesc->latency();
1858 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1859
Eric Laurente552edb2014-03-10 17:42:56 -07001860 // increment usage count for this stream on the requested output:
1861 // NOTE that the usage count is the same for duplicated output and hardware output which is
1862 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001863 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001864
1865 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001866 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1867 client->isPreferredDeviceForExclusiveUse()) {
1868 // Preferred device may be exclusive, use only if no other active clients on this output
1869 devices = DeviceVector(
1870 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1871 } else {
1872 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1873 }
François Gaffie11d30102018-11-02 16:09:09 +01001874 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001875 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001876 }
1877 }
Eric Laurente552edb2014-03-10 17:42:56 -07001878
François Gaffiec005e562018-11-06 15:04:49 +01001879 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001880 selectOutputForMusicEffects();
1881 }
1882
François Gaffie1c878552018-11-22 16:53:21 +01001883 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001884 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001885 if (devices.isEmpty()) {
1886 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001887 }
François Gaffiec005e562018-11-06 15:04:49 +01001888 bool shouldWait =
1889 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1890 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1891 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001892 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001893 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001894 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001895 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001896 // An output has a shared device if
1897 // - managed by the same hw module
1898 // - supports the currently selected device
1899 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001900 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001901
Eric Laurent77305a62016-07-25 16:39:22 -07001902 // force a device change if any other output is:
1903 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001904 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001905 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001906 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001907 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001908 // change the device currently selected by the other output.
1909 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001910 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001911 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001912 force = true;
1913 }
1914 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001915 // a notification so that audio focus effect can propagate, or that a mute/unmute
1916 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001917 const uint32_t latencyMs = desc->latency();
1918 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1919
1920 if (shouldWait && isActive && (waitMs < latencyMs)) {
1921 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001922 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001923
1924 // Require mute check if another output is on a shared device
1925 // and currently active to have proper drain and avoid pops.
1926 // Note restoring AudioTracks onto this output needs to invoke
1927 // a volume ramp if there is no mute.
1928 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001929 }
1930 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001931
1932 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001933 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001934
Eric Laurente552edb2014-03-10 17:42:56 -07001935 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001936 auto &curves = getVolumeCurves(client->attributes());
1937 checkAndSetVolume(curves, client->volumeSource(),
1938 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001939 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001940 outputDesc->devices().types(), 0 /*delay*/,
1941 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001942
1943 // update the outputs if starting an output with a stream that can affect notification
1944 // routing
1945 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001946
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001947 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001948 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001949 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1950 }
Eric Laurentdc462862016-07-19 12:29:53 -07001951
1952 if (waitMs > muteWaitMs) {
1953 *delayMs = waitMs - muteWaitMs;
1954 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001955
1956 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1957 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1958 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1959 // change occurs after the MixerThread starts and causes a stream volume
1960 // glitch.
1961 //
1962 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001963 }
Eric Laurentdc462862016-07-19 12:29:53 -07001964
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001965 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001966 mEngine->getForceUse(
1967 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001968 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001969 }
1970
Eric Laurent97ac8712018-07-27 18:59:02 -07001971 // Automatically enable the remote submix input when output is started on a re routing mix
1972 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001973 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1974 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001975 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1976 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1977 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001978 "remote-submix",
1979 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001980 }
1981
Eric Laurente552edb2014-03-10 17:42:56 -07001982 return NO_ERROR;
1983}
1984
Eric Laurent8fc147b2018-07-22 19:13:55 -07001985status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001986{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001987 ALOGV("%s portId %d", __FUNCTION__, portId);
1988
1989 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1990 if (outputDesc == 0) {
1991 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001992 return BAD_VALUE;
1993 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001994 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001995
Eric Laurent97ac8712018-07-27 18:59:02 -07001996 ALOGV("stopOutput() output %d, stream %d, session %d",
1997 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001998
Eric Laurent97ac8712018-07-27 18:59:02 -07001999 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002000
Eric Laurent733ce942017-12-07 12:18:25 -08002001 if (status == NO_ERROR ) {
2002 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002003 }
2004 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002005}
2006
Eric Laurent97ac8712018-07-27 18:59:02 -07002007status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2008 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002009{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002010 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002011 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002012 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002013
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002014 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2015
François Gaffie1c878552018-11-22 16:53:21 +01002016 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2017 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002018 // Automatically disable the remote submix input when output is stopped on a
2019 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002020 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002021 if (isSingleDeviceType(
2022 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002023 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002024 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002025 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2026 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002027 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002028 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002029 }
2030 }
2031 bool forceDeviceUpdate = false;
2032 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002033 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002034 forceDeviceUpdate = true;
2035 }
2036
Eric Laurente552edb2014-03-10 17:42:56 -07002037 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002038 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002039
Eric Laurente552edb2014-03-10 17:42:56 -07002040 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002041 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002042 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002043 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002044 // delay the device switch by twice the latency because stopOutput() is executed when
2045 // the track stop() command is received and at that time the audio track buffer can
2046 // still contain data that needs to be drained. The latency only covers the audio HAL
2047 // and kernel buffers. Also the latency does not always include additional delay in the
2048 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002049 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002050
2051 // force restoring the device selection on other active outputs if it differs from the
2052 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002053 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002054 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002056 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002057 desc->isActive() &&
2058 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002059 (newDevices != desc->devices())) {
2060 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2061 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002062
François Gaffie11d30102018-11-02 16:09:09 +01002063 setOutputDevices(desc, newDevices2, force, delayMs);
2064
Eric Laurent57de36c2016-09-28 16:59:11 -07002065 // re-apply device specific volume if not done by setOutputDevice()
2066 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002067 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002068 }
Eric Laurente552edb2014-03-10 17:42:56 -07002069 }
2070 }
2071 // update the outputs if stopping one with a stream that can affect notification routing
2072 handleNotificationRoutingForStream(stream);
2073 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002074
2075 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2076 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002077 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002078 }
2079
François Gaffiec005e562018-11-06 15:04:49 +01002080 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002081 selectOutputForMusicEffects();
2082 }
Eric Laurente552edb2014-03-10 17:42:56 -07002083 return NO_ERROR;
2084 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002085 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002086 return INVALID_OPERATION;
2087 }
2088}
2089
jiabinbce0c1d2020-10-05 11:20:18 -07002090bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002091{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002092 ALOGV("%s portId %d", __FUNCTION__, portId);
2093
2094 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2095 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002096 // If an output descriptor is closed due to a device routing change,
2097 // then there are race conditions with releaseOutput from tracks
2098 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2099 // destroyed shortly thereafter.
2100 //
2101 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002103 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002104 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002105
2106 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002107
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302108 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2109 if (outputDesc->isClientActive(client)) {
2110 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2111 stopOutput(portId);
2112 }
2113
Eric Laurent8fc147b2018-07-22 19:13:55 -07002114 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2115 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002116 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002117 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002118 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002119 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002120 if (--outputDesc->mDirectOpenCount == 0) {
2121 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002122 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002123 }
2124 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302125
Andy Hung39efb7a2018-09-26 15:39:28 -07002126 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002127 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2128 // The output is pending reopened to query dynamic profiles and
2129 // there is no active clients
2130 closeOutput(outputDesc->mIoHandle);
2131 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2132 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2133 if (newOutputDesc == nullptr) {
2134 ALOGE("%s failed to open output", __func__);
2135 }
2136 return true;
2137 }
2138 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002139}
2140
Eric Laurentcaf7f482014-11-25 17:50:47 -08002141status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2142 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002143 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002144 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002145 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002146 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002147 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002148 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002149 input_type_t *inputType,
2150 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002151{
François Gaffiec005e562018-11-06 15:04:49 +01002152 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2153 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2154 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002155
Eric Laurentad2e7b92017-09-14 20:06:42 -07002156 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002157 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002158 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002159 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002160 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002161 sp<AudioInputDescriptor> inputDesc;
2162 sp<RecordClientDescriptor> clientDesc;
2163 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002164 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002165 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002166
2167 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2168 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2169 return INVALID_OPERATION;
2170 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002171
Francois Gaffie716e1432019-01-14 16:58:59 +01002172 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2173 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002174 }
2175
Paul McLean466dc8e2015-04-17 13:15:36 -06002176 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002177 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002178 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002179
Eric Laurentad2e7b92017-09-14 20:06:42 -07002180 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2181 // possible
2182 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2183 *input != AUDIO_IO_HANDLE_NONE) {
2184 ssize_t index = mInputs.indexOfKey(*input);
2185 if (index < 0) {
2186 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2187 status = BAD_VALUE;
2188 goto error;
2189 }
2190 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002191 RecordClientVector clients = inputDesc->getClientsForSession(session);
2192 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002193 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2194 status = BAD_VALUE;
2195 goto error;
2196 }
2197 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2198 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002199 // corresponds to a new client and is only permitted from the same UID.
2200 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002201 if (clients.size() > 1) {
2202 for (const auto& client : clients) {
2203 // The client map is ordered by key values (portId) and portIds are allocated
2204 // incrementaly. So the first client in this list is the one opened by audio flinger
2205 // when the mmap stream is created and should be ignored as it does not correspond
2206 // to an actual client
2207 if (client == *clients.cbegin()) {
2208 continue;
2209 }
2210 if (uid != client->uid() && !client->isSilenced()) {
2211 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2212 uid, client->portId(), client->uid());
2213 status = INVALID_OPERATION;
2214 goto error;
2215 }
Eric Laurent331679c2018-04-16 17:03:16 -07002216 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002217 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002218 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002219 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002220
Eric Laurentfecbceb2021-02-09 14:46:43 +01002221 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002222 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002223 }
2224
2225 *input = AUDIO_IO_HANDLE_NONE;
2226 *inputType = API_INPUT_INVALID;
2227
Francois Gaffie716e1432019-01-14 16:58:59 +01002228 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002229
Francois Gaffie716e1432019-01-14 16:58:59 +01002230 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2231 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2232 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002233 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002234 ALOGW("%s could not find input mix for attr %s",
2235 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002236 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002237 }
jiabinc1de2df2019-05-07 14:26:40 -07002238 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2239 String8(attr->tags + strlen("addr=")),
2240 AUDIO_FORMAT_DEFAULT);
2241 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002242 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002243 __func__, attributes.source, attributes.tags);
2244 status = BAD_VALUE;
2245 goto error;
2246 }
2247
Kevin Rocard25f9b052019-02-27 15:08:54 -08002248 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2249 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2250 } else {
2251 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2252 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002253 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002254 if (explicitRoutingDevice != nullptr) {
2255 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002256 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002257 // Prevent from storing invalid requested device id in clients
2258 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002259 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002260 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2261 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002262 }
François Gaffie11d30102018-11-02 16:09:09 +01002263 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002264 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002265 status = BAD_VALUE;
2266 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002267 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002268 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2269 *inputType = API_INPUT_MIX_CAPTURE;
2270 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002271 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2272 // there is an external policy, but this input is attached to a mix of recorders,
2273 // meaning it receives audio injected into the framework, so the recorder doesn't
2274 // know about it and is therefore considered "legacy"
2275 *inputType = API_INPUT_LEGACY;
2276 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002277 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002278 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002279 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002280 } else {
2281 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002282 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002283
Eric Laurent599c7582015-12-07 18:05:55 -08002284 }
2285
François Gaffiec005e562018-11-06 15:04:49 +01002286 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002287 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002288 status = INVALID_OPERATION;
2289 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002290 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002291
Eric Laurent8f42ea12018-08-08 09:08:25 -07002292exit:
2293
François Gaffiec005e562018-11-06 15:04:49 +01002294 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2295 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002296
Francois Gaffie716e1432019-01-14 16:58:59 +01002297 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002298 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002299 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002300
Mikhail Naganov2996f672019-04-18 12:29:59 -07002301 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002302 requestedDeviceId, attributes.source, flags,
2303 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002304 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002305 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002306
2307 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2308 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002309
Eric Laurent599c7582015-12-07 18:05:55 -08002310 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002311
2312error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002313 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002314}
2315
2316
François Gaffie11d30102018-11-02 16:09:09 +01002317audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002318 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002319 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002320 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002321 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002322 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002323{
2324 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002325 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002326 bool isSoundTrigger = false;
2327
François Gaffiec005e562018-11-06 15:04:49 +01002328 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002329 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2330 if (index >= 0) {
2331 input = mSoundTriggerSessions.valueFor(session);
2332 isSoundTrigger = true;
2333 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2334 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2335 } else {
2336 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002337 }
François Gaffiec005e562018-11-06 15:04:49 +01002338 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002339 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002340 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002341 }
2342
Andy Hungf129b032015-04-07 13:45:50 -07002343 // find a compatible input profile (not necessarily identical in parameters)
2344 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002345 // sampling rate and flags may be updated by getInputProfile
2346 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2347 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002348 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002349 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002350 audio_input_flags_t profileFlags = flags;
2351 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002352 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002353 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002354 profileFlags);
2355 if (profile != 0) {
2356 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002357 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2358 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002359 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2360 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2361 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002362 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002363 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002364 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002365 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002366 }
Eric Laurente552edb2014-03-10 17:42:56 -07002367 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002368 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002369 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002370 if (samplingRate == 0) {
2371 samplingRate = profileSamplingRate;
2372 }
Eric Laurente552edb2014-03-10 17:42:56 -07002373
Eric Laurent322b4d22015-04-03 15:57:54 -07002374 if (profile->getModuleHandle() == 0) {
2375 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002376 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002377 }
2378
Eric Laurentec376dc2021-04-08 20:41:22 +02002379 // Reuse an already opened input if a client with the same session ID already exists
2380 // on that input
2381 for (size_t i = 0; i < mInputs.size(); i++) {
2382 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2383 if (desc->mProfile != profile) {
2384 continue;
2385 }
2386 RecordClientVector clients = desc->clientsList();
2387 for (const auto &client : clients) {
2388 if (session == client->session()) {
2389 return desc->mIoHandle;
2390 }
2391 }
2392 }
2393
Eric Laurent3974e3b2017-12-07 17:58:43 -08002394 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002395 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002396 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002397 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002398 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002399 continue;
2400 }
2401 // if sound trigger, reuse input if used by other sound trigger on same session
2402 // else
2403 // reuse input if active client app is not in IDLE state
2404 //
2405 RecordClientVector clients = desc->clientsList();
2406 bool doClose = false;
2407 for (const auto& client : clients) {
2408 if (isSoundTrigger != client->isSoundTrigger()) {
2409 continue;
2410 }
2411 if (client->isSoundTrigger()) {
2412 if (session == client->session()) {
2413 return desc->mIoHandle;
2414 }
2415 continue;
2416 }
2417 if (client->active() && client->appState() != APP_STATE_IDLE) {
2418 return desc->mIoHandle;
2419 }
2420 doClose = true;
2421 }
2422 if (doClose) {
2423 closeInput(desc->mIoHandle);
2424 } else {
2425 i++;
2426 }
2427 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002428 }
2429
Eric Laurentfe231122017-11-17 17:48:06 -08002430 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002431
Eric Laurentfe231122017-11-17 17:48:06 -08002432 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2433 lConfig.sample_rate = profileSamplingRate;
2434 lConfig.channel_mask = profileChannelMask;
2435 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002436
François Gaffie11d30102018-11-02 16:09:09 +01002437 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002438
2439 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002440 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002441 (profileSamplingRate != lConfig.sample_rate) ||
2442 !audio_formats_match(profileFormat, lConfig.format) ||
2443 (profileChannelMask != lConfig.channel_mask)) {
2444 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002445 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002446 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002447 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002448 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002449 }
Eric Laurent599c7582015-12-07 18:05:55 -08002450 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002451 }
2452
Eric Laurentc722f302014-12-10 11:21:49 -08002453 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002454
Eric Laurent599c7582015-12-07 18:05:55 -08002455 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002456 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002457
Eric Laurent599c7582015-12-07 18:05:55 -08002458 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002459}
2460
Eric Laurent4eb58f12018-12-07 16:41:02 -08002461status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002462{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002463 ALOGV("%s portId %d", __FUNCTION__, portId);
2464
2465 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2466 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002468 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002469 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002470 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002471 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002472 if (client->active()) {
2473 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2474 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002475 }
2476
Eric Laurent8f42ea12018-08-08 09:08:25 -07002477 audio_session_t session = client->session();
2478
Eric Laurent4eb58f12018-12-07 16:41:02 -08002479 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002480
Eric Laurent4eb58f12018-12-07 16:41:02 -08002481 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002482
Eric Laurent4eb58f12018-12-07 16:41:02 -08002483 status_t status = inputDesc->start();
2484 if (status != NO_ERROR) {
2485 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002486 }
Eric Laurente552edb2014-03-10 17:42:56 -07002487
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002488 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002489 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002491
Eric Laurent8f42ea12018-08-08 09:08:25 -07002492 // indicate active capture to sound trigger service if starting capture from a mic on
2493 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002494 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002495 if (device != nullptr) {
2496 status = setInputDevice(input, device, true /* force */);
2497 } else {
2498 ALOGW("%s no new input device can be found for descriptor %d",
2499 __FUNCTION__, inputDesc->getId());
2500 status = BAD_VALUE;
2501 }
Eric Laurente552edb2014-03-10 17:42:56 -07002502
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002503 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002504 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002505 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002506 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002507 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2508 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002509 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002510 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002511
François Gaffie11d30102018-11-02 16:09:09 +01002512 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2513 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002515 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002516 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002517
Eric Laurent8f42ea12018-08-08 09:08:25 -07002518 // automatically enable the remote submix output when input is started if not
2519 // used by a policy mix of type MIX_TYPE_RECORDERS
2520 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002521 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002522 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002523 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002525 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2526 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002527 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002528 if (address != "") {
2529 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2530 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002531 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002532 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002533 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002534 } else if (status != NO_ERROR) {
2535 // Restore client activity state.
2536 inputDesc->setClientActive(client, false);
2537 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002538 }
2539
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002540 ALOGV("%s input %d source = %d status = %d exit",
2541 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002542
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002543 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002544}
2545
Eric Laurent8fc147b2018-07-22 19:13:55 -07002546status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002547{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002548 ALOGV("%s portId %d", __FUNCTION__, portId);
2549
2550 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2551 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002553 return BAD_VALUE;
2554 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002555 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002556 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002557 if (!client->active()) {
2558 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002559 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002560 }
Carter Hsue6139d52021-07-08 10:30:20 +08002561 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002562 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002563
Eric Laurent8f42ea12018-08-08 09:08:25 -07002564 inputDesc->stop();
2565 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002566 auto current_source = inputDesc->source();
2567 setInputDevice(input, getNewInputDevice(inputDesc),
2568 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002569 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002570 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002571 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002572 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002573 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2574 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002575 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002576 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002577
2578 // automatically disable the remote submix output when input is stopped if not
2579 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002580 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002581 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002582 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002583 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002584 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2585 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586 }
2587 if (address != "") {
2588 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2589 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002590 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002591 }
2592 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 resetInputDevice(input);
2594
2595 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2596 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002597 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2598 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002599 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002600 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601 }
2602 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002603 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002604 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002605}
2606
Eric Laurent8fc147b2018-07-22 19:13:55 -07002607void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002608{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002609 ALOGV("%s portId %d", __FUNCTION__, portId);
2610
2611 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2612 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002614 return;
2615 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002616 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002617 audio_io_handle_t input = inputDesc->mIoHandle;
2618
Eric Laurent8f42ea12018-08-08 09:08:25 -07002619 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002620
Andy Hung39efb7a2018-09-26 15:39:28 -07002621 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002622
Andy Hung39efb7a2018-09-26 15:39:28 -07002623 if (inputDesc->getClientCount() > 0) {
2624 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002625 return;
2626 }
2627
Eric Laurent05b90f82014-08-27 15:32:29 -07002628 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002629 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002631}
2632
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002635 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636
2637 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002638 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002639 }
2640}
2641
Eric Laurent8f42ea12018-08-08 09:08:25 -07002642void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2643{
2644 stopInput(portId);
2645 releaseInput(portId);
2646}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647
Eric Laurent0dd51852019-04-19 18:18:58 -07002648void AudioPolicyManager::checkCloseInputs() {
2649 // After connecting or disconnecting an input device, close input if:
2650 // - it has no client (was just opened to check profile) OR
2651 // - none of its supported devices are connected anymore OR
2652 // - one of its clients cannot be routed to one of its supported
2653 // devices anymore. Otherwise update device selection
2654 std::vector<audio_io_handle_t> inputsToClose;
2655 for (size_t i = 0; i < mInputs.size(); i++) {
2656 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2657 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002658 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002659 inputsToClose.push_back(mInputs.keyAt(i));
2660 } else {
2661 bool close = false;
2662 for (const auto& client : input->clientsList()) {
2663 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002664 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002665 if (!input->supportedDevices().contains(device)) {
2666 close = true;
2667 break;
2668 }
2669 }
2670 if (close) {
2671 inputsToClose.push_back(mInputs.keyAt(i));
2672 } else {
2673 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2674 }
2675 }
2676 }
2677
2678 for (const audio_io_handle_t handle : inputsToClose) {
2679 ALOGV("%s closing input %d", __func__, handle);
2680 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002681 }
Eric Laurentd4692962014-05-05 18:13:44 -07002682}
2683
François Gaffie251c7f02018-11-07 10:41:08 +01002684void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002685{
2686 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002687 if (indexMin < 0 || indexMax < 0) {
2688 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2689 return;
2690 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002691 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002692
2693 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002694 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2695 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002696 continue;
2697 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002698 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002699 }
Eric Laurente552edb2014-03-10 17:42:56 -07002700}
2701
Eric Laurente0720872014-03-11 09:30:41 -07002702status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002703 int index,
2704 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002705{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002706 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002707 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2708 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2709 return NO_ERROR;
2710 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002711 ALOGV("%s: stream %s attributes=%s", __func__,
2712 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002713 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002714}
2715
Eric Laurente0720872014-03-11 09:30:41 -07002716status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002717 int *index,
2718 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002719{
François Gaffiec005e562018-11-06 15:04:49 +01002720 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2721 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002722 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002723 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002724 deviceTypes = mEngine->getOutputDevicesForStream(
2725 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002726 }
jiabin9a3361e2019-10-01 09:38:30 -07002727 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002728}
2729
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002730status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002731 int index,
2732 audio_devices_t device)
2733{
2734 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002735 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2736 if (group == VOLUME_GROUP_NONE) {
2737 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002738 return BAD_VALUE;
2739 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002740 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002741 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002742 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002743 VolumeSource vs = toVolumeSource(group);
2744 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2745
2746 status = setVolumeCurveIndex(index, device, curves);
2747 if (status != NO_ERROR) {
2748 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2749 return status;
2750 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002751
jiabin9a3361e2019-10-01 09:38:30 -07002752 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002753 auto curCurvAttrs = curves.getAttributes();
2754 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2755 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002756 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002757 } else if (!curves.getStreamTypes().empty()) {
2758 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002759 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002760 } else {
2761 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2762 return BAD_VALUE;
2763 }
jiabin9a3361e2019-10-01 09:38:30 -07002764 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2765 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002766
François Gaffiecfe17322018-11-07 13:41:29 +01002767 // update volume on all outputs and streams matching the following:
2768 // - The requested stream (or a stream matching for volume control) is active on the output
2769 // - The device (or devices) selected by the engine for this stream includes
2770 // the requested device
2771 // - For non default requested device, currently selected device on the output is either the
2772 // requested device or one of the devices selected by the engine for this stream
2773 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2774 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002775 for (size_t i = 0; i < mOutputs.size(); i++) {
2776 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002777 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002778
jiabin9a3361e2019-10-01 09:38:30 -07002779 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2780 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002781 }
François Gaffieed91f582020-01-31 10:35:37 +01002782 if (!(desc->isActive(vs) || isInCall())) {
2783 continue;
2784 }
2785 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2786 curDevices.find(device) == curDevices.end()) {
2787 continue;
2788 }
2789 bool applyVolume = false;
2790 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2791 curSrcDevices.insert(device);
2792 applyVolume = (curSrcDevices.find(
2793 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2794 } else {
2795 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2796 }
2797 if (!applyVolume) {
2798 continue; // next output
2799 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002800 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2801 // If a higher priority strategy is active, and the output is routed to a device with a
2802 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002803 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002804 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002805 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2806 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2807 false /*preferredDevice*/);
2808 if (activeClients.empty()) {
2809 continue;
2810 }
2811 bool isPreempted = false;
2812 bool isHigherPriority = productStrategy < strategy;
2813 for (const auto &client : activeClients) {
2814 if (isHigherPriority && (client->volumeSource() != vs)) {
2815 ALOGV("%s: Strategy=%d (\nrequester:\n"
2816 " group %d, volumeGroup=%d attributes=%s)\n"
2817 " higher priority source active:\n"
2818 " volumeGroup=%d attributes=%s) \n"
2819 " on output %zu, bailing out", __func__, productStrategy,
2820 group, group, toString(attributes).c_str(),
2821 client->volumeSource(), toString(client->attributes()).c_str(), i);
2822 applyVolume = false;
2823 isPreempted = true;
2824 break;
2825 }
2826 // However, continue for loop to ensure no higher prio clients running on output
2827 if (client->volumeSource() == vs) {
2828 applyVolume = true;
2829 }
2830 }
2831 if (isPreempted || applyVolume) {
2832 break;
2833 }
2834 }
2835 if (!applyVolume) {
2836 continue; // next output
2837 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002838 }
François Gaffieed91f582020-01-31 10:35:37 +01002839 //FIXME: workaround for truncated touch sounds
2840 // delayed volume change for system stream to be removed when the problem is
2841 // handled by system UI
2842 status_t volStatus = checkAndSetVolume(
2843 curves, vs, index, desc, curDevices,
2844 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2845 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2846 if (volStatus != NO_ERROR) {
2847 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002848 }
2849 }
François Gaffiecfe17322018-11-07 13:41:29 +01002850 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2851 return status;
2852}
2853
François Gaffieaaac0fd2018-11-22 17:56:39 +01002854status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002855 audio_devices_t device,
2856 IVolumeCurves &volumeCurves)
2857{
2858 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2859 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002860 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2861 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002862 (index > volumeCurves.getVolumeIndexMax())) {
2863 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2864 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2865 return BAD_VALUE;
2866 }
2867 if (!audio_is_output_device(device)) {
2868 return BAD_VALUE;
2869 }
2870
2871 // Force max volume if stream cannot be muted
2872 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2873
François Gaffieaaac0fd2018-11-22 17:56:39 +01002874 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002875 volumeCurves.addCurrentVolumeIndex(device, index);
2876 return NO_ERROR;
2877}
2878
2879status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2880 int &index,
2881 audio_devices_t device)
2882{
2883 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2884 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002885 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002886 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002887 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2888 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002889 }
jiabin9a3361e2019-10-01 09:38:30 -07002890 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002891}
2892
2893status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2894 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002895 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002896{
jiabin9a3361e2019-10-01 09:38:30 -07002897 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002898 return BAD_VALUE;
2899 }
jiabin9a3361e2019-10-01 09:38:30 -07002900 index = curves.getVolumeIndex(deviceTypes);
2901 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002902 return NO_ERROR;
2903}
2904
2905status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2906 int &index)
2907{
2908 index = getVolumeCurves(attr).getVolumeIndexMin();
2909 return NO_ERROR;
2910}
2911
2912status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2913 int &index)
2914{
2915 index = getVolumeCurves(attr).getVolumeIndexMax();
2916 return NO_ERROR;
2917}
2918
Eric Laurent36829f92017-04-07 19:04:42 -07002919audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002920{
2921 // select one output among several suitable for global effects.
2922 // The priority is as follows:
2923 // 1: An offloaded output. If the effect ends up not being offloadable,
2924 // AudioFlinger will invalidate the track and the offloaded output
2925 // will be closed causing the effect to be moved to a PCM output.
2926 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002927 // 3: The primary output
2928 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002929
François Gaffiec005e562018-11-06 15:04:49 +01002930 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2931 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002932 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002933
Eric Laurent36829f92017-04-07 19:04:42 -07002934 if (outputs.size() == 0) {
2935 return AUDIO_IO_HANDLE_NONE;
2936 }
Eric Laurente552edb2014-03-10 17:42:56 -07002937
Eric Laurent36829f92017-04-07 19:04:42 -07002938 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2939 bool activeOnly = true;
2940
2941 while (output == AUDIO_IO_HANDLE_NONE) {
2942 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2943 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2944 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2945
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002946 for (audio_io_handle_t output : outputs) {
2947 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002948 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002949 continue;
2950 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002951 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2952 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002953 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002954 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002955 }
2956 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002957 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002958 }
2959 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002960 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002961 }
2962 }
2963 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2964 output = outputOffloaded;
2965 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2966 output = outputDeepBuffer;
2967 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2968 output = outputPrimary;
2969 } else {
2970 output = outputs[0];
2971 }
2972 activeOnly = false;
2973 }
2974
2975 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002976 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002977 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2978 mMusicEffectOutput = output;
2979 }
2980
2981 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002982 return output;
2983}
2984
Eric Laurent36829f92017-04-07 19:04:42 -07002985audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2986{
2987 return selectOutputForMusicEffects();
2988}
2989
Eric Laurente0720872014-03-11 09:30:41 -07002990status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002991 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002992 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002993 int session,
2994 int id)
2995{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002996 if (session != AUDIO_SESSION_DEVICE) {
2997 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002999 index = mInputs.indexOfKey(io);
3000 if (index < 0) {
3001 ALOGW("registerEffect() unknown io %d", io);
3002 return INVALID_OPERATION;
3003 }
Eric Laurente552edb2014-03-10 17:42:56 -07003004 }
3005 }
François Gaffiec005e562018-11-06 15:04:49 +01003006 return mEffects.registerEffect(desc, io, session, id,
3007 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3008 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003009}
3010
Eric Laurentc241b0d2018-11-28 09:08:49 -08003011status_t AudioPolicyManager::unregisterEffect(int id)
3012{
3013 if (mEffects.getEffect(id) == nullptr) {
3014 return INVALID_OPERATION;
3015 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003016 if (mEffects.isEffectEnabled(id)) {
3017 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3018 setEffectEnabled(id, false);
3019 }
3020 return mEffects.unregisterEffect(id);
3021}
3022
3023status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3024{
3025 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3026 if (effect == nullptr) {
3027 return INVALID_OPERATION;
3028 }
3029
3030 status_t status = mEffects.setEffectEnabled(id, enabled);
3031 if (status == NO_ERROR) {
3032 mInputs.trackEffectEnabled(effect, enabled);
3033 }
3034 return status;
3035}
3036
Eric Laurent6c796322019-04-09 14:13:17 -07003037
3038status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3039{
3040 mEffects.moveEffects(ids, io);
3041 return NO_ERROR;
3042}
3043
Eric Laurentc75307b2015-03-17 15:29:32 -07003044bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3045{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003046 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003047}
3048
3049bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3050{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003051 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003052}
3053
Eric Laurente0720872014-03-11 09:30:41 -07003054bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003055{
3056 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003057 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003058 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003059 return true;
3060 }
3061 }
3062 return false;
3063}
3064
Eric Laurent275e8e92014-11-30 15:14:47 -08003065// Register a list of custom mixes with their attributes and format.
3066// When a mix is registered, corresponding input and output profiles are
3067// added to the remote submix hw module. The profile contains only the
3068// parameters (sampling rate, format...) specified by the mix.
3069// The corresponding input remote submix device is also connected.
3070//
3071// When a remote submix device is connected, the address is checked to select the
3072// appropriate profile and the corresponding input or output stream is opened.
3073//
3074// When capture starts, getInputForAttr() will:
3075// - 1 look for a mix matching the address passed in attribtutes tags if any
3076// - 2 if none found, getDeviceForInputSource() will:
3077// - 2.1 look for a mix matching the attributes source
3078// - 2.2 if none found, default to device selection by policy rules
3079// At this time, the corresponding output remote submix device is also connected
3080// and active playback use cases can be transferred to this mix if needed when reconnecting
3081// after AudioTracks are invalidated
3082//
3083// When playback starts, getOutputForAttr() will:
3084// - 1 look for a mix matching the address passed in attribtutes tags if any
3085// - 2 if none found, look for a mix matching the attributes usage
3086// - 3 if none found, default to device and output selection by policy rules.
3087
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003088status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003089{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003090 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3091 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003092 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003093 sp<HwModule> rSubmixModule;
3094 // examine each mix's route type
3095 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003096 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003097 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3098 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3099 ALOGE("Unsupported Policy Mix %zu of %zu: "
3100 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3101 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003102 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003103 break;
3104 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003105 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3106 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003107 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003108 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3109 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003110 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003111 rSubmixModule = mHwModules.getModuleFromName(
3112 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3113 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003114 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003115 i);
3116 res = INVALID_OPERATION;
3117 break;
3118 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003119 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003120
Eric Laurent97ac8712018-07-27 18:59:02 -07003121 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003122 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003123 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003124 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003125 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3126 } else {
3127 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3128 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003129 }
François Gaffie036e1e92015-03-19 10:16:24 +01003130
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003131 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003132 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003133 res = INVALID_OPERATION;
3134 break;
3135 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003136 audio_config_t outputConfig = mix.mFormat;
3137 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003138 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3139 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003140 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3141 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003142 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003143 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003144 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003145 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003146
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003147 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003148 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3149 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3150 ALOGE("Failed to set remote submix device available, type %u, address %s",
3151 mix.mDeviceType, address.string());
3152 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003153 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003154 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3155 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003156 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003157 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003158 i, mixes.size(), type, address.string());
3159
3160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3161 mix.mDeviceType, mix.mDeviceAddress,
3162 String8(), AUDIO_FORMAT_DEFAULT);
3163 if (device == nullptr) {
3164 res = INVALID_OPERATION;
3165 break;
3166 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003167
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003168 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003169 // First try to find an already opened output supporting the device
3170 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003172
Eric Laurentc529cf62020-04-17 18:19:10 -07003173 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003174 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003175 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3176 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003177 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003178 } else {
3179 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003180 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003181 }
3182 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003183 // If no output found, try to find a direct output profile supporting the device
3184 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3185 sp<HwModule> module = mHwModules[i];
3186 for (size_t j = 0;
3187 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3188 j++) {
3189 sp<IOProfile> profile = module->getOutputProfiles()[j];
3190 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3191 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3192 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3193 address.string());
3194 res = INVALID_OPERATION;
3195 } else {
3196 foundOutput = true;
3197 }
3198 }
3199 }
3200 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003201 if (res != NO_ERROR) {
3202 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003203 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003204 res = INVALID_OPERATION;
3205 break;
3206 } else if (!foundOutput) {
3207 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003208 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003209 res = INVALID_OPERATION;
3210 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003211 } else {
3212 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003213 }
Eric Laurentc722f302014-12-10 11:21:49 -08003214 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003215 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003216 if (res != NO_ERROR) {
3217 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003218 } else if (checkOutputs) {
3219 checkForDeviceAndOutputChanges();
3220 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003221 }
3222 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003223}
3224
3225status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3226{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003227 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003228 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003229 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003230 sp<HwModule> rSubmixModule;
3231 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003232 for (const auto& mix : mixes) {
3233 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003234
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003236 rSubmixModule = mHwModules.getModuleFromName(
3237 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3238 if (rSubmixModule == 0) {
3239 res = INVALID_OPERATION;
3240 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003241 }
3242 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003243
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003244 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003245
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003246 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003247 res = INVALID_OPERATION;
3248 continue;
3249 }
3250
Kevin Rocard04ed0462019-05-02 17:53:24 -07003251 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3252 if (getDeviceConnectionState(device, address.string()) ==
3253 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3254 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3255 address.string(), "remote-submix",
3256 AUDIO_FORMAT_DEFAULT);
3257 if (res != OK) {
3258 ALOGE("Error making RemoteSubmix device unavailable for mix "
3259 "with type %d, address %s", device, address.string());
3260 }
3261 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003262 }
jiabin5740f082019-08-19 15:08:30 -07003263 rSubmixModule->removeOutputProfile(address.c_str());
3264 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265
Kevin Rocard153f92d2018-12-18 18:33:28 -08003266 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003267 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268 res = INVALID_OPERATION;
3269 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003270 } else {
3271 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003272 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003273 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003274 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003275 if (res == NO_ERROR && checkOutputs) {
3276 checkForDeviceAndOutputChanges();
3277 updateCallAndOutputRouting();
3278 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003279 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003280}
3281
Mikhail Naganov100f0122018-11-29 11:22:16 -08003282void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3283{
3284 size_t i = 0;
3285 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3286 for (const auto& fmt : mManualSurroundFormats) {
3287 if (i++ != 0) dst->append(", ");
3288 std::string sfmt;
3289 FormatConverter::toString(fmt, sfmt);
3290 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3291 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3292 }
3293}
3294
Eric Laurentc529cf62020-04-17 18:19:10 -07003295// Returns true if all devices types match the predicate and are supported by one HW module
3296bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003297 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003298 std::function<bool(audio_devices_t)> predicate,
3299 const char *context) {
3300 for (size_t i = 0; i < devices.size(); i++) {
3301 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003302 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003303 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003304 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003305 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003306 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003307 return false;
3308 }
3309 }
3310 return true;
3311}
3312
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003313status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003314 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003315 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003316 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3317 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003318 }
3319 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003320 if (res != NO_ERROR) {
3321 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3322 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003323 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003324
3325 checkForDeviceAndOutputChanges();
3326 updateCallAndOutputRouting();
3327
3328 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003329}
3330
3331status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3332 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003333 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3334 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003335 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003336 __FUNCTION__, uid);
3337 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003338 }
3339
Eric Laurentc529cf62020-04-17 18:19:10 -07003340 checkForDeviceAndOutputChanges();
3341 updateCallAndOutputRouting();
3342
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003343 return res;
3344}
3345
Eric Laurent2517af32020-11-25 15:31:27 +01003346
jiabin0a488932020-08-07 17:32:40 -07003347status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3348 device_role_t role,
3349 const AudioDeviceTypeAddrVector &devices) {
3350 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3351 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003352
Eric Laurentc529cf62020-04-17 18:19:10 -07003353 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003354 return BAD_VALUE;
3355 }
jiabin0a488932020-08-07 17:32:40 -07003356 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003357 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003358 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3359 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003360 return status;
3361 }
3362
3363 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003364
3365 bool forceVolumeReeval = false;
3366 // FIXME: workaround for truncated touch sounds
3367 // to be removed when the problem is handled by system UI
3368 uint32_t delayMs = 0;
3369 if (strategy == mCommunnicationStrategy) {
3370 forceVolumeReeval = true;
3371 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3372 updateInputRouting();
3373 }
3374 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003375
3376 return NO_ERROR;
3377}
3378
3379void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3380{
3381 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003382 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003383 // Only apply special touch sound delay once
3384 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003385 }
3386 for (size_t i = 0; i < mOutputs.size(); i++) {
3387 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3388 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3389 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3390 // As done in setDeviceConnectionState, we could also fix default device issue by
3391 // preventing the force re-routing in case of default dev that distinguishes on address.
3392 // Let's give back to engine full device choice decision however.
3393 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003394 // Only apply special touch sound delay once
3395 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003396 }
3397 if (forceVolumeReeval && !newDevices.isEmpty()) {
3398 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3399 }
3400 }
3401}
3402
Eric Laurent2517af32020-11-25 15:31:27 +01003403void AudioPolicyManager::updateInputRouting() {
3404 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303405 // Skip for hotword recording as the input device switch
3406 // is handled within sound trigger HAL
3407 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3408 continue;
3409 }
Eric Laurent2517af32020-11-25 15:31:27 +01003410 auto newDevice = getNewInputDevice(activeDesc);
3411 // Force new input selection if the new device can not be reached via current input
3412 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3413 setInputDevice(activeDesc->mIoHandle, newDevice);
3414 } else {
3415 closeInput(activeDesc->mIoHandle);
3416 }
3417 }
3418}
3419
jiabin0a488932020-08-07 17:32:40 -07003420status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3421 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003422{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003423 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003424
jiabin0a488932020-08-07 17:32:40 -07003425 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003426 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003427 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3428 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003429 return status;
3430 }
3431
3432 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003433
3434 bool forceVolumeReeval = false;
3435 // FIXME: workaround for truncated touch sounds
3436 // to be removed when the problem is handled by system UI
3437 uint32_t delayMs = 0;
3438 if (strategy == mCommunnicationStrategy) {
3439 forceVolumeReeval = true;
3440 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3441 updateInputRouting();
3442 }
3443 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003444
3445 return NO_ERROR;
3446}
3447
jiabin0a488932020-08-07 17:32:40 -07003448status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3449 device_role_t role,
3450 AudioDeviceTypeAddrVector &devices) {
3451 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003452}
3453
Jiabin Huang3b98d322020-09-03 17:54:16 +00003454status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3455 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3456 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3457 dumpAudioDeviceTypeAddrVector(devices).c_str());
3458
Mikhail Naganov55773032020-10-01 15:08:13 -07003459 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003460 return BAD_VALUE;
3461 }
3462 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3463 ALOGW_IF(status != NO_ERROR,
3464 "Engine could not set preferred devices %s for audio source %d role %d",
3465 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3466
3467 return status;
3468}
3469
3470status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3471 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3472 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3473 dumpAudioDeviceTypeAddrVector(devices).c_str());
3474
Mikhail Naganov55773032020-10-01 15:08:13 -07003475 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003476 return BAD_VALUE;
3477 }
3478 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3479 ALOGW_IF(status != NO_ERROR,
3480 "Engine could not add preferred devices %s for audio source %d role %d",
3481 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3482
Eric Laurent2517af32020-11-25 15:31:27 +01003483 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003484 return status;
3485}
3486
3487status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3488 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3489{
3490 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3491 dumpAudioDeviceTypeAddrVector(devices).c_str());
3492
Mikhail Naganov55773032020-10-01 15:08:13 -07003493 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003494 return BAD_VALUE;
3495 }
3496
3497 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3498 audioSource, role, devices);
3499 ALOGW_IF(status != NO_ERROR,
3500 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3501
Eric Laurent2517af32020-11-25 15:31:27 +01003502 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003503 return status;
3504}
3505
3506status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3507 device_role_t role) {
3508 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3509
3510 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3511 ALOGW_IF(status != NO_ERROR,
3512 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3513
Eric Laurent2517af32020-11-25 15:31:27 +01003514 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003515 return status;
3516}
3517
3518status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3519 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3520 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3521}
3522
Oscar Azucena90e77632019-11-27 17:12:28 -08003523status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003524 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003525 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003526 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3527 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003528 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003529 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3530 if (status != NO_ERROR) {
3531 ALOGE("%s() could not set device affinity for userId %d",
3532 __FUNCTION__, userId);
3533 return status;
3534 }
3535
3536 // reevaluate outputs for all devices
3537 checkForDeviceAndOutputChanges();
3538 updateCallAndOutputRouting();
3539
3540 return NO_ERROR;
3541}
3542
3543status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003544 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003545 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3546 if (status != NO_ERROR) {
3547 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3548 __FUNCTION__, userId);
3549 return status;
3550 }
3551
3552 // reevaluate outputs for all devices
3553 checkForDeviceAndOutputChanges();
3554 updateCallAndOutputRouting();
3555
3556 return NO_ERROR;
3557}
3558
Andy Hungc29d82b2018-10-05 12:23:17 -07003559void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003560{
Andy Hungc29d82b2018-10-05 12:23:17 -07003561 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3562 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003563 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003564 std::string stateLiteral;
3565 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003566 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003567 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3568 "communications", "media", "record", "dock", "system",
3569 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3570 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3571 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003572 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3573 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3574 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3575 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3576 dst->append(" (MANUAL: ");
3577 dumpManualSurroundFormats(dst);
3578 dst->append(")");
3579 }
3580 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003581 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003582 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3583 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003584 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003585 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003586
Andy Hungc29d82b2018-10-05 12:23:17 -07003587 mAvailableOutputDevices.dump(dst, String8("Available output"));
3588 mAvailableInputDevices.dump(dst, String8("Available input"));
3589 mHwModulesAll.dump(dst);
3590 mOutputs.dump(dst);
3591 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003592 mEffects.dump(dst);
3593 mAudioPatches.dump(dst);
3594 mPolicyMixes.dump(dst);
3595 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003596
Kevin Rocardb99cc752019-03-21 20:52:24 -07003597 dst->appendFormat(" AllowedCapturePolicies:\n");
3598 for (auto& policy : mAllowedCapturePolicies) {
3599 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3600 }
3601
François Gaffiec005e562018-11-06 15:04:49 +01003602 dst->appendFormat("\nPolicy Engine dump:\n");
3603 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003604}
3605
3606status_t AudioPolicyManager::dump(int fd)
3607{
3608 String8 result;
3609 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003610 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003611 return NO_ERROR;
3612}
3613
Kevin Rocardb99cc752019-03-21 20:52:24 -07003614status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3615{
3616 mAllowedCapturePolicies[uid] = capturePolicy;
3617 return NO_ERROR;
3618}
3619
Eric Laurente552edb2014-03-10 17:42:56 -07003620// This function checks for the parameters which can be offloaded.
3621// This can be enhanced depending on the capability of the DSP and policy
3622// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003623audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003624{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003625 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003626 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003627 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003628 offloadInfo.format,
3629 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3630 offloadInfo.has_video);
3631
Andy Hung2ddee192015-12-18 17:34:44 -08003632 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003633 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003634 }
3635
Eric Laurente552edb2014-03-10 17:42:56 -07003636 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003637 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003638 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3639 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003640 }
3641
3642 // Check if stream type is music, then only allow offload as of now.
3643 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3644 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003645 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3646 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003647 }
3648
3649 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003650 const bool allowOffloadWithVideo =
3651 property_get_bool("audio.offload.video", false /* default_value */);
3652 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003653 ALOGV("%s: has_video == true, returning false", __func__);
3654 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003655 }
3656
3657 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003658 const int min_duration_secs = property_get_int32(
3659 "audio.offload.min.duration.secs", -1 /* default_value */);
3660 if (min_duration_secs >= 0) {
3661 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003662 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3663 __func__, min_duration_secs);
3664 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003665 }
3666 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003667 ALOGV("%s: Offload denied by duration < default min(=%u)",
3668 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3669 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003670 }
3671
3672 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3673 // creating an offloaded track and tearing it down immediately after start when audioflinger
3674 // detects there is an active non offloadable effect.
3675 // FIXME: We should check the audio session here but we do not have it in this context.
3676 // This may prevent offloading in rare situations where effects are left active by apps
3677 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003678 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003679 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003680 }
3681
3682 // See if there is a profile to support this.
3683 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003684 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003685 offloadInfo.sample_rate,
3686 offloadInfo.format,
3687 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003688 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3689 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003690 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3691 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3692 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003693 if (profile == nullptr) {
3694 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3695 }
3696 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3697 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3698 }
3699 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003700}
3701
Michael Chana94fbb22018-04-24 14:31:19 +10003702bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3703 const audio_attributes_t& attributes) {
3704 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003705 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003706 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003707 config.sample_rate,
3708 config.format,
3709 config.channel_mask,
3710 output_flags,
3711 true /* directOnly */);
3712 ALOGV("%s() profile %sfound with name: %s, "
3713 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3714 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003715 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003716 config.sample_rate, config.format, config.channel_mask, output_flags);
3717 return (profile != 0);
3718}
3719
Eric Laurent6a94d692014-05-20 11:18:06 -07003720status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3721 audio_port_type_t type,
3722 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003723 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 unsigned int *generation)
3725{
jiabin19cdba52020-11-24 11:28:58 -08003726 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3727 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003728 return BAD_VALUE;
3729 }
3730 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003731 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003732 *num_ports = 0;
3733 }
3734
3735 size_t portsWritten = 0;
3736 size_t portsMax = *num_ports;
3737 *num_ports = 0;
3738 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003739 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3740 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003741 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003742 for (const auto& dev : mAvailableOutputDevices) {
3743 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003744 continue;
3745 }
3746 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003747 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003748 }
3749 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003751 }
3752 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003753 for (const auto& dev : mAvailableInputDevices) {
3754 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003755 continue;
3756 }
3757 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003758 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003759 }
3760 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003761 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003762 }
3763 }
3764 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3765 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3766 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3767 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3768 }
3769 *num_ports += mInputs.size();
3770 }
3771 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003772 size_t numOutputs = 0;
3773 for (size_t i = 0; i < mOutputs.size(); i++) {
3774 if (!mOutputs[i]->isDuplicated()) {
3775 numOutputs++;
3776 if (portsWritten < portsMax) {
3777 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3778 }
3779 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003780 }
Eric Laurent84c70242014-06-23 08:46:27 -07003781 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003782 }
3783 }
3784 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003785 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003786 return NO_ERROR;
3787}
3788
jiabin19cdba52020-11-24 11:28:58 -08003789status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003790{
Eric Laurent99fcae42018-05-17 16:59:18 -07003791 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3792 return BAD_VALUE;
3793 }
3794 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3795 if (dev != 0) {
3796 dev->toAudioPort(port);
3797 return NO_ERROR;
3798 }
3799 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3800 if (dev != 0) {
3801 dev->toAudioPort(port);
3802 return NO_ERROR;
3803 }
3804 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3805 if (out != 0) {
3806 out->toAudioPort(port);
3807 return NO_ERROR;
3808 }
3809 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3810 if (in != 0) {
3811 in->toAudioPort(port);
3812 return NO_ERROR;
3813 }
3814 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003815}
3816
François Gaffieafd4cea2019-11-18 15:50:22 +01003817status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3818 audio_patch_handle_t *handle,
3819 uid_t uid, uint32_t delayMs,
3820 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003821{
François Gaffieafd4cea2019-11-18 15:50:22 +01003822 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 if (handle == NULL || patch == NULL) {
3824 return BAD_VALUE;
3825 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003826 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003827
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003828 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003829 return BAD_VALUE;
3830 }
3831 // only one source per audio patch supported for now
3832 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003833 return INVALID_OPERATION;
3834 }
Eric Laurent874c42872014-08-08 15:13:39 -07003835
3836 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003837 return INVALID_OPERATION;
3838 }
Eric Laurent874c42872014-08-08 15:13:39 -07003839 for (size_t i = 0; i < patch->num_sinks; i++) {
3840 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3841 return INVALID_OPERATION;
3842 }
3843 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003844
3845 sp<AudioPatch> patchDesc;
3846 ssize_t index = mAudioPatches.indexOfKey(*handle);
3847
François Gaffieafd4cea2019-11-18 15:50:22 +01003848 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3849 patch->sources[0].role,
3850 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003851#if LOG_NDEBUG == 0
3852 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003853 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3854 patch->sinks[i].role,
3855 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003856 }
3857#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003858
3859 if (index >= 0) {
3860 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003861 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3862 __func__, mUidCached, patchDesc->getUid(), uid);
3863 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 return INVALID_OPERATION;
3865 }
3866 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003867 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003868 }
3869
3870 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003871 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003872 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003873 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003874 return BAD_VALUE;
3875 }
Eric Laurent84c70242014-06-23 08:46:27 -07003876 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3877 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003878 if (patchDesc != 0) {
3879 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003880 ALOGV("%s source id differs for patch current id %d new id %d",
3881 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003882 return BAD_VALUE;
3883 }
3884 }
Eric Laurent874c42872014-08-08 15:13:39 -07003885 DeviceVector devices;
3886 for (size_t i = 0; i < patch->num_sinks; i++) {
3887 // Only support mix to devices connection
3888 // TODO add support for mix to mix connection
3889 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003890 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003891 return INVALID_OPERATION;
3892 }
3893 sp<DeviceDescriptor> devDesc =
3894 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3895 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003896 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003897 return BAD_VALUE;
3898 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003899
François Gaffie11d30102018-11-02 16:09:09 +01003900 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003901 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003902 NULL, // updatedSamplingRate
3903 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003904 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003905 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003906 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003907 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003908 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003909 return INVALID_OPERATION;
3910 }
3911 devices.add(devDesc);
3912 }
3913 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003914 return INVALID_OPERATION;
3915 }
Eric Laurent874c42872014-08-08 15:13:39 -07003916
Eric Laurent6a94d692014-05-20 11:18:06 -07003917 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003918 ALOGV("%s setting device %s on output %d",
3919 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003920 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003921 index = mAudioPatches.indexOfKey(*handle);
3922 if (index >= 0) {
3923 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003924 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003925 }
3926 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003927 patchDesc->setUid(uid);
3928 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003929 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003930 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003931 return INVALID_OPERATION;
3932 }
3933 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3934 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3935 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003936 // only one sink supported when connecting an input device to a mix
3937 if (patch->num_sinks > 1) {
3938 return INVALID_OPERATION;
3939 }
François Gaffie53615e22015-03-19 09:24:12 +01003940 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003941 if (inputDesc == NULL) {
3942 return BAD_VALUE;
3943 }
3944 if (patchDesc != 0) {
3945 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3946 return BAD_VALUE;
3947 }
3948 }
François Gaffie11d30102018-11-02 16:09:09 +01003949 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003950 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003951 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003952 return BAD_VALUE;
3953 }
3954
François Gaffie11d30102018-11-02 16:09:09 +01003955 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003956 patch->sinks[0].sample_rate,
3957 NULL, /*updatedSampleRate*/
3958 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003959 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003960 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003961 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003962 // FIXME for the parameter type,
3963 // and the NONE
3964 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003965 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 return INVALID_OPERATION;
3967 }
3968 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003969 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003970 device->toString().c_str(), inputDesc->mIoHandle);
3971 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 index = mAudioPatches.indexOfKey(*handle);
3973 if (index >= 0) {
3974 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003975 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 }
3977 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003978 patchDesc->setUid(uid);
3979 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003981 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003982 return INVALID_OPERATION;
3983 }
3984 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3985 // device to device connection
3986 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003987 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 return BAD_VALUE;
3989 }
3990 }
François Gaffie11d30102018-11-02 16:09:09 +01003991 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003992 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003993 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003994 return BAD_VALUE;
3995 }
Eric Laurent874c42872014-08-08 15:13:39 -07003996
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 //update source and sink with our own data as the data passed in the patch may
3998 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003999 PatchBuilder patchBuilder;
4000 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004001
4002 // if first sink is to MSD, establish single MSD patch
4003 if (getMsdAudioOutDevices().contains(
4004 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4005 ALOGV("%s patching to MSD", __FUNCTION__);
4006 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4007 goto installPatch;
4008 }
4009
François Gaffieafd4cea2019-11-18 15:50:22 +01004010 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4011 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004012
Eric Laurent874c42872014-08-08 15:13:39 -07004013 for (size_t i = 0; i < patch->num_sinks; i++) {
4014 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004015 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004016 return INVALID_OPERATION;
4017 }
François Gaffie11d30102018-11-02 16:09:09 +01004018 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004019 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004020 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004021 return BAD_VALUE;
4022 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004023 audio_port_config sinkPortConfig = {};
4024 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4025 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004026
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004027 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4028 // volume management purpose (tracking activity)
4029 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4030 // in config XML to reach the sink so that is can be declared as available.
4031 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4032 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4033 if (sourceDesc != nullptr) {
4034 // take care of dynamic routing for SwOutput selection,
4035 audio_attributes_t attributes = sourceDesc->attributes();
4036 audio_stream_type_t stream = sourceDesc->stream();
4037 audio_attributes_t resultAttr;
4038 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4039 config.sample_rate = sourceDesc->config().sample_rate;
4040 config.channel_mask = sourceDesc->config().channel_mask;
4041 config.format = sourceDesc->config().format;
4042 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4043 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4044 bool isRequestedDeviceForExclusiveUse = false;
4045 output_type_t outputType;
4046 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4047 &stream, sourceDesc->uid(), &config, &flags,
4048 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4049 nullptr, &outputType);
4050 if (output == AUDIO_IO_HANDLE_NONE) {
4051 ALOGV("%s no output for device %s",
4052 __FUNCTION__, sinkDevice->toString().c_str());
4053 return INVALID_OPERATION;
4054 }
4055 outputDesc = mOutputs.valueFor(output);
4056 if (outputDesc->isDuplicated()) {
4057 ALOGE("%s output is duplicated", __func__);
4058 return INVALID_OPERATION;
4059 }
4060 sourceDesc->setSwOutput(outputDesc);
4061 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004062 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004063 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004064 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004065 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004066 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4067 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004068 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4069 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004070 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4071 (sourceDesc != nullptr &&
4072 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004073 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004074 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004075 return INVALID_OPERATION;
4076 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004077 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004078 SortedVector<audio_io_handle_t> outputs =
4079 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4080 // if the sink device is reachable via an opened output stream, request to
4081 // go via this output stream by adding a second source to the patch
4082 // description
4083 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004084 if (output != AUDIO_IO_HANDLE_NONE) {
4085 outputDesc = mOutputs.valueFor(output);
4086 if (outputDesc->isDuplicated()) {
4087 ALOGV("%s output for device %s is duplicated",
4088 __FUNCTION__, sinkDevice->toString().c_str());
4089 return INVALID_OPERATION;
4090 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004091 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004092 }
4093 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004094 audio_port_config srcMixPortConfig = {};
4095 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004096 // for volume control, we may need a valid stream
4097 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4098 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4099 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004100 }
Eric Laurent83b88082014-06-20 18:31:16 -07004101 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004102 }
4103 // TODO: check from routing capabilities in config file and other conflicting patches
4104
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004105installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004106 status_t status = installPatch(
4107 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004108 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004109 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004110 return INVALID_OPERATION;
4111 }
4112 } else {
4113 return BAD_VALUE;
4114 }
4115 } else {
4116 return BAD_VALUE;
4117 }
4118 return NO_ERROR;
4119}
4120
4121status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4122 uid_t uid)
4123{
4124 ALOGV("releaseAudioPatch() patch %d", handle);
4125
4126 ssize_t index = mAudioPatches.indexOfKey(handle);
4127
4128 if (index < 0) {
4129 return BAD_VALUE;
4130 }
4131 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004132 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4133 __func__, mUidCached, patchDesc->getUid(), uid);
4134 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004135 return INVALID_OPERATION;
4136 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004137 return releaseAudioPatchInternal(handle);
4138}
Eric Laurent6a94d692014-05-20 11:18:06 -07004139
François Gaffieafd4cea2019-11-18 15:50:22 +01004140status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4141 uint32_t delayMs)
4142{
4143 ALOGV("%s patch %d", __func__, handle);
4144 if (mAudioPatches.indexOfKey(handle) < 0) {
4145 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4146 return BAD_VALUE;
4147 }
4148 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004149 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004150 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004151 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004152 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004153 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004154 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 return BAD_VALUE;
4156 }
4157
François Gaffie11d30102018-11-02 16:09:09 +01004158 setOutputDevices(outputDesc,
4159 getNewOutputDevices(outputDesc, true /*fromCache*/),
4160 true,
4161 0,
4162 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004163 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4164 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004165 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004167 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004168 return BAD_VALUE;
4169 }
4170 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004171 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 true,
4173 NULL);
4174 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004175 status_t status =
4176 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4177 ALOGV("%s patch panel returned %d patchHandle %d",
4178 __func__, status, patchDesc->getAfHandle());
4179 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004181 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004182 // SW Bridge
4183 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4184 sp<SwAudioOutputDescriptor> outputDesc =
4185 mOutputs.getOutputFromId(patch->sources[1].id);
4186 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004187 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4188 // releaseOutput has already called closeOuput in case of direct output
4189 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004190 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004191 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4192 // force SwOutput patch removal as AF counter part patch has already gone.
4193 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4194 removeAudioPatch(outputDesc->getPatchHandle());
4195 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004196 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4197 setOutputDevices(outputDesc,
4198 getNewOutputDevices(outputDesc, true /*fromCache*/),
4199 true, /*force*/
4200 0,
4201 NULL);
4202 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 } else {
4204 return BAD_VALUE;
4205 }
4206 } else {
4207 return BAD_VALUE;
4208 }
4209 return NO_ERROR;
4210}
4211
4212status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4213 struct audio_patch *patches,
4214 unsigned int *generation)
4215{
François Gaffie53615e22015-03-19 09:24:12 +01004216 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004217 return BAD_VALUE;
4218 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004220 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004221}
4222
Eric Laurente1715a42014-05-20 11:30:42 -07004223status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004224{
Eric Laurente1715a42014-05-20 11:30:42 -07004225 ALOGV("setAudioPortConfig()");
4226
4227 if (config == NULL) {
4228 return BAD_VALUE;
4229 }
4230 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4231 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004232 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4233 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004234 }
4235
Eric Laurenta121f902014-06-03 13:32:54 -07004236 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004237 if (config->type == AUDIO_PORT_TYPE_MIX) {
4238 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004240 if (outputDesc == NULL) {
4241 return BAD_VALUE;
4242 }
Eric Laurent84c70242014-06-23 08:46:27 -07004243 ALOG_ASSERT(!outputDesc->isDuplicated(),
4244 "setAudioPortConfig() called on duplicated output %d",
4245 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004246 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004247 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004248 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004249 if (inputDesc == NULL) {
4250 return BAD_VALUE;
4251 }
Eric Laurenta121f902014-06-03 13:32:54 -07004252 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004253 } else {
4254 return BAD_VALUE;
4255 }
4256 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4257 sp<DeviceDescriptor> deviceDesc;
4258 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4259 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4260 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4261 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4262 } else {
4263 return BAD_VALUE;
4264 }
4265 if (deviceDesc == NULL) {
4266 return BAD_VALUE;
4267 }
Eric Laurenta121f902014-06-03 13:32:54 -07004268 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004269 } else {
4270 return BAD_VALUE;
4271 }
4272
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004273 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004274 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4275 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004276 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004277 audioPortConfig->toAudioPortConfig(&newConfig, config);
4278 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004279 }
Eric Laurenta121f902014-06-03 13:32:54 -07004280 if (status != NO_ERROR) {
4281 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004282 }
Eric Laurente1715a42014-05-20 11:30:42 -07004283
4284 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004285}
4286
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004287void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4288{
Eric Laurentd60560a2015-04-10 11:31:20 -07004289 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004290 clearAudioPatches(uid);
4291 clearSessionRoutes(uid);
4292}
4293
Eric Laurent6a94d692014-05-20 11:18:06 -07004294void AudioPolicyManager::clearAudioPatches(uid_t uid)
4295{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004296 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004297 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004298 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004299 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004300 }
4301 }
4302}
4303
François Gaffiec005e562018-11-06 15:04:49 +01004304void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004305{
François Gaffiec005e562018-11-06 15:04:49 +01004306 // Take the first attributes following the product strategy as it is used to retrieve the routed
4307 // device. All attributes wihin a strategy follows the same "routing strategy"
4308 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4309 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004310 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004311 for (size_t j = 0; j < mOutputs.size(); j++) {
4312 if (mOutputs.keyAt(j) == ouptutToSkip) {
4313 continue;
4314 }
4315 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004316 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004317 continue;
4318 }
4319 // If the default device for this strategy is on another output mix,
4320 // invalidate all tracks in this strategy to force re connection.
4321 // Otherwise select new device on the output mix.
4322 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004323 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4324 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004325 }
4326 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004327 setOutputDevices(
4328 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004329 }
4330 }
4331}
4332
4333void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4334{
4335 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004336 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004337 for (size_t i = 0; i < mOutputs.size(); i++) {
4338 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004339 for (const auto& client : outputDesc->getClientIterable()) {
4340 if (client->hasPreferredDevice() && client->uid() == uid) {
4341 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004342 auto clientStrategy = client->strategy();
4343 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4344 end(affectedStrategies)) {
4345 continue;
4346 }
4347 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004348 }
4349 }
4350 }
4351 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004352 for (const auto& strategy : affectedStrategies) {
4353 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004354 }
4355
4356 // remove input routes associated with this uid
4357 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004358 for (size_t i = 0; i < mInputs.size(); i++) {
4359 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004360 for (const auto& client : inputDesc->getClientIterable()) {
4361 if (client->hasPreferredDevice() && client->uid() == uid) {
4362 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4363 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004364 }
4365 }
4366 }
4367 // reroute inputs if necessary
4368 SortedVector<audio_io_handle_t> inputsToClose;
4369 for (size_t i = 0; i < mInputs.size(); i++) {
4370 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004371 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004372 inputsToClose.add(inputDesc->mIoHandle);
4373 }
4374 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004375 for (const auto& input : inputsToClose) {
4376 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004377 }
4378}
4379
Eric Laurentd60560a2015-04-10 11:31:20 -07004380void AudioPolicyManager::clearAudioSources(uid_t uid)
4381{
4382 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004383 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4384 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004385 stopAudioSource(mAudioSources.keyAt(i));
4386 }
4387 }
4388}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004389
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004390status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4391 audio_io_handle_t *ioHandle,
4392 audio_devices_t *device)
4393{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004394 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4395 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004396 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004397 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004398
François Gaffiedf372692015-03-19 10:43:27 +01004399 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004400}
4401
Eric Laurentd60560a2015-04-10 11:31:20 -07004402status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004403 const audio_attributes_t *attributes,
4404 audio_port_handle_t *portId,
4405 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004406{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004407 ALOGV("%s", __FUNCTION__);
4408 *portId = AUDIO_PORT_HANDLE_NONE;
4409
4410 if (source == NULL || attributes == NULL || portId == NULL) {
4411 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4412 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004413 return BAD_VALUE;
4414 }
4415
Eric Laurentd60560a2015-04-10 11:31:20 -07004416 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4417 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004418 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4419 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004420 return INVALID_OPERATION;
4421 }
4422
François Gaffie11d30102018-11-02 16:09:09 +01004423 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004424 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004425 String8(source->ext.device.address),
4426 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004427 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004428 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004429 return BAD_VALUE;
4430 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004431
jiabin4ef93452019-09-10 14:29:54 -07004432 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004433
François Gaffieaaac0fd2018-11-22 17:56:39 +01004434 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004436 mEngine->getStreamTypeForAttributes(*attributes),
4437 mEngine->getProductStrategyForAttributes(*attributes),
4438 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004439
4440 status_t status = connectAudioSource(sourceDesc);
4441 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004442 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004443 }
4444 return status;
4445}
4446
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004447status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004448{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004449 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004450
4451 // make sure we only have one patch per source.
4452 disconnectAudioSource(sourceDesc);
4453
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004454 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004455 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4456 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4457 sourceDesc->srcDevice()->type(),
4458 String8(sourceDesc->srcDevice()->address().c_str()),
4459 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004460 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004461 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004462 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004463 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004464 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4465 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4466 return INVALID_OPERATION;
4467 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004468 PatchBuilder patchBuilder;
4469 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4470 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4471 status_t status =
4472 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4473 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4474 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4475 return INVALID_OPERATION;
4476 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004477 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004478 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4479 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4480 if (swOutput != 0) {
4481 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004482 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004483 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004484 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004485 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004486 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004487 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004488 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004489 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004490 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004491 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004492 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004493 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4494 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004495 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004496 if (delayMs != 0) {
4497 usleep(delayMs * 1000);
4498 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004499 } else {
4500 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4501 if (hwOutputDesc != 0) {
4502 // create Hwoutput and add to mHwOutputs
4503 } else {
4504 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4505 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004506 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004507 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004508
4509FailureSourceActive:
4510 swOutput->stop();
4511 releaseOutput(sourceDesc->portId());
4512FailureSourceAdded:
4513 sourceDesc->setSwOutput(nullptr);
4514FailureReleasePatch:
4515 releaseAudioPatchInternal(handle);
4516 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004517}
4518
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004519status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004520{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004521 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4522 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004523 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004524 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004525 return BAD_VALUE;
4526 }
4527 status_t status = disconnectAudioSource(sourceDesc);
4528
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004529 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004530 return status;
4531}
4532
Andy Hung2ddee192015-12-18 17:34:44 -08004533status_t AudioPolicyManager::setMasterMono(bool mono)
4534{
4535 if (mMasterMono == mono) {
4536 return NO_ERROR;
4537 }
4538 mMasterMono = mono;
4539 // if enabling mono we close all offloaded devices, which will invalidate the
4540 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4541 // for recreating the new AudioTrack as non-offloaded PCM.
4542 //
4543 // If disabling mono, we leave all tracks as is: we don't know which clients
4544 // and tracks are able to be recreated as offloaded. The next "song" should
4545 // play back offloaded.
4546 if (mMasterMono) {
4547 Vector<audio_io_handle_t> offloaded;
4548 for (size_t i = 0; i < mOutputs.size(); ++i) {
4549 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4550 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4551 offloaded.push(desc->mIoHandle);
4552 }
4553 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004554 for (const auto& handle : offloaded) {
4555 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004556 }
4557 }
4558 // update master mono for all remaining outputs
4559 for (size_t i = 0; i < mOutputs.size(); ++i) {
4560 updateMono(mOutputs.keyAt(i));
4561 }
4562 return NO_ERROR;
4563}
4564
4565status_t AudioPolicyManager::getMasterMono(bool *mono)
4566{
4567 *mono = mMasterMono;
4568 return NO_ERROR;
4569}
4570
Eric Laurentac9cef52017-06-09 15:46:26 -07004571float AudioPolicyManager::getStreamVolumeDB(
4572 audio_stream_type_t stream, int index, audio_devices_t device)
4573{
jiabin9a3361e2019-10-01 09:38:30 -07004574 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004575}
4576
jiabin81772902018-04-02 17:52:27 -07004577status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4578 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004579 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004580{
Kriti Dang6537def2021-03-02 13:46:59 +01004581 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4582 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004583 return BAD_VALUE;
4584 }
Kriti Dang6537def2021-03-02 13:46:59 +01004585 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4586 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004587
4588 size_t formatsWritten = 0;
4589 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004590
Kriti Dang6537def2021-03-02 13:46:59 +01004591 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004592 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4593 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004594 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004595 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004596 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004597 bool formatEnabled = true;
4598 switch (forceUse) {
4599 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004600 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004601 break;
4602 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4603 formatEnabled = false;
4604 break;
4605 default: // AUTO or ALWAYS => true
4606 break;
jiabin81772902018-04-02 17:52:27 -07004607 }
4608 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4609 }
jiabin81772902018-04-02 17:52:27 -07004610 }
4611 return NO_ERROR;
4612}
4613
Kriti Dang6537def2021-03-02 13:46:59 +01004614status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4615 audio_format_t *surroundFormats) {
4616 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4617 return BAD_VALUE;
4618 }
4619 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4620 __func__, *numSurroundFormats, surroundFormats);
4621
4622 size_t formatsWritten = 0;
4623 size_t formatsMax = *numSurroundFormats;
4624 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4625
4626 // Return formats from all device profiles that have already been resolved by
4627 // checkOutputsForDevice().
4628 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4629 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4630 audio_devices_t deviceType = device->type();
4631 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4632 // returns formats reported by HDMI devices.
4633 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4634 continue;
4635 }
4636 // Formats reported by sink devices
4637 std::unordered_set<audio_format_t> formatset;
4638 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4639 formatset.insert(it->second.begin(), it->second.end());
4640 }
4641
4642 // Formats hard-coded in the in policy configuration file (if any).
4643 FormatVector encodedFormats = device->encodedFormats();
4644 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4645 // Filter the formats which are supported by the vendor hardware.
4646 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4647 if (mConfig.getSurroundFormats().count(*it) != 0) {
4648 formats.insert(*it);
4649 } else {
4650 for (const auto& pair : mConfig.getSurroundFormats()) {
4651 if (pair.second.count(*it) != 0) {
4652 formats.insert(pair.first);
4653 break;
4654 }
4655 }
4656 }
4657 }
4658 }
4659 *numSurroundFormats = formats.size();
4660 for (const auto& format: formats) {
4661 if (formatsWritten < formatsMax) {
4662 surroundFormats[formatsWritten++] = format;
4663 }
4664 }
4665 return NO_ERROR;
4666}
4667
jiabin81772902018-04-02 17:52:27 -07004668status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4669{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004670 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004671 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4672 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004673 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004674 return BAD_VALUE;
4675 }
4676
Mikhail Naganov100f0122018-11-29 11:22:16 -08004677 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4678 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004679 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004680 return INVALID_OPERATION;
4681 }
4682
Mikhail Naganov100f0122018-11-29 11:22:16 -08004683 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004684 return NO_ERROR;
4685 }
4686
Mikhail Naganov100f0122018-11-29 11:22:16 -08004687 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004688 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004689 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004690 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004691 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004692 }
4693 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004694 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004695 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004696 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004697 }
4698 }
4699
4700 sp<SwAudioOutputDescriptor> outputDesc;
4701 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004702 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4703 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004704 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4705 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004706 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004707 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004708 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4709 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4710 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004711 name.c_str(),
4712 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004713 if (status != NO_ERROR) {
4714 continue;
4715 }
4716 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4717 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4718 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004719 name.c_str(),
4720 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004721 profileUpdated |= (status == NO_ERROR);
4722 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004723 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004724 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004725 AUDIO_DEVICE_IN_HDMI);
4726 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4727 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004728 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004729 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004730 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4731 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4732 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004733 name.c_str(),
4734 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004735 if (status != NO_ERROR) {
4736 continue;
4737 }
4738 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4739 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4740 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004741 name.c_str(),
4742 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004743 profileUpdated |= (status == NO_ERROR);
4744 }
4745
jiabin81772902018-04-02 17:52:27 -07004746 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004747 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004748 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004749 }
4750
4751 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4752}
4753
Eric Laurent5ada82e2019-08-29 17:53:54 -07004754void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004755{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004756 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004757 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004758 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004759 }
4760}
4761
jiabin6012f912018-11-02 17:06:30 -07004762bool AudioPolicyManager::isHapticPlaybackSupported()
4763{
4764 for (const auto& hwModule : mHwModules) {
4765 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4766 for (const auto &outProfile : outputProfiles) {
4767 struct audio_port audioPort;
4768 outProfile->toAudioPort(&audioPort);
4769 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4770 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4771 return true;
4772 }
4773 }
4774 }
4775 }
4776 return false;
4777}
4778
Eric Laurent8340e672019-11-06 11:01:08 -08004779bool AudioPolicyManager::isCallScreenModeSupported()
4780{
4781 return getConfig().isCallScreenModeSupported();
4782}
4783
4784
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004785status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004786{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004787 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004788 if (!sourceDesc->isConnected()) {
4789 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4790 return NO_ERROR;
4791 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004792 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4793 if (swOutput != 0) {
4794 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004795 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004796 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004797 }
jiabinbce0c1d2020-10-05 11:20:18 -07004798 if (releaseOutput(sourceDesc->portId())) {
4799 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4800 // no need to release audio patch here but just return NO_ERROR.
4801 return NO_ERROR;
4802 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004803 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004804 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004805 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004806 // close Hwoutput and remove from mHwOutputs
4807 } else {
4808 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4809 }
4810 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004811 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4812 sourceDesc->disconnect();
4813 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004814}
4815
François Gaffiec005e562018-11-06 15:04:49 +01004816sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4817 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004818{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004819 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004820 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004821 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004822 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004823 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4824 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004825 source = sourceDesc;
4826 break;
4827 }
4828 }
4829 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004830}
4831
Eric Laurente552edb2014-03-10 17:42:56 -07004832// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004833// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004834// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004835uint32_t AudioPolicyManager::nextAudioPortGeneration()
4836{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004837 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004838}
4839
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004840static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004841 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4842 !audioPolicyXmlConfigFile.empty()) {
4843 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4844 if (ret == NO_ERROR) {
4845 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004846 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004847 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004848 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004849 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004850}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004851
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004852AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4853 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004854 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004855 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004856 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004857 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004858 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004859 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004860 mAudioPortGeneration(1),
4861 mBeaconMuteRefCount(0),
4862 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004863 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004864 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004865 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004866 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004867{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004868}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004869
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004870AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4871 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4872{
4873 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004874}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004875
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004876void AudioPolicyManager::loadConfig() {
4877 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004878 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004879 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004880 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004881}
4882
4883status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004884 {
4885 auto engLib = EngineLibrary::load(
4886 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4887 if (!engLib) {
4888 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4889 return NO_INIT;
4890 }
4891 mEngine = engLib->createEngine();
4892 if (mEngine == nullptr) {
4893 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4894 return NO_INIT;
4895 }
François Gaffie2110e042015-03-24 08:41:51 +01004896 }
4897 mEngine->setObserver(this);
4898 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004899 if (status != NO_ERROR) {
4900 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4901 return status;
4902 }
François Gaffie2110e042015-03-24 08:41:51 +01004903
Eric Laurent1d69c872021-01-11 18:53:01 +01004904 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4905 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4906
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004907 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004908 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004909 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004910
Eric Laurent3a4311c2014-03-17 12:00:47 -07004911 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004912 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4913 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4914 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004915 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004916 }
jiabin9ff780e2018-03-19 18:19:52 -07004917 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004918 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004919 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004920 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004921 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004922 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004923 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004924 }
4925 }
4926 }
Eric Laurente552edb2014-03-10 17:42:56 -07004927
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004928 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004929
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004930 // Silence ALOGV statements
4931 property_set("log.tag." LOG_TAG, "D");
4932
Eric Laurente552edb2014-03-10 17:42:56 -07004933 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004934 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004935}
4936
Eric Laurente0720872014-03-11 09:30:41 -07004937AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004938{
Eric Laurente552edb2014-03-10 17:42:56 -07004939 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004940 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004941 }
4942 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004943 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004944 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004945 mAvailableOutputDevices.clear();
4946 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004947 mOutputs.clear();
4948 mInputs.clear();
4949 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004950 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004951 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004952}
4953
Eric Laurente0720872014-03-11 09:30:41 -07004954status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004955{
Eric Laurent87ffa392015-05-22 10:32:38 -07004956 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004957}
4958
Eric Laurente552edb2014-03-10 17:42:56 -07004959// ---
4960
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004961void AudioPolicyManager::onNewAudioModulesAvailable()
4962{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004963 DeviceVector newDevices;
4964 onNewAudioModulesAvailableInt(&newDevices);
4965 if (!newDevices.empty()) {
4966 nextAudioPortGeneration();
4967 mpClientInterface->onAudioPortListUpdate();
4968 }
4969}
4970
4971void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4972{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004973 for (const auto& hwModule : mHwModulesAll) {
4974 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4975 continue;
4976 }
4977 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4978 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4979 ALOGW("could not open HW module %s", hwModule->getName());
4980 continue;
4981 }
4982 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10004983 // open all output streams needed to access attached devices.
4984 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004985 // This also validates mAvailableOutputDevices list
4986 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4987 if (!outProfile->canOpenNewIo()) {
4988 ALOGE("Invalid Output profile max open count %u for profile %s",
4989 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4990 continue;
4991 }
4992 if (!outProfile->hasSupportedDevices()) {
4993 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4994 continue;
4995 }
4996 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4997 mTtsOutputAvailable = true;
4998 }
4999
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005000 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5001 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5002 sp<DeviceDescriptor> supportedDevice = 0;
5003 if (supportedDevices.contains(mDefaultOutputDevice)) {
5004 supportedDevice = mDefaultOutputDevice;
5005 } else {
5006 // choose first device present in profile's SupportedDevices also part of
5007 // mAvailableOutputDevices.
5008 if (availProfileDevices.isEmpty()) {
5009 continue;
5010 }
5011 supportedDevice = availProfileDevices.itemAt(0);
5012 }
5013 if (!mOutputDevicesAll.contains(supportedDevice)) {
5014 continue;
5015 }
5016 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5017 mpClientInterface);
5018 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5019 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
5020 AUDIO_STREAM_DEFAULT,
5021 AUDIO_OUTPUT_FLAG_NONE, &output);
5022 if (status != NO_ERROR) {
5023 ALOGW("Cannot open output stream for devices %s on hw module %s",
5024 supportedDevice->toString().c_str(), hwModule->getName());
5025 continue;
5026 }
5027 for (const auto &device : availProfileDevices) {
5028 // give a valid ID to an attached device once confirmed it is reachable
5029 if (!device->isAttached()) {
5030 device->attach(hwModule);
5031 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005032 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005033 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005034 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5035 }
5036 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005037 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005038 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5039 mPrimaryOutput = outputDesc;
5040 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005041 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5042 outputDesc->close();
5043 } else {
5044 addOutput(output, outputDesc);
5045 setOutputDevices(outputDesc,
5046 DeviceVector(supportedDevice),
5047 true,
5048 0,
5049 NULL);
5050 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005051 }
5052 // open input streams needed to access attached devices to validate
5053 // mAvailableInputDevices list
5054 for (const auto& inProfile : hwModule->getInputProfiles()) {
5055 if (!inProfile->canOpenNewIo()) {
5056 ALOGE("Invalid Input profile max open count %u for profile %s",
5057 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5058 continue;
5059 }
5060 if (!inProfile->hasSupportedDevices()) {
5061 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5062 continue;
5063 }
5064 // chose first device present in profile's SupportedDevices also part of
5065 // available input devices
5066 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5067 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5068 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005069 ALOGV("%s: Input device list is empty! for profile %s",
5070 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005071 continue;
5072 }
5073 sp<AudioInputDescriptor> inputDesc =
5074 new AudioInputDescriptor(inProfile, mpClientInterface);
5075
5076 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5077 status_t status = inputDesc->open(nullptr,
5078 availProfileDevices.itemAt(0),
5079 AUDIO_SOURCE_MIC,
5080 AUDIO_INPUT_FLAG_NONE,
5081 &input);
5082 if (status != NO_ERROR) {
5083 ALOGW("Cannot open input stream for device %s on hw module %s",
5084 availProfileDevices.toString().c_str(),
5085 hwModule->getName());
5086 continue;
5087 }
5088 for (const auto &device : availProfileDevices) {
5089 // give a valid ID to an attached device once confirmed it is reachable
5090 if (!device->isAttached()) {
5091 device->attach(hwModule);
5092 device->importAudioPortAndPickAudioProfile(inProfile, true);
5093 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005094 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005095 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5096 }
5097 }
5098 inputDesc->close();
5099 }
5100 }
5101}
5102
Eric Laurent98e38192018-02-15 18:31:53 -08005103void AudioPolicyManager::addOutput(audio_io_handle_t output,
5104 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005105{
Eric Laurent1c333e22014-05-20 10:48:17 -07005106 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005107 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005108 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005109 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005111}
5112
François Gaffie53615e22015-03-19 09:24:12 +01005113void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5114{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005115 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5116 ALOGV("%s: removing primary output", __func__);
5117 mPrimaryOutput = nullptr;
5118 }
François Gaffie53615e22015-03-19 09:24:12 +01005119 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005120 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005121}
5122
Eric Laurent98e38192018-02-15 18:31:53 -08005123void AudioPolicyManager::addInput(audio_io_handle_t input,
5124 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005125{
Eric Laurent1c333e22014-05-20 10:48:17 -07005126 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005128}
Eric Laurente552edb2014-03-10 17:42:56 -07005129
François Gaffie11d30102018-11-02 16:09:09 +01005130status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005131 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005132 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005133{
François Gaffie11d30102018-11-02 16:09:09 +01005134 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005135 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005136 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005137
François Gaffie11d30102018-11-02 16:09:09 +01005138 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005139 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005140 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005141 }
Eric Laurente552edb2014-03-10 17:42:56 -07005142
Eric Laurent3b73df72014-03-11 09:06:29 -07005143 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005144 // first call getAudioPort to get the supported attributes from the HAL
5145 struct audio_port_v7 port = {};
5146 device->toAudioPort(&port);
5147 status_t status = mpClientInterface->getAudioPort(&port);
5148 if (status == NO_ERROR) {
5149 device->importAudioPort(port);
5150 }
5151
5152 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005153 for (size_t i = 0; i < mOutputs.size(); i++) {
5154 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005155 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005156 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005157 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5158 mOutputs.keyAt(i), device->toString().c_str());
5159 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005160 }
5161 }
5162 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005163 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005164 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005165 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5166 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005167 if (profile->supportsDevice(device)) {
5168 profiles.add(profile);
5169 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5170 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005171 }
5172 }
5173 }
5174
Eric Laurent7b279bb2015-12-14 10:18:23 -08005175 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005176
Eric Laurente552edb2014-03-10 17:42:56 -07005177 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005178 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005179 return BAD_VALUE;
5180 }
5181
5182 // open outputs for matching profiles if needed. Direct outputs are also opened to
5183 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5184 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005185 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005186
5187 // nothing to do if one output is already opened for this profile
5188 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005189 for (j = 0; j < outputs.size(); j++) {
5190 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005191 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005192 // matching profile: save the sample rates, format and channel masks supported
5193 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005194 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005195 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005196 }
Eric Laurente552edb2014-03-10 17:42:56 -07005197 break;
5198 }
5199 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005200 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005201 continue;
5202 }
5203
Eric Laurent3974e3b2017-12-07 17:58:43 -08005204 if (!profile->canOpenNewIo()) {
5205 ALOGW("Max Output number %u already opened for this profile %s",
5206 profile->maxOpenCount, profile->getTagName().c_str());
5207 continue;
5208 }
5209
Eric Laurent83efe1c2017-07-09 16:51:08 -07005210 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005211 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005212 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5213 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005214 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005215 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005216 profiles.removeAt(profile_index);
5217 profile_index--;
5218 } else {
5219 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005220 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005221 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005222 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5223 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005224 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005225 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005226
François Gaffie11d30102018-11-02 16:09:09 +01005227 if (device_distinguishes_on_address(deviceType)) {
5228 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5229 device->toString().c_str());
5230 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5231 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005232 }
Eric Laurente552edb2014-03-10 17:42:56 -07005233 ALOGV("checkOutputsForDevice(): adding output %d", output);
5234 }
5235 }
5236
5237 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005238 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005239 return BAD_VALUE;
5240 }
Eric Laurentd4692962014-05-05 18:13:44 -07005241 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005242 // check if one opened output is not needed any more after disconnecting one device
5243 for (size_t i = 0; i < mOutputs.size(); i++) {
5244 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005245 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005246 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005247 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005248 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005249 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005250 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005251 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5252 mOutputs.keyAt(i));
5253 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005254 }
Eric Laurente552edb2014-03-10 17:42:56 -07005255 }
5256 }
Eric Laurentd4692962014-05-05 18:13:44 -07005257 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005258 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005259 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5260 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005261 if (!profile->supportsDevice(device)) {
5262 continue;
5263 }
5264 ALOGV("checkOutputsForDevice(): "
5265 "clearing direct output profile %zu on module %s",
5266 j, hwModule->getName());
5267 profile->clearAudioProfiles();
5268 if (!profile->hasDynamicAudioProfile()) {
5269 continue;
5270 }
5271 // When a device is disconnected, if there is an IOProfile that contains dynamic
5272 // profiles and supports the disconnected device, call getAudioPort to repopulate
5273 // the capabilities of the devices that is supported by the IOProfile.
5274 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5275 if (supportedDevice == device ||
5276 !mAvailableOutputDevices.contains(supportedDevice)) {
5277 continue;
5278 }
5279 struct audio_port_v7 port;
5280 supportedDevice->toAudioPort(&port);
5281 status_t status = mpClientInterface->getAudioPort(&port);
5282 if (status == NO_ERROR) {
5283 supportedDevice->importAudioPort(port);
5284 }
Eric Laurente552edb2014-03-10 17:42:56 -07005285 }
5286 }
5287 }
5288 }
5289 return NO_ERROR;
5290}
5291
François Gaffie11d30102018-11-02 16:09:09 +01005292status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005293 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005294{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005295 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005296
François Gaffie11d30102018-11-02 16:09:09 +01005297 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005298 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005299 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005300 }
5301
Eric Laurentd4692962014-05-05 18:13:44 -07005302 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005303 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005304 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005305 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005306 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005307 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005308 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005309 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005310
François Gaffie11d30102018-11-02 16:09:09 +01005311 if (profile->supportsDevice(device)) {
5312 profiles.add(profile);
5313 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5314 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005315 }
5316 }
5317 }
5318
Eric Laurent0dd51852019-04-19 18:18:58 -07005319 if (profiles.isEmpty()) {
5320 ALOGW("%s: No input profile available for device %s",
5321 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005322 return BAD_VALUE;
5323 }
5324
5325 // open inputs for matching profiles if needed. Direct inputs are also opened to
5326 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5327 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5328
Eric Laurent1c333e22014-05-20 10:48:17 -07005329 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005330
Eric Laurentd4692962014-05-05 18:13:44 -07005331 // nothing to do if one input is already opened for this profile
5332 size_t input_index;
5333 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5334 desc = mInputs.valueAt(input_index);
5335 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005336 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005337 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005338 }
Eric Laurentd4692962014-05-05 18:13:44 -07005339 break;
5340 }
5341 }
5342 if (input_index != mInputs.size()) {
5343 continue;
5344 }
5345
Eric Laurent3974e3b2017-12-07 17:58:43 -08005346 if (!profile->canOpenNewIo()) {
5347 ALOGW("Max Input number %u already opened for this profile %s",
5348 profile->maxOpenCount, profile->getTagName().c_str());
5349 continue;
5350 }
5351
Eric Laurentfe231122017-11-17 17:48:06 -08005352 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005353 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005354 status_t status = desc->open(nullptr,
5355 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005356 AUDIO_SOURCE_MIC,
5357 AUDIO_INPUT_FLAG_NONE,
5358 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005359
Eric Laurentcf2c0212014-07-25 16:20:43 -07005360 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005361 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005362 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005363 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005364 mpClientInterface->setParameters(input, String8(param));
5365 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005366 }
François Gaffie11d30102018-11-02 16:09:09 +01005367 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005368 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005369 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005370 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005371 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005372 }
5373
Eric Laurent0dd51852019-04-19 18:18:58 -07005374 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005375 addInput(input, desc);
5376 }
5377 } // endif input != 0
5378
Eric Laurentcf2c0212014-07-25 16:20:43 -07005379 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005380 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005381 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005382 profiles.removeAt(profile_index);
5383 profile_index--;
5384 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005385 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005386 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005387 }
Eric Laurentd4692962014-05-05 18:13:44 -07005388 ALOGV("checkInputsForDevice(): adding input %d", input);
5389 }
5390 } // end scan profiles
5391
5392 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005393 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005394 return BAD_VALUE;
5395 }
5396 } else {
5397 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005398 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005399 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005400 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005401 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005402 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005403 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005404 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005405 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5406 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005407 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005408 }
5409 }
5410 }
5411 } // end disconnect
5412
5413 return NO_ERROR;
5414}
5415
5416
Eric Laurente0720872014-03-11 09:30:41 -07005417void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005418{
5419 ALOGV("closeOutput(%d)", output);
5420
François Gaffie1c878552018-11-22 16:53:21 +01005421 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5422 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005423 ALOGW("closeOutput() unknown output %d", output);
5424 return;
5425 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005426 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005427 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005428
Eric Laurente552edb2014-03-10 17:42:56 -07005429 // look for duplicated outputs connected to the output being removed.
5430 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005431 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5432 if (dupOutput->isDuplicated() &&
5433 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5434 sp<SwAudioOutputDescriptor> remainingOutput =
5435 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005436 // As all active tracks on duplicated output will be deleted,
5437 // and as they were also referenced on the other output, the reference
5438 // count for their stream type must be adjusted accordingly on
5439 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005440 const bool wasActive = remainingOutput->isActive();
5441 // Note: no-op on the closing output where all clients has already been set inactive
5442 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005443 // stop() will be a no op if the output is still active but is needed in case all
5444 // active streams refcounts where cleared above
5445 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005446 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005447 }
Eric Laurente552edb2014-03-10 17:42:56 -07005448 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5449 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5450
5451 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005452 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005453 }
5454 }
5455
Eric Laurent05b90f82014-08-27 15:32:29 -07005456 nextAudioPortGeneration();
5457
François Gaffie1c878552018-11-22 16:53:21 +01005458 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005459 if (index >= 0) {
5460 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005461 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5462 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005463 mAudioPatches.removeItemsAt(index);
5464 mpClientInterface->onAudioPatchListUpdate();
5465 }
5466
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005467 if (closingOutputWasActive) {
5468 closingOutput->stop();
5469 }
François Gaffie1c878552018-11-22 16:53:21 +01005470 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005471
François Gaffie53615e22015-03-19 09:24:12 +01005472 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005473 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005474
5475 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5476 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005477 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005478 bool directOutputOpen = false;
5479 for (size_t i = 0; i < mOutputs.size(); i++) {
5480 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5481 directOutputOpen = true;
5482 break;
5483 }
5484 }
5485 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005486 ALOGV("no direct outputs open, reset MSD patches");
5487 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5488 // how output devices for patching are resolved. Avoid by caching and reusing the
5489 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5490 // devices to patch to. This may be complicated by the fact that devices may become
5491 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005492 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005493 }
5494 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005495}
5496
5497void AudioPolicyManager::closeInput(audio_io_handle_t input)
5498{
5499 ALOGV("closeInput(%d)", input);
5500
5501 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5502 if (inputDesc == NULL) {
5503 ALOGW("closeInput() unknown input %d", input);
5504 return;
5505 }
5506
Eric Laurent6a94d692014-05-20 11:18:06 -07005507 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005508
François Gaffie11d30102018-11-02 16:09:09 +01005509 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005510 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005511 if (index >= 0) {
5512 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005513 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5514 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005515 mAudioPatches.removeItemsAt(index);
5516 mpClientInterface->onAudioPatchListUpdate();
5517 }
5518
Eric Laurentfe231122017-11-17 17:48:06 -08005519 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005520 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005521
François Gaffie11d30102018-11-02 16:09:09 +01005522 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5523 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005524 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005525 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005526 }
Eric Laurente552edb2014-03-10 17:42:56 -07005527}
5528
François Gaffie11d30102018-11-02 16:09:09 +01005529SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5530 const DeviceVector &devices,
5531 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005532{
5533 SortedVector<audio_io_handle_t> outputs;
5534
François Gaffie11d30102018-11-02 16:09:09 +01005535 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005536 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005537 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005538 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005539 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005540 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005541 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005542 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005543 outputs.add(openOutputs.keyAt(i));
5544 }
5545 }
5546 return outputs;
5547}
5548
Mikhail Naganov37977152018-07-11 15:54:44 -07005549void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5550{
5551 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5552 // output is suspended before any tracks are moved to it
5553 checkA2dpSuspend();
5554 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005555 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005556 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005557 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005558 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005559 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5560 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5561 // configuration changes will ultimately be rerouted correctly. We can still avoid
5562 // unnecessary rerouting by caching and reusing the arguments to
5563 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5564 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005565 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005566 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005567 // an event that changed routing likely occurred, inform upper layers
5568 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005569}
5570
François Gaffiec005e562018-11-06 15:04:49 +01005571bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5572 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005573{
François Gaffiec005e562018-11-06 15:04:49 +01005574 return mEngine->getProductStrategyForAttributes(lAttr) ==
5575 mEngine->getProductStrategyForAttributes(rAttr);
5576}
5577
Francois Gaffieff1eb522020-05-06 18:37:04 +02005578void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5579{
5580 for (size_t i = 0; i < mAudioSources.size(); i++) {
5581 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5582 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005583 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5584 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005585 connectAudioSource(sourceDesc);
5586 }
5587 }
5588}
5589
5590void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5591{
5592 for (size_t i = 0; i < mAudioSources.size(); i++) {
5593 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5594 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5595 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5596 disconnectAudioSource(sourceDesc);
5597 }
5598 }
5599}
5600
François Gaffiec005e562018-11-06 15:04:49 +01005601void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5602{
5603 auto psId = mEngine->getProductStrategyForAttributes(attr);
5604
5605 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5606 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005607
François Gaffie11d30102018-11-02 16:09:09 +01005608 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5609 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005610
Eric Laurentc209fe42020-06-05 18:11:23 -07005611 uint32_t maxLatency = 0;
5612 bool invalidate = false;
5613 // take into account dynamic audio policies related changes: if a client is now associated
5614 // to a different policy mix than at creation time, invalidate corresponding stream
5615 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5616 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5617 if (desc->isDuplicated()) {
5618 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005619 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005620 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5621 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5622 continue;
5623 }
5624 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005625 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5626 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07005627 if (status != OK) {
5628 continue;
5629 }
yucliuf4de36d2020-09-14 14:57:56 -07005630 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005631 invalidate = true;
5632 if (desc->isStrategyActive(psId)) {
5633 maxLatency = desc->latency();
5634 }
5635 break;
5636 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005637 }
5638 }
5639
Eric Laurentc209fe42020-06-05 18:11:23 -07005640 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005641 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5642 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005643 for (audio_io_handle_t srcOut : srcOutputs) {
5644 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005645 if (desc == nullptr) continue;
5646
5647 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005648 maxLatency = desc->latency();
5649 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005650
5651 if (invalidate) continue;
5652
5653 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005654 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005655 // a client on a non direct outputs has necessarily a linear PCM format
5656 // so we can call selectOutput() safely
5657 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5658 client->flags(),
5659 client->config().format,
5660 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005661 client->config().sample_rate,
5662 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005663 if (newOutput != srcOut) {
5664 invalidate = true;
5665 break;
5666 }
5667 } else {
5668 sp<IOProfile> profile = getProfileForOutput(newDevices,
5669 client->config().sample_rate,
5670 client->config().format,
5671 client->config().channel_mask,
5672 client->flags(),
5673 true /* directOnly */);
5674 if (profile != desc->mProfile) {
5675 invalidate = true;
5676 break;
5677 }
5678 }
5679 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005680 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005681
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005682 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005683 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005684 std::to_string(srcOutputs[0]).c_str(),
5685 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005686 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005687 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005688 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005689 if (desc == nullptr) continue;
5690
5691 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005692 setStrategyMute(psId, true, desc);
5693 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005694 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005695 }
François Gaffiec005e562018-11-06 15:04:49 +01005696 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005697 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005698 connectAudioSource(source);
5699 }
Eric Laurente552edb2014-03-10 17:42:56 -07005700 }
5701
François Gaffiec005e562018-11-06 15:04:49 +01005702 // Move effects associated to this stream from previous output to new output
5703 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005704 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005705 }
François Gaffiec005e562018-11-06 15:04:49 +01005706 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005707 if (invalidate) {
5708 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5709 mpClientInterface->invalidateStream(stream);
5710 }
Eric Laurente552edb2014-03-10 17:42:56 -07005711 }
5712 }
5713}
5714
Eric Laurente0720872014-03-11 09:30:41 -07005715void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005716{
François Gaffiec005e562018-11-06 15:04:49 +01005717 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5718 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5719 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005720 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005721 }
Eric Laurente552edb2014-03-10 17:42:56 -07005722}
5723
Kevin Rocard153f92d2018-12-18 18:33:28 -08005724void AudioPolicyManager::checkSecondaryOutputs() {
5725 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005726 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005727 for (size_t i = 0; i < mOutputs.size(); i++) {
5728 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5729 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005730 sp<AudioPolicyMix> primaryMix;
5731 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005732 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5733 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07005734 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5735 for (auto &secondaryMix : secondaryMixes) {
5736 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5737 if (outputDesc != nullptr &&
5738 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5739 secondaryDescs.push_back(outputDesc);
5740 }
5741 }
5742
jiabinf042b9b2021-05-07 23:46:28 +00005743 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005744 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005745 } else if (!std::equal(
5746 client->getSecondaryOutputs().begin(),
5747 client->getSecondaryOutputs().end(),
5748 secondaryDescs.begin(), secondaryDescs.end())) {
5749 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5750 std::vector<audio_io_handle_t> secondaryOutputIds;
5751 for (const auto& secondaryDesc : secondaryDescs) {
5752 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5753 weakSecondaryDescs.push_back(secondaryDesc);
5754 }
5755 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5756 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005757 }
5758 }
5759 }
jiabinf042b9b2021-05-07 23:46:28 +00005760 if (!trackSecondaryOutputs.empty()) {
5761 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5762 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005763 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005764 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005765 mpClientInterface->invalidateStream(stream);
5766 }
5767}
5768
Eric Laurent2517af32020-11-25 15:31:27 +01005769bool AudioPolicyManager::isScoRequestedForComm() const {
5770 AudioDeviceTypeAddrVector devices;
5771 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5772 for (const auto &device : devices) {
5773 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5774 return true;
5775 }
5776 }
5777 return false;
5778}
5779
Eric Laurente0720872014-03-11 09:30:41 -07005780void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005781{
François Gaffie53615e22015-03-19 09:24:12 +01005782 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005783 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005784 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005785 return;
5786 }
5787
Eric Laurent3a4311c2014-03-17 12:00:47 -07005788 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005789 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5790 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005791 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005792
5793 // if suspended, restore A2DP output if:
5794 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005795 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005796 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005797 //
Eric Laurentf732e072016-08-03 19:30:28 -07005798 // if not suspended, suspend A2DP output if:
5799 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005800 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005801 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005802 //
5803 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005804 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005805 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005806 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005807 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005808
5809 mpClientInterface->restoreOutput(a2dpOutput);
5810 mA2dpSuspended = false;
5811 }
5812 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005813 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005814 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005815 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005816 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005817
5818 mpClientInterface->suspendOutput(a2dpOutput);
5819 mA2dpSuspended = true;
5820 }
5821 }
5822}
5823
François Gaffie11d30102018-11-02 16:09:09 +01005824DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5825 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005826{
François Gaffie11d30102018-11-02 16:09:09 +01005827 DeviceVector devices;
5828
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005829 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005830 if (index >= 0) {
5831 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005832 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005833 ALOGV("%s device %s forced by patch %d", __func__,
5834 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5835 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005836 }
5837 }
5838
Dean Wheatley514b4312020-06-17 21:45:00 +10005839 // Do not retrieve engine device for outputs through MSD
5840 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5841 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5842 return outputDesc->devices();
5843 }
5844
Eric Laurent97ac8712018-07-27 18:59:02 -07005845 // Honor explicit routing requests only if no client using default routing is active on this
5846 // input: a specific app can not force routing for other apps by setting a preferred device.
5847 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005848 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005849 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005850 if (device != nullptr) {
5851 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005852 }
5853
François Gaffiea807ef92018-11-05 10:44:33 +01005854 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5855 // of setForceUse / Default Bus device here
5856 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5857 if (device != nullptr) {
5858 return DeviceVector(device);
5859 }
5860
François Gaffiec005e562018-11-06 15:04:49 +01005861 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5862 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5863 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305864 auto hasStreamActive = [&](auto stream) {
5865 return hasStream(streams, stream) && isStreamActive(stream, 0);
5866 };
Eric Laurent484e9272018-06-07 17:29:23 -07005867
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305868 auto doGetOutputDevicesForVoice = [&]() {
5869 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5870 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5871 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02005872 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5873 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305874 };
5875
5876 // With low-latency playing on speaker, music on WFD, when the first low-latency
5877 // output is stopped, getNewOutputDevices checks for a product strategy
5878 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00005879 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305880 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5881 // stream is associated to the output descriptor.
5882 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5883 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5884 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5885 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005886 // Retrieval of devices for voice DL is done on primary output profile, cannot
5887 // check the route (would force modifying configuration file for this profile)
5888 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5889 break;
5890 }
Eric Laurente552edb2014-03-10 17:42:56 -07005891 }
François Gaffiec005e562018-11-06 15:04:49 +01005892 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005893 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005894}
5895
François Gaffie11d30102018-11-02 16:09:09 +01005896sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5897 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005898{
François Gaffie11d30102018-11-02 16:09:09 +01005899 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005900
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005901 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005902 if (index >= 0) {
5903 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005904 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005905 ALOGV("getNewInputDevice() device %s forced by patch %d",
5906 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5907 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005908 }
5909 }
5910
Eric Laurent97ac8712018-07-27 18:59:02 -07005911 // Honor explicit routing requests only if no client using default routing is active on this
5912 // input: a specific app can not force routing for other apps by setting a preferred device.
5913 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005914 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5915 if (device != nullptr) {
5916 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005917 }
5918
Eric Laurentdc95a252018-04-12 12:46:56 -07005919 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005920 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005921 audio_attributes_t attributes;
5922 uid_t uid;
5923 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5924 if (topClient != nullptr) {
5925 attributes = topClient->attributes();
5926 uid = topClient->uid();
5927 } else {
5928 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5929 uid = 0;
5930 }
5931
Francois Gaffie716e1432019-01-14 16:58:59 +01005932 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5933 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005934 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005935 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005936 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005937 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005938
Eric Laurente552edb2014-03-10 17:42:56 -07005939 return device;
5940}
5941
Eric Laurent794fde22016-03-11 09:50:45 -08005942bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5943 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005944 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005945}
5946
Eric Laurente0720872014-03-11 09:30:41 -07005947audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005948 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005949 // getOutputDevicesForStream's behavior for invalid streams.
5950 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5951 // device for music stream), but we want to return the empty set.
5952 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005953 return AUDIO_DEVICE_NONE;
5954 }
François Gaffie11d30102018-11-02 16:09:09 +01005955 DeviceVector activeDevices;
5956 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005957 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5958 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005959 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005960 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005961 }
François Gaffiec005e562018-11-06 15:04:49 +01005962 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005963 devices.merge(curDevices);
5964 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005965 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005966 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005967 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005968 }
5969 }
Eric Laurente552edb2014-03-10 17:42:56 -07005970 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005971
Eric Laurentb0688d62018-08-14 15:49:18 -07005972 // Favor devices selected on active streams if any to report correct device in case of
5973 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005974 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005975 devices = activeDevices;
5976 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005977 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5978 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005979 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005980 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005981 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005982 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005983 }
jiabin9a3361e2019-10-01 09:38:30 -07005984 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5985 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005986}
5987
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005988status_t AudioPolicyManager::getDevicesForAttributes(
5989 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5990 if (devices == nullptr) {
5991 return BAD_VALUE;
5992 }
5993 // check dynamic policies but only for primary descriptors (secondary not used for audible
5994 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005995 sp<AudioPolicyMix> policyMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005996 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
5997 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005998 if (status != OK) {
5999 return status;
6000 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006001 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6002 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6003 devices->push_back(device);
6004 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006005 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006006 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6007 for (const auto& device : curDevices) {
6008 devices->push_back(device->getDeviceTypeAddr());
6009 }
6010 return NO_ERROR;
6011}
6012
Eric Laurente0720872014-03-11 09:30:41 -07006013void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006014 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006015 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006016 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006017 updateDevicesAndOutputs();
6018 break;
6019 default:
6020 break;
6021 }
6022}
6023
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006024uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006025
6026 // skip beacon mute management if a dedicated TTS output is available
6027 if (mTtsOutputAvailable) {
6028 return 0;
6029 }
6030
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006031 switch(event) {
6032 case STARTING_OUTPUT:
6033 mBeaconMuteRefCount++;
6034 break;
6035 case STOPPING_OUTPUT:
6036 if (mBeaconMuteRefCount > 0) {
6037 mBeaconMuteRefCount--;
6038 }
6039 break;
6040 case STARTING_BEACON:
6041 mBeaconPlayingRefCount++;
6042 break;
6043 case STOPPING_BEACON:
6044 if (mBeaconPlayingRefCount > 0) {
6045 mBeaconPlayingRefCount--;
6046 }
6047 break;
6048 }
6049
6050 if (mBeaconMuteRefCount > 0) {
6051 // any playback causes beacon to be muted
6052 return setBeaconMute(true);
6053 } else {
6054 // no other playback: unmute when beacon starts playing, mute when it stops
6055 return setBeaconMute(mBeaconPlayingRefCount == 0);
6056 }
6057}
6058
6059uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6060 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6061 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6062 // keep track of muted state to avoid repeating mute/unmute operations
6063 if (mBeaconMuted != mute) {
6064 // mute/unmute AUDIO_STREAM_TTS on all outputs
6065 ALOGV("\t muting %d", mute);
6066 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006067 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006068 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006069 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006070 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006071 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006072 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006073 maxLatency = latency;
6074 }
6075 }
6076 mBeaconMuted = mute;
6077 return maxLatency;
6078 }
6079 return 0;
6080}
6081
Eric Laurente0720872014-03-11 09:30:41 -07006082void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006083{
François Gaffiec005e562018-11-06 15:04:49 +01006084 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006085 mPreviousOutputs = mOutputs;
6086}
6087
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006088uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006089 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006090 uint32_t delayMs)
6091{
6092 // mute/unmute strategies using an incompatible device combination
6093 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6094 // if unmuting, unmute only after the specified delay
6095 if (outputDesc->isDuplicated()) {
6096 return 0;
6097 }
6098
6099 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006100 DeviceVector devices = outputDesc->devices();
6101 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006102
François Gaffiec005e562018-11-06 15:04:49 +01006103 auto productStrategies = mEngine->getOrderedProductStrategies();
6104 for (const auto &productStrategy : productStrategies) {
6105 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6106 DeviceVector curDevices =
6107 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6108 curDevices = curDevices.filter(outputDesc->supportedDevices());
6109 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006110 bool doMute = false;
6111
François Gaffiec005e562018-11-06 15:04:49 +01006112 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006113 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006114 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6115 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006116 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006117 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006118 }
Eric Laurent99401132014-05-07 19:48:15 -07006119 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006120 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006121 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006122 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006123 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006124 continue;
6125 }
François Gaffiec005e562018-11-06 15:04:49 +01006126 ALOGVV("%s() %s (curDevice %s)", __func__,
6127 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6128 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6129 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006130 if (mute) {
6131 // FIXME: should not need to double latency if volume could be applied
6132 // immediately by the audioflinger mixer. We must account for the delay
6133 // between now and the next time the audioflinger thread for this output
6134 // will process a buffer (which corresponds to one buffer size,
6135 // usually 1/2 or 1/4 of the latency).
6136 if (muteWaitMs < desc->latency() * 2) {
6137 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006138 }
6139 }
6140 }
6141 }
6142 }
6143 }
6144
Eric Laurent99401132014-05-07 19:48:15 -07006145 // temporary mute output if device selection changes to avoid volume bursts due to
6146 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006147 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006148 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6149 // temporary mute duration is conservatively set to 4 times the reported latency
6150 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6151 if (muteWaitMs < tempMuteWaitMs) {
6152 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006153 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006154 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6155 // make sure that we do not start the temporary mute period too early in case of
6156 // delayed device change
6157 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6158 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006159 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006160 }
6161 }
6162
Eric Laurente552edb2014-03-10 17:42:56 -07006163 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6164 if (muteWaitMs > delayMs) {
6165 muteWaitMs -= delayMs;
6166 usleep(muteWaitMs * 1000);
6167 return muteWaitMs;
6168 }
6169 return 0;
6170}
6171
François Gaffie11d30102018-11-02 16:09:09 +01006172uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6173 const DeviceVector &devices,
6174 bool force,
6175 int delayMs,
6176 audio_patch_handle_t *patchHandle,
6177 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006178{
François Gaffie11d30102018-11-02 16:09:09 +01006179 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006180 uint32_t muteWaitMs;
6181
6182 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006183 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6184 nullptr /* patchHandle */, requiresMuteCheck);
6185 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6186 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006187 return muteWaitMs;
6188 }
Eric Laurente552edb2014-03-10 17:42:56 -07006189
6190 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006191 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006192 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006193
François Gaffie11d30102018-11-02 16:09:09 +01006194 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6195
6196 if (!filteredDevices.isEmpty()) {
6197 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006198 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006199
6200 // if the outputs are not materially active, there is no need to mute.
6201 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006202 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006203 } else {
6204 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6205 muteWaitMs = 0;
6206 }
Eric Laurente552edb2014-03-10 17:42:56 -07006207
Eric Laurent79ea9582020-06-11 18:49:24 -07006208 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6209 // output profile or if new device is not supported AND previous device(s) is(are) still
6210 // available (otherwise reset device must be done on the output)
6211 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6212 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6213 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6214 // restore previous device after evaluating strategy mute state
6215 outputDesc->setDevices(prevDevices);
6216 return muteWaitMs;
6217 }
6218
Eric Laurente552edb2014-03-10 17:42:56 -07006219 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006220 // the requested device is AUDIO_DEVICE_NONE
6221 // OR the requested device is the same as current device
6222 // AND force is not specified
6223 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006224 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006225 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006226 !force && outputDesc->getPatchHandle() != 0) {
6227 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6228 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006229 return muteWaitMs;
6230 }
6231
François Gaffie11d30102018-11-02 16:09:09 +01006232 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006233
Eric Laurente552edb2014-03-10 17:42:56 -07006234 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006235 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006236 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006237 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006238 PatchBuilder patchBuilder;
6239 patchBuilder.addSource(outputDesc);
6240 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6241 for (const auto &filteredDevice : filteredDevices) {
6242 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006243 }
6244
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006245 // Add half reported latency to delayMs when muteWaitMs is null in order
6246 // to avoid disordered sequence of muting volume and changing devices.
6247 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6248 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006249 }
Eric Laurente552edb2014-03-10 17:42:56 -07006250
6251 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006252 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006253
6254 return muteWaitMs;
6255}
6256
Eric Laurentc75307b2015-03-17 15:29:32 -07006257status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006258 int delayMs,
6259 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006260{
Eric Laurent6a94d692014-05-20 11:18:06 -07006261 ssize_t index;
6262 if (patchHandle) {
6263 index = mAudioPatches.indexOfKey(*patchHandle);
6264 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006265 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006266 }
6267 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006268 return INVALID_OPERATION;
6269 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006270 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006271 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006272 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006273 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006274 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006275 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006276 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006277 return status;
6278}
6279
6280status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006281 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006282 bool force,
6283 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006284{
6285 status_t status = NO_ERROR;
6286
Eric Laurent1f2f2232014-06-02 12:01:23 -07006287 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006288 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6289 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006290
François Gaffie11d30102018-11-02 16:09:09 +01006291 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006292 PatchBuilder patchBuilder;
6293 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006294 // AUDIO_SOURCE_HOTWORD is for internal use only:
6295 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006296 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6297 auto result = usecase;
6298 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6299 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6300 }
6301 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006302 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006303 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006304 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006305 }
6306 }
6307 return status;
6308}
6309
Eric Laurent6a94d692014-05-20 11:18:06 -07006310status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6311 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006312{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006313 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006314 ssize_t index;
6315 if (patchHandle) {
6316 index = mAudioPatches.indexOfKey(*patchHandle);
6317 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006318 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006319 }
6320 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006321 return INVALID_OPERATION;
6322 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006323 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006324 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006325 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006326 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006327 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006328 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006329 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006330 return status;
6331}
6332
François Gaffie11d30102018-11-02 16:09:09 +01006333sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006334 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006335 audio_format_t& format,
6336 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006337 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006338{
6339 // Choose an input profile based on the requested capture parameters: select the first available
6340 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006341 //
6342 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6343 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006344
Glenn Kasten730b9262018-03-29 15:01:26 -07006345 sp<IOProfile> firstInexact;
6346 uint32_t updatedSamplingRate = 0;
6347 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6348 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006349 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006350 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006351 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006352 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006353 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006354 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006355 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006356 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006357 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006358 &channelMask /*updatedChannelMask*/,
6359 // FIXME ugly cast
6360 (audio_output_flags_t) flags,
6361 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006362 return profile;
6363 }
François Gaffie11d30102018-11-02 16:09:09 +01006364 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006365 samplingRate,
6366 &updatedSamplingRate,
6367 format,
6368 &updatedFormat,
6369 channelMask,
6370 &updatedChannelMask,
6371 // FIXME ugly cast
6372 (audio_output_flags_t) flags,
6373 false /*exactMatchRequiredForInputFlags*/)) {
6374 firstInexact = profile;
6375 }
6376
Eric Laurente552edb2014-03-10 17:42:56 -07006377 }
6378 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006379 if (firstInexact != nullptr) {
6380 samplingRate = updatedSamplingRate;
6381 format = updatedFormat;
6382 channelMask = updatedChannelMask;
6383 return firstInexact;
6384 }
Eric Laurente552edb2014-03-10 17:42:56 -07006385 return NULL;
6386}
6387
François Gaffieaaac0fd2018-11-22 17:56:39 +01006388float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6389 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006390 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006391 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006392{
jiabin9a3361e2019-10-01 09:38:30 -07006393 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006394
6395 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6396 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6397 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6398 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006399 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6400 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6401 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6402 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006403 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006404
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006405 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006406 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6407 mOutputs.isActive(ringVolumeSrc, 0)) {
6408 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006409 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006410 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006411 }
6412
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006413 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006414 if ((volumeSource != callVolumeSrc && (isInCall() ||
6415 mOutputs.isActiveLocally(callVolumeSrc))) &&
6416 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6417 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6418 volumeSource == alarmVolumeSrc ||
6419 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6420 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6421 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006422 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006423 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006424 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006425 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006426 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006427 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006428 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6429 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6430 // programmatically muted.
6431 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6432 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6433 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006434 bool exemptFromCapping =
6435 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6436 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006437 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6438 volumeSource, volumeDb);
6439 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006440 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6441 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6442 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006443 }
6444 }
Eric Laurente552edb2014-03-10 17:42:56 -07006445 // if a headset is connected, apply the following rules to ring tones and notifications
6446 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006447 // - always attenuate notifications volume by 6dB
6448 // - attenuate ring tones volume by 6dB unless music is not playing and
6449 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006450 // - if music is playing, always limit the volume to current music volume,
6451 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006452 if (!Intersection(deviceTypes,
6453 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6454 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006455 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6456 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006457 ((volumeSource == alarmVolumeSrc ||
6458 volumeSource == ringVolumeSrc) ||
6459 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6460 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6461 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6462 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6463 curves.canBeMuted()) {
6464
Eric Laurente552edb2014-03-10 17:42:56 -07006465 // when the phone is ringing we must consider that music could have been paused just before
6466 // by the music application and behave as if music was active if the last music track was
6467 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006468 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006469 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006470 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006471 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006472 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6473 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006474 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006475 float musicVolDb = computeVolume(musicCurves,
6476 musicVolumeSrc,
6477 musicCurves.getVolumeIndex(musicDevice),
6478 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006479 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6480 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6481 if (volumeDb > minVolDb) {
6482 volumeDb = minVolDb;
6483 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006484 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006485 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6486 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6487 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006488 // on A2DP, also ensure notification volume is not too low compared to media when
6489 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006490 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006491 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006492 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6493 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006494 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6495 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006496 }
6497 }
jiabin9a3361e2019-10-01 09:38:30 -07006498 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006499 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006500 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006501 }
6502 }
6503
François Gaffie43c73442018-11-08 08:21:55 +01006504 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006505}
6506
Eric Laurent3839bc02018-07-10 18:33:34 -07006507int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006508 VolumeSource fromVolumeSource,
6509 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006510{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006511 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006512 return srcIndex;
6513 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006514 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6515 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006516 float minSrc = (float)srcCurves.getVolumeIndexMin();
6517 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6518 float minDst = (float)dstCurves.getVolumeIndexMin();
6519 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006520
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006521 // preserve mute request or correct range
6522 if (srcIndex < minSrc) {
6523 if (srcIndex == 0) {
6524 return 0;
6525 }
6526 srcIndex = minSrc;
6527 } else if (srcIndex > maxSrc) {
6528 srcIndex = maxSrc;
6529 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006530 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6531}
6532
François Gaffieaaac0fd2018-11-22 17:56:39 +01006533status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6534 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006535 int index,
6536 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006537 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006538 int delayMs,
6539 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006540{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006541 // do not change actual attributes volume if the attributes is muted
6542 if (outputDesc->isMuted(volumeSource)) {
6543 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6544 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006545 return NO_ERROR;
6546 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006547 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6548 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6549 bool isVoiceVolSrc = callVolSrc == volumeSource;
6550 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6551
Eric Laurent2517af32020-11-25 15:31:27 +01006552 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006553 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006554 // if sco and call follow same curves, bypass forceUseForComm
6555 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006556 ((isVoiceVolSrc && isScoRequested) ||
6557 (isBtScoVolSrc && !isScoRequested))) {
6558 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6559 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006560 // Do not return an error here as AudioService will always set both voice call
6561 // and bluetooth SCO volumes due to stream aliasing.
6562 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006563 }
jiabin9a3361e2019-10-01 09:38:30 -07006564 if (deviceTypes.empty()) {
6565 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006566 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006567
jiabin9a3361e2019-10-01 09:38:30 -07006568 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6569 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006570 // Force VoIP volume to max for bluetooth SCO device except if muted
6571 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006572 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006573 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006574 }
jiabin9a3361e2019-10-01 09:38:30 -07006575 outputDesc->setVolume(
6576 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006577
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006578 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006579 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006580 // 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 +01006581 if (isVoiceVolSrc) {
6582 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006583 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006584 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006585 }
Eric Laurent18fba842016-03-31 14:41:26 -07006586 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006587 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6588 mLastVoiceVolume = voiceVolume;
6589 }
6590 }
Eric Laurente552edb2014-03-10 17:42:56 -07006591 return NO_ERROR;
6592}
6593
Eric Laurentc75307b2015-03-17 15:29:32 -07006594void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006595 const DeviceTypeSet& deviceTypes,
6596 int delayMs,
6597 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006598{
jiabincd510522020-01-22 09:40:55 -08006599 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006600 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6601 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6602 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006603 curves.getVolumeIndex(deviceTypes),
6604 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006605 }
6606}
6607
François Gaffiec005e562018-11-06 15:04:49 +01006608void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6609 bool on,
6610 const sp<AudioOutputDescriptor>& outputDesc,
6611 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006612 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006613{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006614 std::vector<VolumeSource> sourcesToMute;
6615 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6616 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6617 toString(attributes).c_str(), on, outputDesc->getId());
6618 VolumeSource source = toVolumeSource(attributes);
6619 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6620 sourcesToMute.push_back(source);
6621 }
Eric Laurente552edb2014-03-10 17:42:56 -07006622 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006623 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006624 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006625 }
6626
Eric Laurente552edb2014-03-10 17:42:56 -07006627}
6628
François Gaffieaaac0fd2018-11-22 17:56:39 +01006629void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6630 bool on,
6631 const sp<AudioOutputDescriptor>& outputDesc,
6632 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006633 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006634{
jiabin9a3361e2019-10-01 09:38:30 -07006635 if (deviceTypes.empty()) {
6636 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006637 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006638 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006639 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006640 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006641 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006642 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6643 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6644 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006645 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006646 }
6647 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006648 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6649 // ignored
6650 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006651 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006652 if (!outputDesc->isMuted(volumeSource)) {
6653 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006654 return;
6655 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006656 if (outputDesc->decMuteCount(volumeSource) == 0) {
6657 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006658 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006659 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006660 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006661 delayMs);
6662 }
6663 }
6664}
6665
François Gaffie53615e22015-03-19 09:24:12 +01006666bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6667{
François Gaffiec005e562018-11-06 15:04:49 +01006668 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006669 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6670 return true;
6671 }
6672
6673 // has known usage?
6674 switch (paa->usage) {
6675 case AUDIO_USAGE_UNKNOWN:
6676 case AUDIO_USAGE_MEDIA:
6677 case AUDIO_USAGE_VOICE_COMMUNICATION:
6678 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6679 case AUDIO_USAGE_ALARM:
6680 case AUDIO_USAGE_NOTIFICATION:
6681 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6682 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6683 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6684 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6685 case AUDIO_USAGE_NOTIFICATION_EVENT:
6686 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6687 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6688 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6689 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006690 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006691 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006692 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006693 case AUDIO_USAGE_EMERGENCY:
6694 case AUDIO_USAGE_SAFETY:
6695 case AUDIO_USAGE_VEHICLE_STATUS:
6696 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006697 break;
6698 default:
6699 return false;
6700 }
6701 return true;
6702}
6703
François Gaffie2110e042015-03-24 08:41:51 +01006704audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6705{
6706 return mEngine->getForceUse(usage);
6707}
6708
6709bool AudioPolicyManager::isInCall()
6710{
6711 return isStateInCall(mEngine->getPhoneState());
6712}
6713
6714bool AudioPolicyManager::isStateInCall(int state)
6715{
6716 return is_state_in_call(state);
6717}
6718
Eric Laurent74b71512019-11-06 17:21:57 -08006719bool AudioPolicyManager::isCallAudioAccessible()
6720{
6721 audio_mode_t mode = mEngine->getPhoneState();
6722 return (mode == AUDIO_MODE_IN_CALL)
6723 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6724 || (mode == AUDIO_MODE_CALL_SCREEN);
6725}
6726
Eric Laurentd60560a2015-04-10 11:31:20 -07006727void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6728{
6729 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006730 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006731 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006732 sourceDesc->sinkDevice()->equals(deviceDesc))
6733 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006734 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006735 }
6736 }
6737
6738 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6739 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6740 bool release = false;
6741 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6742 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6743 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6744 source->ext.device.type == deviceDesc->type()) {
6745 release = true;
6746 }
6747 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006748 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006749 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6750 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6751 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006752 sink->ext.device.type == deviceDesc->type() &&
6753 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6754 || strncmp(sink->ext.device.address, address,
6755 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006756 release = true;
6757 }
6758 }
6759 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006760 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6761 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006762 }
6763 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006764
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006765 mInputs.clearSessionRoutesForDevice(deviceDesc);
6766
Francois Gaffie716e1432019-01-14 16:58:59 +01006767 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006768}
6769
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006770void AudioPolicyManager::modifySurroundFormats(
6771 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006772 std::unordered_set<audio_format_t> enforcedSurround(
6773 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006774 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6775 for (const auto& pair : mConfig.getSurroundFormats()) {
6776 allSurround.insert(pair.first);
6777 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6778 }
Phil Burk09bc4612016-02-24 15:58:15 -08006779
6780 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6781 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006782 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006783 // This is the resulting set of formats depending on the surround mode:
6784 // 'all surround' = allSurround
6785 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6786 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6787 // 'manual surround' = mManualSurroundFormats
6788 // AUTO: formats v 'enforced surround'
6789 // ALWAYS: formats v 'all surround' v 'enforced surround'
6790 // NEVER: formats ^ 'non-surround'
6791 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006792
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006793 std::unordered_set<audio_format_t> formatSet;
6794 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6795 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006796 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006797 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006798 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006799 formatSet.insert(*formatIter);
6800 }
6801 }
6802 } else {
6803 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6804 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006805 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006806
jiabin81772902018-04-02 17:52:27 -07006807 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006808 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006809 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6810 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6811 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006812 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006813 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6815 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006816 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006817 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006818 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006819 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006820 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006821 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006822}
6823
jiabin06e4bab2019-07-29 10:13:34 -07006824void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6825 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006826 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6827 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6828
6829 // If NEVER, then remove support for channelMasks > stereo.
6830 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006831 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6832 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006833 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006834 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006835 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006836 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006837 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006838 }
6839 }
jiabin81772902018-04-02 17:52:27 -07006840 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6841 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6842 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006843 bool supports5dot1 = false;
6844 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006845 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006846 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6847 supports5dot1 = true;
6848 break;
6849 }
6850 }
6851 // If not then add 5.1 support.
6852 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006853 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006854 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006855 }
Phil Burk09bc4612016-02-24 15:58:15 -08006856 }
6857}
6858
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006859void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006860 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006861 AudioProfileVector &profiles)
6862{
6863 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006864 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006865
François Gaffie112b0af2015-11-19 16:13:25 +01006866 // Format MUST be checked first to update the list of AudioProfile
6867 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006868 reply = mpClientInterface->getParameters(
6869 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006870 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006871 AudioParameter repliedParameters(reply);
6872 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006873 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006874 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6875 return;
6876 }
Phil Burk09bc4612016-02-24 15:58:15 -08006877 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006878 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006879 if (device == AUDIO_DEVICE_OUT_HDMI
6880 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006881 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006882 }
jiabin3e277cc2019-09-10 14:27:34 -07006883 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006884 }
François Gaffie112b0af2015-11-19 16:13:25 +01006885
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006886 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006887 ChannelMaskSet channelMasks;
6888 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006889 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006890 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006891
6892 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006893 reply = mpClientInterface->getParameters(
6894 ioHandle,
6895 requestedParameters.toString() + ";" +
6896 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006897 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006898 AudioParameter repliedParameters(reply);
6899 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006900 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006901 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006902 }
6903 }
6904 if (profiles.hasDynamicChannelsFor(format)) {
6905 reply = mpClientInterface->getParameters(ioHandle,
6906 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006907 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006908 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006909 AudioParameter repliedParameters(reply);
6910 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006911 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006912 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006913 if (device == AUDIO_DEVICE_OUT_HDMI
6914 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006915 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006916 }
François Gaffie112b0af2015-11-19 16:13:25 +01006917 }
6918 }
jiabin3e277cc2019-09-10 14:27:34 -07006919 addDynamicAudioProfileAndSort(
6920 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006921 }
6922}
Eric Laurentd60560a2015-04-10 11:31:20 -07006923
Mikhail Naganovdc769682018-05-04 15:34:08 -07006924status_t AudioPolicyManager::installPatch(const char *caller,
6925 audio_patch_handle_t *patchHandle,
6926 AudioIODescriptorInterface *ioDescriptor,
6927 const struct audio_patch *patch,
6928 int delayMs)
6929{
6930 ssize_t index = mAudioPatches.indexOfKey(
6931 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6932 *patchHandle : ioDescriptor->getPatchHandle());
6933 sp<AudioPatch> patchDesc;
6934 status_t status = installPatch(
6935 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6936 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006937 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006938 }
6939 return status;
6940}
6941
6942status_t AudioPolicyManager::installPatch(const char *caller,
6943 ssize_t index,
6944 audio_patch_handle_t *patchHandle,
6945 const struct audio_patch *patch,
6946 int delayMs,
6947 uid_t uid,
6948 sp<AudioPatch> *patchDescPtr)
6949{
6950 sp<AudioPatch> patchDesc;
6951 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6952 if (index >= 0) {
6953 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006954 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006955 }
6956
6957 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6958 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6959 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6960 if (status == NO_ERROR) {
6961 if (index < 0) {
6962 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006963 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006964 } else {
6965 patchDesc->mPatch = *patch;
6966 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006967 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006968 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006969 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006970 }
6971 nextAudioPortGeneration();
6972 mpClientInterface->onAudioPatchListUpdate();
6973 }
6974 if (patchDescPtr) *patchDescPtr = patchDesc;
6975 return status;
6976}
6977
jiabinbce0c1d2020-10-05 11:20:18 -07006978bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6979{
6980 const TrackClientVector activeClients = output->getActiveClients();
6981 if (activeClients.empty()) {
6982 return true;
6983 }
6984 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6985 if (index < 0) {
6986 ALOGE("%s, no audio patch found while there are active clients on output %d",
6987 __func__, output->getId());
6988 return false;
6989 }
6990 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6991 DeviceVector routedDevices;
6992 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6993 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6994 patchDesc->mPatch.sinks[i].id);
6995 if (device == nullptr) {
6996 ALOGE("%s, no audio device found with id(%d)",
6997 __func__, patchDesc->mPatch.sinks[i].id);
6998 return false;
6999 }
7000 routedDevices.add(device);
7001 }
7002 for (const auto& client : activeClients) {
7003 // TODO: b/175343099 only travel the valid client
7004 sp<DeviceDescriptor> preferredDevice =
7005 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7006 if (mEngine->getOutputDevicesForAttributes(
7007 client->attributes(), preferredDevice, false) == routedDevices) {
7008 return false;
7009 }
7010 }
7011 return true;
7012}
7013
7014sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7015 const sp<IOProfile>& profile, const DeviceVector& devices)
7016{
7017 for (const auto& device : devices) {
7018 // TODO: This should be checking if the profile supports the device combo.
7019 if (!profile->supportsDevice(device)) {
7020 return nullptr;
7021 }
7022 }
7023 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7024 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
7025 status_t status = desc->open(nullptr, devices,
7026 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7027 if (status != NO_ERROR) {
7028 return nullptr;
7029 }
7030
7031 // Here is where the out_set_parameters() for card & device gets called
7032 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7033 const audio_devices_t deviceType = device->type();
7034 const String8 &address = String8(device->address().c_str());
7035 if (!address.isEmpty()) {
7036 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7037 mpClientInterface->setParameters(output, String8(param));
7038 free(param);
7039 }
7040 updateAudioProfiles(device, output, profile->getAudioProfiles());
7041 if (!profile->hasValidAudioProfile()) {
7042 ALOGW("%s() missing param", __func__);
7043 desc->close();
7044 return nullptr;
7045 } else if (profile->hasDynamicAudioProfile()) {
7046 desc->close();
7047 output = AUDIO_IO_HANDLE_NONE;
7048 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7049 profile->pickAudioProfile(
7050 config.sample_rate, config.channel_mask, config.format);
7051 config.offload_info.sample_rate = config.sample_rate;
7052 config.offload_info.channel_mask = config.channel_mask;
7053 config.offload_info.format = config.format;
7054
7055 status = desc->open(&config, devices,
7056 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7057 if (status != NO_ERROR) {
7058 return nullptr;
7059 }
7060 }
7061
7062 addOutput(output, desc);
7063 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7064 sp<AudioPolicyMix> policyMix;
7065 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7066 policyMix->setOutput(desc);
7067 desc->mPolicyMix = policyMix;
7068 } else {
7069 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7070 address.string());
7071 }
7072
7073 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7074 // no duplicated output for direct outputs and
7075 // outputs used by dynamic policy mixes
7076 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7077
7078 //TODO: configure audio effect output stage here
7079
7080 // open a duplicating output thread for the new output and the primary output
7081 sp<SwAudioOutputDescriptor> dupOutputDesc =
7082 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7083 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7084 if (status == NO_ERROR) {
7085 // add duplicated output descriptor
7086 addOutput(duplicatedOutput, dupOutputDesc);
7087 } else {
7088 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7089 mPrimaryOutput->mIoHandle, output);
7090 desc->close();
7091 removeOutput(output);
7092 nextAudioPortGeneration();
7093 return nullptr;
7094 }
7095 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007096 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7097 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7098 mPrimaryOutput = desc;
7099 }
jiabinbce0c1d2020-10-05 11:20:18 -07007100 return desc;
7101}
7102
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007103} // namespace android