blob: 1525a6ff1deefca5507a056f22e9e527a6f73103 [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();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001054 if (deviceDesc != nullptr
1055 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001056 audio_io_handle_t newOutput;
1057 status = openDirectOutput(
1058 *stream, session, config,
1059 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1060 DeviceVector(deviceDesc), &newOutput);
1061 if (status != NO_ERROR) {
1062 policyDesc = nullptr;
1063 } else {
1064 policyDesc = mOutputs.valueFor(newOutput);
1065 primaryMix->setOutput(policyDesc);
1066 }
1067 }
1068 if (policyDesc != nullptr) {
1069 policyDesc->mPolicyMix = primaryMix;
1070 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001071 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001072
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001073 ALOGV("getOutputForAttr() returns output %d", *output);
1074 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1075 *outputType = API_OUT_MIX_PLAYBACK;
1076 } else {
1077 *outputType = API_OUTPUT_LEGACY;
1078 }
1079 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001080 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001081 }
François Gaffiec005e562018-11-06 15:04:49 +01001082 // Virtual sources must always be dynamicaly or explicitly routed
1083 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1084 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1085 return BAD_VALUE;
1086 }
1087 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1088 // in order to let the choice of the order to future vendor engine
1089 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001090
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001091 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001092 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001093 }
1094
Nadav Barb2f18162018-07-18 13:01:53 +03001095 // Set incall music only if device was explicitly set, and fallback to the device which is
1096 // chosen by the engine if not.
1097 // FIXME: provide a more generic approach which is not device specific and move this back
1098 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001099 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001100 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001101 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001102 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001103 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001104 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001105 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001106 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001107 }
1108 }
1109
François Gaffiec005e562018-11-06 15:04:49 +01001110 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1111 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1112 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001113
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001114 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001115 if (!msdDevices.isEmpty()) {
1116 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001117 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001118 ALOGV("%s() Using MSD devices %s instead of devices %s",
1119 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001120 } else {
1121 *output = AUDIO_IO_HANDLE_NONE;
1122 }
1123 }
1124 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabine375d412019-02-26 12:54:53 -08001125 *output = getOutputForDevices(outputDevices, session, *stream, config,
Eric Laurent42984412019-05-09 17:57:03 -07001126 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001127 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001128 if (*output == AUDIO_IO_HANDLE_NONE) {
1129 return INVALID_OPERATION;
1130 }
Paul McLeanaa981192015-03-21 09:55:15 -07001131
François Gaffiec005e562018-11-06 15:04:49 +01001132 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001133 for (auto &outputDevice : outputDevices) {
1134 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1135 *selectedDeviceId = outputDevice->getId();
1136 break;
1137 }
1138 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001139
Eric Laurent8a1095a2019-11-08 14:44:16 -08001140 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1141 *outputType = API_OUTPUT_TELEPHONY_TX;
1142 } else {
1143 *outputType = API_OUTPUT_LEGACY;
1144 }
1145
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1147
1148 return NO_ERROR;
1149}
1150
1151status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1152 audio_io_handle_t *output,
1153 audio_session_t session,
1154 audio_stream_type_t *stream,
Svet Ganov33761132021-05-13 22:51:08 +00001155 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 const audio_config_t *config,
1157 audio_output_flags_t *flags,
1158 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001159 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001160 std::vector<audio_io_handle_t> *secondaryOutputs,
1161 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162{
1163 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1164 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1165 return INVALID_OPERATION;
1166 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001167 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov33761132021-05-13 22:51:08 +00001168 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001169 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001170 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001171 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001173 const sp<DeviceDescriptor> requestedDevice =
1174 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1175
1176 // Prevent from storing invalid requested device id in clients
1177 const audio_port_handle_t sanitizedRequestedPortId =
1178 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1179 *selectedDeviceId = sanitizedRequestedPortId;
1180
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001181 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001183 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001184 if (status != NO_ERROR) {
1185 return status;
1186 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001187 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001188 if (secondaryOutputs != nullptr) {
1189 for (auto &secondaryMix : secondaryMixes) {
1190 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1191 if (outputDesc != nullptr &&
1192 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1193 secondaryOutputs->push_back(outputDesc->mIoHandle);
1194 weakSecondaryOutputDescs.push_back(outputDesc);
1195 }
1196 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001197 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001198
Eric Laurent8fc147b2018-07-22 19:13:55 -07001199 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001200 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001201 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001202 };
jiabin4ef93452019-09-10 14:29:54 -07001203 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001204
Eric Laurentc209fe42020-06-05 18:11:23 -07001205 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001206 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001208 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001209 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001210 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001212 std::move(weakSecondaryOutputDescs),
1213 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001214 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001215
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001216 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1217 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001218
Eric Laurente83b55d2014-11-14 10:06:21 -08001219 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001220}
1221
Eric Laurentc529cf62020-04-17 18:19:10 -07001222status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1223 audio_session_t session,
1224 const audio_config_t *config,
1225 audio_output_flags_t flags,
1226 const DeviceVector &devices,
1227 audio_io_handle_t *output) {
1228
1229 *output = AUDIO_IO_HANDLE_NONE;
1230
1231 // skip direct output selection if the request can obviously be attached to a mixed output
1232 // and not explicitly requested
1233 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1234 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1235 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1236 return NAME_NOT_FOUND;
1237 }
1238
1239 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1240 // This prevents creating an offloaded track and tearing it down immediately after start
1241 // when audioflinger detects there is an active non offloadable effect.
1242 // FIXME: We should check the audio session here but we do not have it in this context.
1243 // This may prevent offloading in rare situations where effects are left active by apps
1244 // in the background.
1245 sp<IOProfile> profile;
1246 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1247 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1248 profile = getProfileForOutput(
1249 devices, config->sample_rate, config->format, config->channel_mask,
1250 flags, true /* directOnly */);
1251 }
1252
1253 if (profile == nullptr) {
1254 return NAME_NOT_FOUND;
1255 }
1256
1257 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1258 for (size_t i = 0; i < mOutputs.size(); i++) {
1259 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1260 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1261 // reuse direct output if currently open by the same client
1262 // and configured with same parameters
1263 if ((config->sample_rate == desc->getSamplingRate()) &&
1264 (config->format == desc->getFormat()) &&
1265 (config->channel_mask == desc->getChannelMask()) &&
1266 (session == desc->mDirectClientSession)) {
1267 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001268 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 mOutputs.keyAt(i), session);
1270 *output = mOutputs.keyAt(i);
1271 return NO_ERROR;
1272 }
1273 }
1274 }
1275
1276 if (!profile->canOpenNewIo()) {
1277 return NAME_NOT_FOUND;
1278 }
1279
1280 sp<SwAudioOutputDescriptor> outputDesc =
1281 new SwAudioOutputDescriptor(profile, mpClientInterface);
1282
Michael Chan6fb34492020-12-08 15:44:49 +11001283 // An MSD patch may be using the only output stream that can service this request. Release
1284 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001285 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001286
1287 status_t status = outputDesc->open(config, devices, stream, flags, output);
1288
1289 // only accept an output with the requested parameters
1290 if (status != NO_ERROR ||
1291 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1292 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1293 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1294 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1295 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1296 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1297 config->channel_mask, outputDesc->getChannelMask());
1298 if (*output != AUDIO_IO_HANDLE_NONE) {
1299 outputDesc->close();
1300 }
1301 // fall back to mixer output if possible when the direct output could not be open
1302 if (audio_is_linear_pcm(config->format) &&
1303 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1304 return NAME_NOT_FOUND;
1305 }
1306 *output = AUDIO_IO_HANDLE_NONE;
1307 return BAD_VALUE;
1308 }
1309 outputDesc->mDirectOpenCount = 1;
1310 outputDesc->mDirectClientSession = session;
1311
1312 addOutput(*output, outputDesc);
1313 mPreviousOutputs = mOutputs;
1314 ALOGV("%s returns new direct output %d", __func__, *output);
1315 mpClientInterface->onAudioPortListUpdate();
1316 return NO_ERROR;
1317}
1318
François Gaffie11d30102018-11-02 16:09:09 +01001319audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1320 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001321 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001322 audio_stream_type_t stream,
Eric Laurentfe231122017-11-17 17:48:06 -08001323 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001324 audio_output_flags_t *flags,
1325 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001326{
Andy Hungc88b0642018-04-27 15:42:35 -07001327 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001328
jiabine375d412019-02-26 12:54:53 -08001329 // Discard haptic channel mask when forcing muting haptic channels.
1330 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001331 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1332 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001333
Eric Laurente552edb2014-03-10 17:42:56 -07001334 // open a direct output if required by specified parameters
1335 //force direct flag if offload flag is set: offloading implies a direct output stream
1336 // and all common behaviors are driven by checking only the direct flag
1337 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001338 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1339 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001340 }
Nadav Bar766fb022018-01-07 12:18:03 +02001341 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1342 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001343 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001344 // only allow deep buffering for music stream type
1345 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001346 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001347 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001348 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001349 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1350 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001351 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001352 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001353 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001354 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001355 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001356 audio_is_linear_pcm(config->format) &&
1357 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001358 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001359 AUDIO_OUTPUT_FLAG_DIRECT);
1360 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001361 }
Eric Laurente552edb2014-03-10 17:42:56 -07001362
Eric Laurentc529cf62020-04-17 18:19:10 -07001363 audio_config_t directConfig = *config;
1364 directConfig.channel_mask = channelMask;
1365 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1366 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001367 return output;
1368 }
1369
Eric Laurent14cbfca2016-03-17 09:42:16 -07001370 // A request for HW A/V sync cannot fallback to a mixed output because time
1371 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001372 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001373 return AUDIO_IO_HANDLE_NONE;
1374 }
1375
Eric Laurente552edb2014-03-10 17:42:56 -07001376 // ignoring channel mask due to downmix capability in mixer
1377
1378 // open a non direct output
1379
1380 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001381 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001382 // get which output is suitable for the specified stream. The actual
1383 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001384 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001385
Eric Laurent8838a382014-09-08 16:44:28 -07001386 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001387 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001388 output = selectOutput(
1389 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001390 }
François Gaffie11d30102018-11-02 16:09:09 +01001391 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001392 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001393 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001394
Eric Laurente552edb2014-03-10 17:42:56 -07001395 return output;
1396}
1397
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001398sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001399 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1400 mAvailableInputDevices);
1401 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1402}
1403
1404DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1405 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1406 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001407}
1408
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001409const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001410 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001411 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1412 if (msdModule != 0) {
1413 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1414 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1415 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1416 const struct audio_port_config *source = &patch->mPatch.sources[j];
1417 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1418 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001419 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001420 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001421 }
1422 }
1423 }
1424 return msdPatches;
1425}
1426
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001427status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1428 const InputProfileCollection &inputProfiles,
1429 const OutputProfileCollection &outputProfiles,
1430 const sp<DeviceDescriptor> &sourceDevice,
1431 const sp<DeviceDescriptor> &sinkDevice,
1432 AudioProfileVector& sourceProfiles,
1433 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001434 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001435 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001436 return NO_INIT;
1437 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001438 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001439 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001440 return NO_INIT;
1441 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001442 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001443 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1444 inProfile->supportsDevice(sourceDevice)) {
1445 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001446 }
1447 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001448 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001449 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001450 outProfile->supportsDevice(sinkDevice)) {
1451 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001452 }
1453 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001454 return NO_ERROR;
1455}
1456
1457status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1458 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1459 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1460{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001461 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001462 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1463 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1464 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001465 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001466 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1467 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001468 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001469 }
1470 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1471 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1472 sinkConfig->format = bestSinkConfig.format;
1473 // For encoded streams force direct flag to prevent downstream mixing.
1474 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1475 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001476 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1477 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001478 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001479 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1480 // raw and IEC61937 framed streams.
1481 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1482 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1483 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001484 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1485 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1486 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1487 sourceConfig->format = bestSinkConfig.format;
1488 // Copy input stream directly without any processing (e.g. resampling).
1489 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1490 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1491 if (hwAvSync) {
1492 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1493 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1494 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1495 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1496 }
1497 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1498 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1499 sinkConfig->config_mask |= config_mask;
1500 sourceConfig->config_mask |= config_mask;
1501 return NO_ERROR;
1502}
1503
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001504PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1505 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001506{
1507 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001508 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1509 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1510 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1511 if (deviceModule == nullptr) {
1512 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1513 return patchBuilder;
1514 }
1515 const InputProfileCollection inputProfiles = msdIsSource ?
1516 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1517 const OutputProfileCollection outputProfiles = msdIsSource ?
1518 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1519
1520 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1521 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1522 device : getMsdAudioOutDevices().itemAt(0);
1523 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1524
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001525 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1526 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001527 AudioProfileVector sourceProfiles;
1528 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001529 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1530 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001531 for (auto hwAvSync : { true, false }) {
1532 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1533 sourceProfiles, sinkProfiles) != NO_ERROR) {
1534 continue;
1535 }
1536 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1537 &sinkConfig) == NO_ERROR) {
1538 // Found a matching config. Re-create PatchBuilder with this config.
1539 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1540 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001541 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001543 " supporting PCM format conversion.", __func__);
1544 return patchBuilder;
1545}
1546
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001547status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001548 DeviceVector devices;
1549 if (outputDevices != nullptr && outputDevices->size() > 0) {
1550 devices.add(*outputDevices);
1551 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001552 // Use media strategy for unspecified output device. This should only
1553 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1554 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001555 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001556 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001557 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001558 }
Michael Chan6fb34492020-12-08 15:44:49 +11001559 std::vector<PatchBuilder> patchesToCreate;
1560 for (auto i = 0u; i < devices.size(); ++i) {
1561 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001562 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001563 }
1564 // Retain only the MSD patches associated with outputDevices request.
1565 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001566 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001567 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1568 auto retainedPatch = false;
1569 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1570 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1571 patchesToRemove.removeItemsAt(i);
1572 retainedPatch = true;
1573 break;
1574 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001575 }
Michael Chan6fb34492020-12-08 15:44:49 +11001576 if (retainedPatch) {
1577 it = patchesToCreate.erase(it);
1578 continue;
1579 }
1580 ++it;
1581 }
1582 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1583 return NO_ERROR;
1584 }
1585 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1586 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001587 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001588 }
Michael Chan6fb34492020-12-08 15:44:49 +11001589 status_t status = NO_ERROR;
1590 for (const auto &p : patchesToCreate) {
1591 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1592 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1593 char message[256];
1594 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1595 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1596 currStatus == NO_ERROR ? "Success" : "Error",
1597 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1598 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1599 if (currStatus == NO_ERROR) {
1600 ALOGD("%s", message);
1601 } else {
1602 ALOGE("%s", message);
1603 if (status == NO_ERROR) {
1604 status = currStatus;
1605 }
1606 }
1607 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001608 return status;
1609}
1610
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1612 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001613 for (size_t i = 0; i < msdPatches.size(); i++) {
1614 const auto& patch = msdPatches[i];
1615 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1616 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1617 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1618 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1619 releaseAudioPatch(patch->getHandle(), mUidCached);
1620 break;
1621 }
1622 }
1623 }
1624}
1625
Eric Laurente0720872014-03-11 09:30:41 -07001626audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001627 audio_output_flags_t flags,
1628 audio_format_t format,
1629 audio_channel_mask_t channelMask,
1630 uint32_t samplingRate,
1631 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001632{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001633 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1634 "%s called with format %#x", __func__, format);
1635
jiabinebb6af42020-06-09 17:31:17 -07001636 // Return the output that haptic-generating attached to when 1) session id is specified,
1637 // 2) haptic-generating effect exists for given session id and 3) the output that
1638 // haptic-generating effect attached to is in given outputs.
1639 if (sessionId != AUDIO_SESSION_NONE) {
1640 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1641 sessionId, FX_IID_HAPTICGENERATOR);
1642 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1643 return hapticGeneratingOutput;
1644 }
1645 }
1646
Eric Laurent16c66dd2019-05-01 17:54:10 -07001647 // Flags disqualifying an output: the match must happen before calling selectOutput()
1648 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1649 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1650
1651 // Flags expressing a functional request: must be honored in priority over
1652 // other criteria
1653 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1654 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1655 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1656 // Flags expressing a performance request: have lower priority than serving
1657 // requested sampling rate or channel mask
1658 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1659 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1660 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1661
1662 const audio_output_flags_t functionalFlags =
1663 (audio_output_flags_t)(flags & kFunctionalFlags);
1664 const audio_output_flags_t performanceFlags =
1665 (audio_output_flags_t)(flags & kPerformanceFlags);
1666
1667 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1668
Eric Laurente552edb2014-03-10 17:42:56 -07001669 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001670 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001671 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001672 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001673 // 2: the output with the highest number of requested functional flags
1674 // 3: the output supporting the exact channel mask
1675 // 4: the output with a higher channel count than requested
1676 // 5: the output with a higher sampling rate than requested
1677 // 6: the output with the highest number of requested performance flags
1678 // 7: the output with the bit depth the closest to the requested one
1679 // 8: the primary output
1680 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001681
Eric Laurent16c66dd2019-05-01 17:54:10 -07001682 // matching criteria values in priority order for best matching output so far
1683 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001684
Eric Laurent16c66dd2019-05-01 17:54:10 -07001685 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1686 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1687 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001688
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001689 for (audio_io_handle_t output : outputs) {
1690 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001691 // matching criteria values in priority order for current output
1692 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001693
Eric Laurent16c66dd2019-05-01 17:54:10 -07001694 if (outputDesc->isDuplicated()) {
1695 continue;
1696 }
1697 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1698 continue;
1699 }
Eric Laurent8838a382014-09-08 16:44:28 -07001700
Eric Laurent16c66dd2019-05-01 17:54:10 -07001701 // If haptic channel is specified, use the haptic output if present.
1702 // When using haptic output, same audio format and sample rate are required.
1703 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001704 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001705 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1706 continue;
1707 }
1708 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001709 && format == outputDesc->getFormat()
1710 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001711 currentMatchCriteria[0] = outputHapticChannelCount;
1712 }
1713
1714 // functional flags match
1715 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1716
1717 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001718 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1719 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001720 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1721 channelCount <= outputChannelCount) {
1722 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001723 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1724 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001725 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001726 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001727 currentMatchCriteria[3] = outputChannelCount;
1728 }
1729
1730 // sampling rate match
1731 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001732 samplingRate <= outputDesc->getSamplingRate()) {
1733 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001734 }
1735
1736 // performance flags match
1737 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1738
1739 // format match
1740 if (format != AUDIO_FORMAT_INVALID) {
1741 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001742 PolicyAudioPort::kFormatDistanceMax -
1743 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001744 }
1745
1746 // primary output match
1747 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1748
1749 // compare match criteria by priority then value
1750 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1751 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1752 bestMatchCriteria = currentMatchCriteria;
1753 bestOutput = output;
1754
1755 std::stringstream result;
1756 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1757 std::ostream_iterator<int>(result, " "));
1758 ALOGV("%s new bestOutput %d criteria %s",
1759 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001760 }
1761 }
1762
Eric Laurent16c66dd2019-05-01 17:54:10 -07001763 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001764}
1765
Eric Laurent8fc147b2018-07-22 19:13:55 -07001766status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001767{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001768 ALOGV("%s portId %d", __FUNCTION__, portId);
1769
1770 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1771 if (outputDesc == 0) {
1772 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001773 return BAD_VALUE;
1774 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001775 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001776
Eric Laurent8fc147b2018-07-22 19:13:55 -07001777 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001778 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001779
Eric Laurent733ce942017-12-07 12:18:25 -08001780 status_t status = outputDesc->start();
1781 if (status != NO_ERROR) {
1782 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001783 }
1784
Eric Laurent97ac8712018-07-27 18:59:02 -07001785 uint32_t delayMs;
1786 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001787
1788 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001789 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001790 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001791 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001792 if (delayMs != 0) {
1793 usleep(delayMs * 1000);
1794 }
1795
1796 return status;
1797}
1798
Eric Laurent97ac8712018-07-27 18:59:02 -07001799status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1800 const sp<TrackClientDescriptor>& client,
1801 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001802{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001803 // cannot start playback of STREAM_TTS if any other output is being used
1804 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001805
1806 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001807 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001808 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001809 auto clientStrategy = client->strategy();
1810 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001811 if (stream == AUDIO_STREAM_TTS) {
1812 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001813 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001814 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001815 return INVALID_OPERATION;
1816 } else {
1817 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1818 }
1819 } else {
1820 // some playback other than beacon starts
1821 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1822 }
1823
Eric Laurent77305a62016-07-25 16:39:22 -07001824 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001825 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001826 bool force = !outputDesc->isActive() &&
1827 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001828
François Gaffie11d30102018-11-02 16:09:09 +01001829 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001830 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001831 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001832 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001833 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001834 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001835 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001836 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001837 } else {
1838 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001839 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001840 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1841 AUDIO_FORMAT_DEFAULT);
1842 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1843 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001844 }
1845
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001846 // requiresMuteCheck is false when we can bypass mute strategy.
1847 // It covers a common case when there is no materially active audio
1848 // and muting would result in unnecessary delay and dropped audio.
1849 const uint32_t outputLatencyMs = outputDesc->latency();
1850 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1851
Eric Laurente552edb2014-03-10 17:42:56 -07001852 // increment usage count for this stream on the requested output:
1853 // NOTE that the usage count is the same for duplicated output and hardware output which is
1854 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001855 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001856
1857 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001858 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1859 client->isPreferredDeviceForExclusiveUse()) {
1860 // Preferred device may be exclusive, use only if no other active clients on this output
1861 devices = DeviceVector(
1862 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1863 } else {
1864 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1865 }
François Gaffie11d30102018-11-02 16:09:09 +01001866 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001867 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001868 }
1869 }
Eric Laurente552edb2014-03-10 17:42:56 -07001870
François Gaffiec005e562018-11-06 15:04:49 +01001871 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001872 selectOutputForMusicEffects();
1873 }
1874
François Gaffie1c878552018-11-22 16:53:21 +01001875 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001876 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001877 if (devices.isEmpty()) {
1878 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001879 }
François Gaffiec005e562018-11-06 15:04:49 +01001880 bool shouldWait =
1881 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1882 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1883 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001884 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001885 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01001886 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001887 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001888 // An output has a shared device if
1889 // - managed by the same hw module
1890 // - supports the currently selected device
1891 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01001892 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001893
Eric Laurent77305a62016-07-25 16:39:22 -07001894 // force a device change if any other output is:
1895 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00001896 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001897 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07001898 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001899 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001900 // change the device currently selected by the other output.
1901 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01001902 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07001903 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001904 force = true;
1905 }
1906 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001907 // a notification so that audio focus effect can propagate, or that a mute/unmute
1908 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001909 const uint32_t latencyMs = desc->latency();
1910 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1911
1912 if (shouldWait && isActive && (waitMs < latencyMs)) {
1913 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07001914 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001915
1916 // Require mute check if another output is on a shared device
1917 // and currently active to have proper drain and avoid pops.
1918 // Note restoring AudioTracks onto this output needs to invoke
1919 // a volume ramp if there is no mute.
1920 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07001921 }
1922 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001923
1924 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01001925 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07001926
Eric Laurente552edb2014-03-10 17:42:56 -07001927 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01001928 auto &curves = getVolumeCurves(client->attributes());
1929 checkAndSetVolume(curves, client->volumeSource(),
1930 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07001931 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02001932 outputDesc->devices().types(), 0 /*delay*/,
1933 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001934
1935 // update the outputs if starting an output with a stream that can affect notification
1936 // routing
1937 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001938
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001939 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01001940 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001941 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1942 }
Eric Laurentdc462862016-07-19 12:29:53 -07001943
1944 if (waitMs > muteWaitMs) {
1945 *delayMs = waitMs - muteWaitMs;
1946 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001947
1948 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1949 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1950 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1951 // change occurs after the MixerThread starts and causes a stream volume
1952 // glitch.
1953 //
1954 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07001955 }
Eric Laurentdc462862016-07-19 12:29:53 -07001956
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001957 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07001958 mEngine->getForceUse(
1959 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01001960 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09001961 }
1962
Eric Laurent97ac8712018-07-27 18:59:02 -07001963 // Automatically enable the remote submix input when output is started on a re routing mix
1964 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07001965 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
1966 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07001967 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1968 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1969 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08001970 "remote-submix",
1971 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07001972 }
1973
Eric Laurente552edb2014-03-10 17:42:56 -07001974 return NO_ERROR;
1975}
1976
Eric Laurent8fc147b2018-07-22 19:13:55 -07001977status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001978{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001979 ALOGV("%s portId %d", __FUNCTION__, portId);
1980
1981 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1982 if (outputDesc == 0) {
1983 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001984 return BAD_VALUE;
1985 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001986 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001987
Eric Laurent97ac8712018-07-27 18:59:02 -07001988 ALOGV("stopOutput() output %d, stream %d, session %d",
1989 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07001990
Eric Laurent97ac8712018-07-27 18:59:02 -07001991 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08001992
Eric Laurent733ce942017-12-07 12:18:25 -08001993 if (status == NO_ERROR ) {
1994 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08001995 }
1996 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001997}
1998
Eric Laurent97ac8712018-07-27 18:59:02 -07001999status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2000 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002001{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002002 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002003 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002004 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002005
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002006 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2007
François Gaffie1c878552018-11-22 16:53:21 +01002008 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2009 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002010 // Automatically disable the remote submix input when output is stopped on a
2011 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002012 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002013 if (isSingleDeviceType(
2014 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002015 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002016 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002017 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2018 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002019 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002020 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002021 }
2022 }
2023 bool forceDeviceUpdate = false;
2024 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002025 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 forceDeviceUpdate = true;
2027 }
2028
Eric Laurente552edb2014-03-10 17:42:56 -07002029 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002030 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002031
Eric Laurente552edb2014-03-10 17:42:56 -07002032 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002033 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002034 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002035 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002036 // delay the device switch by twice the latency because stopOutput() is executed when
2037 // the track stop() command is received and at that time the audio track buffer can
2038 // still contain data that needs to be drained. The latency only covers the audio HAL
2039 // and kernel buffers. Also the latency does not always include additional delay in the
2040 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002041 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002042
2043 // force restoring the device selection on other active outputs if it differs from the
2044 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002045 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002046 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002047 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002048 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002049 desc->isActive() &&
2050 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002051 (newDevices != desc->devices())) {
2052 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2053 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002054
François Gaffie11d30102018-11-02 16:09:09 +01002055 setOutputDevices(desc, newDevices2, force, delayMs);
2056
Eric Laurent57de36c2016-09-28 16:59:11 -07002057 // re-apply device specific volume if not done by setOutputDevice()
2058 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002059 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002060 }
Eric Laurente552edb2014-03-10 17:42:56 -07002061 }
2062 }
2063 // update the outputs if stopping one with a stream that can affect notification routing
2064 handleNotificationRoutingForStream(stream);
2065 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002066
2067 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2068 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002069 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002070 }
2071
François Gaffiec005e562018-11-06 15:04:49 +01002072 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002073 selectOutputForMusicEffects();
2074 }
Eric Laurente552edb2014-03-10 17:42:56 -07002075 return NO_ERROR;
2076 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002077 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002078 return INVALID_OPERATION;
2079 }
2080}
2081
jiabinbce0c1d2020-10-05 11:20:18 -07002082bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002083{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002084 ALOGV("%s portId %d", __FUNCTION__, portId);
2085
2086 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2087 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002088 // If an output descriptor is closed due to a device routing change,
2089 // then there are race conditions with releaseOutput from tracks
2090 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2091 // destroyed shortly thereafter.
2092 //
2093 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002094 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002095 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002096 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002097
2098 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002099
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302100 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2101 if (outputDesc->isClientActive(client)) {
2102 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2103 stopOutput(portId);
2104 }
2105
Eric Laurent8fc147b2018-07-22 19:13:55 -07002106 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2107 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002108 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002109 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002110 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002111 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002112 if (--outputDesc->mDirectOpenCount == 0) {
2113 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002114 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002115 }
2116 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302117
Andy Hung39efb7a2018-09-26 15:39:28 -07002118 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002119 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2120 // The output is pending reopened to query dynamic profiles and
2121 // there is no active clients
2122 closeOutput(outputDesc->mIoHandle);
2123 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2124 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2125 if (newOutputDesc == nullptr) {
2126 ALOGE("%s failed to open output", __func__);
2127 }
2128 return true;
2129 }
2130 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002131}
2132
Eric Laurentcaf7f482014-11-25 17:50:47 -08002133status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2134 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002135 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002136 audio_session_t session,
Svet Ganov33761132021-05-13 22:51:08 +00002137 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002138 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002139 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002140 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002141 input_type_t *inputType,
2142 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002143{
François Gaffiec005e562018-11-06 15:04:49 +01002144 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2145 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
2146 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002147
Eric Laurentad2e7b92017-09-14 20:06:42 -07002148 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002149 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002150 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002151 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002152 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002153 sp<AudioInputDescriptor> inputDesc;
2154 sp<RecordClientDescriptor> clientDesc;
2155 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov33761132021-05-13 22:51:08 +00002156 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002157 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002158
2159 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2160 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2161 return INVALID_OPERATION;
2162 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002163
Francois Gaffie716e1432019-01-14 16:58:59 +01002164 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2165 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002166 }
2167
Paul McLean466dc8e2015-04-17 13:15:36 -06002168 // Explicit routing?
Pattye4981552021-11-04 21:01:03 +08002169 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002170 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002171
Eric Laurentad2e7b92017-09-14 20:06:42 -07002172 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2173 // possible
2174 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2175 *input != AUDIO_IO_HANDLE_NONE) {
2176 ssize_t index = mInputs.indexOfKey(*input);
2177 if (index < 0) {
2178 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2179 status = BAD_VALUE;
2180 goto error;
2181 }
2182 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002183 RecordClientVector clients = inputDesc->getClientsForSession(session);
2184 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002185 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2186 status = BAD_VALUE;
2187 goto error;
2188 }
2189 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2190 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002191 // corresponds to a new client and is only permitted from the same UID.
2192 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002193 if (clients.size() > 1) {
2194 for (const auto& client : clients) {
2195 // The client map is ordered by key values (portId) and portIds are allocated
2196 // incrementaly. So the first client in this list is the one opened by audio flinger
2197 // when the mmap stream is created and should be ignored as it does not correspond
2198 // to an actual client
2199 if (client == *clients.cbegin()) {
2200 continue;
2201 }
2202 if (uid != client->uid() && !client->isSilenced()) {
2203 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2204 uid, client->portId(), client->uid());
2205 status = INVALID_OPERATION;
2206 goto error;
2207 }
Eric Laurent331679c2018-04-16 17:03:16 -07002208 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002209 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002210 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002211 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002212
Eric Laurentfecbceb2021-02-09 14:46:43 +01002213 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002214 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002215 }
2216
2217 *input = AUDIO_IO_HANDLE_NONE;
2218 *inputType = API_INPUT_INVALID;
2219
Francois Gaffie716e1432019-01-14 16:58:59 +01002220 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002221
Francois Gaffie716e1432019-01-14 16:58:59 +01002222 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2223 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2224 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002225 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002226 ALOGW("%s could not find input mix for attr %s",
2227 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002228 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002229 }
jiabinc1de2df2019-05-07 14:26:40 -07002230 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2231 String8(attr->tags + strlen("addr=")),
2232 AUDIO_FORMAT_DEFAULT);
2233 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002234 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002235 __func__, attributes.source, attributes.tags);
2236 status = BAD_VALUE;
2237 goto error;
2238 }
2239
Kevin Rocard25f9b052019-02-27 15:08:54 -08002240 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2241 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2242 } else {
2243 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2244 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002245 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002246 if (explicitRoutingDevice != nullptr) {
2247 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002248 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002249 // Prevent from storing invalid requested device id in clients
2250 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002251 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002252 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2253 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002254 }
François Gaffie11d30102018-11-02 16:09:09 +01002255 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002256 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002257 status = BAD_VALUE;
2258 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002259 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002260 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2261 *inputType = API_INPUT_MIX_CAPTURE;
2262 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002263 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2264 // there is an external policy, but this input is attached to a mix of recorders,
2265 // meaning it receives audio injected into the framework, so the recorder doesn't
2266 // know about it and is therefore considered "legacy"
2267 *inputType = API_INPUT_LEGACY;
2268 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002269 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002270 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002271 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002272 } else {
2273 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002274 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002275
Eric Laurent599c7582015-12-07 18:05:55 -08002276 }
2277
François Gaffiec005e562018-11-06 15:04:49 +01002278 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002279 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002280 status = INVALID_OPERATION;
2281 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002282 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002283
Eric Laurent8f42ea12018-08-08 09:08:25 -07002284exit:
2285
François Gaffiec005e562018-11-06 15:04:49 +01002286 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2287 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002288
Francois Gaffie716e1432019-01-14 16:58:59 +01002289 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002290 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002291 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002292
Mikhail Naganov2996f672019-04-18 12:29:59 -07002293 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002294 requestedDeviceId, attributes.source, flags,
2295 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002296 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002297 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002298
2299 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2300 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002301
Eric Laurent599c7582015-12-07 18:05:55 -08002302 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002303
2304error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002305 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002306}
2307
2308
François Gaffie11d30102018-11-02 16:09:09 +01002309audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002310 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002311 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002312 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002313 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002314 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002315{
2316 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002317 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002318 bool isSoundTrigger = false;
2319
François Gaffiec005e562018-11-06 15:04:49 +01002320 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002321 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2322 if (index >= 0) {
2323 input = mSoundTriggerSessions.valueFor(session);
2324 isSoundTrigger = true;
2325 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2326 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2327 } else {
2328 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002329 }
François Gaffiec005e562018-11-06 15:04:49 +01002330 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002331 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002332 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002333 }
2334
Andy Hungf129b032015-04-07 13:45:50 -07002335 // find a compatible input profile (not necessarily identical in parameters)
2336 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002337 // sampling rate and flags may be updated by getInputProfile
2338 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2339 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002340 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002341 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002342 audio_input_flags_t profileFlags = flags;
2343 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002344 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002345 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002346 profileFlags);
2347 if (profile != 0) {
2348 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002349 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2350 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07002351 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2352 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2353 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002354 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattye4981552021-11-04 21:01:03 +08002355 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002356 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002357 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002358 }
Eric Laurente552edb2014-03-10 17:42:56 -07002359 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002360 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002361 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002362 if (samplingRate == 0) {
2363 samplingRate = profileSamplingRate;
2364 }
Eric Laurente552edb2014-03-10 17:42:56 -07002365
Eric Laurent322b4d22015-04-03 15:57:54 -07002366 if (profile->getModuleHandle() == 0) {
2367 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002368 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002369 }
2370
Eric Laurentec376dc2021-04-08 20:41:22 +02002371 // Reuse an already opened input if a client with the same session ID already exists
2372 // on that input
2373 for (size_t i = 0; i < mInputs.size(); i++) {
2374 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2375 if (desc->mProfile != profile) {
2376 continue;
2377 }
2378 RecordClientVector clients = desc->clientsList();
2379 for (const auto &client : clients) {
2380 if (session == client->session()) {
2381 return desc->mIoHandle;
2382 }
2383 }
2384 }
2385
Eric Laurent3974e3b2017-12-07 17:58:43 -08002386 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002387 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002388 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002389 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002390 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002391 continue;
2392 }
2393 // if sound trigger, reuse input if used by other sound trigger on same session
2394 // else
2395 // reuse input if active client app is not in IDLE state
2396 //
2397 RecordClientVector clients = desc->clientsList();
2398 bool doClose = false;
2399 for (const auto& client : clients) {
2400 if (isSoundTrigger != client->isSoundTrigger()) {
2401 continue;
2402 }
2403 if (client->isSoundTrigger()) {
2404 if (session == client->session()) {
2405 return desc->mIoHandle;
2406 }
2407 continue;
2408 }
2409 if (client->active() && client->appState() != APP_STATE_IDLE) {
2410 return desc->mIoHandle;
2411 }
2412 doClose = true;
2413 }
2414 if (doClose) {
2415 closeInput(desc->mIoHandle);
2416 } else {
2417 i++;
2418 }
2419 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002420 }
2421
Eric Laurentfe231122017-11-17 17:48:06 -08002422 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002423
Eric Laurentfe231122017-11-17 17:48:06 -08002424 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2425 lConfig.sample_rate = profileSamplingRate;
2426 lConfig.channel_mask = profileChannelMask;
2427 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002428
François Gaffie11d30102018-11-02 16:09:09 +01002429 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002430
2431 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002432 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002433 (profileSamplingRate != lConfig.sample_rate) ||
2434 !audio_formats_match(profileFormat, lConfig.format) ||
2435 (profileChannelMask != lConfig.channel_mask)) {
2436 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002437 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002438 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002439 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002440 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002441 }
Eric Laurent599c7582015-12-07 18:05:55 -08002442 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002443 }
2444
Eric Laurentc722f302014-12-10 11:21:49 -08002445 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002446
Eric Laurent599c7582015-12-07 18:05:55 -08002447 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002448 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002449
Eric Laurent599c7582015-12-07 18:05:55 -08002450 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002451}
2452
Eric Laurent4eb58f12018-12-07 16:41:02 -08002453status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002454{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002455 ALOGV("%s portId %d", __FUNCTION__, portId);
2456
2457 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2458 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002459 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002460 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002461 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002462 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002463 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002464 if (client->active()) {
2465 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2466 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002467 }
2468
Eric Laurent8f42ea12018-08-08 09:08:25 -07002469 audio_session_t session = client->session();
2470
Eric Laurent4eb58f12018-12-07 16:41:02 -08002471 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002472
Eric Laurent4eb58f12018-12-07 16:41:02 -08002473 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002474
Eric Laurent4eb58f12018-12-07 16:41:02 -08002475 status_t status = inputDesc->start();
2476 if (status != NO_ERROR) {
2477 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002478 }
Eric Laurente552edb2014-03-10 17:42:56 -07002479
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002480 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002481 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002483
Eric Laurent8f42ea12018-08-08 09:08:25 -07002484 // indicate active capture to sound trigger service if starting capture from a mic on
2485 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002486 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002487 if (device != nullptr) {
2488 status = setInputDevice(input, device, true /* force */);
2489 } else {
2490 ALOGW("%s no new input device can be found for descriptor %d",
2491 __FUNCTION__, inputDesc->getId());
2492 status = BAD_VALUE;
2493 }
Eric Laurente552edb2014-03-10 17:42:56 -07002494
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002495 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002496 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002497 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002498 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002499 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2500 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002501 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002502 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002503
François Gaffie11d30102018-11-02 16:09:09 +01002504 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2505 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002506 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002507 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002508 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002509
Eric Laurent8f42ea12018-08-08 09:08:25 -07002510 // automatically enable the remote submix output when input is started if not
2511 // used by a policy mix of type MIX_TYPE_RECORDERS
2512 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002513 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002514 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002515 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002516 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002517 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2518 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002519 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002520 if (address != "") {
2521 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002523 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002524 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002525 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002526 } else if (status != NO_ERROR) {
2527 // Restore client activity state.
2528 inputDesc->setClientActive(client, false);
2529 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002530 }
2531
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002532 ALOGV("%s input %d source = %d status = %d exit",
2533 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002534
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002535 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002536}
2537
Eric Laurent8fc147b2018-07-22 19:13:55 -07002538status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002539{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002540 ALOGV("%s portId %d", __FUNCTION__, portId);
2541
2542 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2543 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002544 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002545 return BAD_VALUE;
2546 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002547 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002548 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002549 if (!client->active()) {
2550 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002551 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002552 }
Carter Hsue6139d52021-07-08 10:30:20 +08002553 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002554 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002555
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 inputDesc->stop();
2557 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002558 auto current_source = inputDesc->source();
2559 setInputDevice(input, getNewInputDevice(inputDesc),
2560 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002561 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002562 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002564 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002565 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2566 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002567 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002568 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002569
2570 // automatically disable the remote submix output when input is stopped if not
2571 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002572 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002573 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002574 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002575 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002576 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2577 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 }
2579 if (address != "") {
2580 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2581 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002582 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002583 }
2584 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002585 resetInputDevice(input);
2586
2587 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2588 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002589 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2590 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002591 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002592 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 }
2594 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002595 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002596 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002597}
2598
Eric Laurent8fc147b2018-07-22 19:13:55 -07002599void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002600{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002601 ALOGV("%s portId %d", __FUNCTION__, portId);
2602
2603 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2604 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002606 return;
2607 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002608 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002609 audio_io_handle_t input = inputDesc->mIoHandle;
2610
Eric Laurent8f42ea12018-08-08 09:08:25 -07002611 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002612
Andy Hung39efb7a2018-09-26 15:39:28 -07002613 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002614
Andy Hung39efb7a2018-09-26 15:39:28 -07002615 if (inputDesc->getClientCount() > 0) {
2616 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002617 return;
2618 }
2619
Eric Laurent05b90f82014-08-27 15:32:29 -07002620 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002621 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002622 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002623}
2624
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002626{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002627 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628
2629 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631 }
2632}
2633
Eric Laurent8f42ea12018-08-08 09:08:25 -07002634void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2635{
2636 stopInput(portId);
2637 releaseInput(portId);
2638}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002639
Eric Laurent0dd51852019-04-19 18:18:58 -07002640void AudioPolicyManager::checkCloseInputs() {
2641 // After connecting or disconnecting an input device, close input if:
2642 // - it has no client (was just opened to check profile) OR
2643 // - none of its supported devices are connected anymore OR
2644 // - one of its clients cannot be routed to one of its supported
2645 // devices anymore. Otherwise update device selection
2646 std::vector<audio_io_handle_t> inputsToClose;
2647 for (size_t i = 0; i < mInputs.size(); i++) {
2648 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2649 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002650 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002651 inputsToClose.push_back(mInputs.keyAt(i));
2652 } else {
2653 bool close = false;
2654 for (const auto& client : input->clientsList()) {
2655 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002656 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002657 if (!input->supportedDevices().contains(device)) {
2658 close = true;
2659 break;
2660 }
2661 }
2662 if (close) {
2663 inputsToClose.push_back(mInputs.keyAt(i));
2664 } else {
2665 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2666 }
2667 }
2668 }
2669
2670 for (const audio_io_handle_t handle : inputsToClose) {
2671 ALOGV("%s closing input %d", __func__, handle);
2672 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002673 }
Eric Laurentd4692962014-05-05 18:13:44 -07002674}
2675
François Gaffie251c7f02018-11-07 10:41:08 +01002676void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002677{
2678 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002679 if (indexMin < 0 || indexMax < 0) {
2680 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2681 return;
2682 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002683 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002684
2685 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002686 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2687 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002688 continue;
2689 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002690 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002691 }
Eric Laurente552edb2014-03-10 17:42:56 -07002692}
2693
Eric Laurente0720872014-03-11 09:30:41 -07002694status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002695 int index,
2696 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002697{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002698 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002699 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2700 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2701 return NO_ERROR;
2702 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002703 ALOGV("%s: stream %s attributes=%s", __func__,
2704 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002705 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002706}
2707
Eric Laurente0720872014-03-11 09:30:41 -07002708status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002709 int *index,
2710 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002711{
François Gaffiec005e562018-11-06 15:04:49 +01002712 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2713 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002714 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002715 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002716 deviceTypes = mEngine->getOutputDevicesForStream(
2717 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002718 }
jiabin9a3361e2019-10-01 09:38:30 -07002719 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002720}
2721
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002722status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002723 int index,
2724 audio_devices_t device)
2725{
2726 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002727 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2728 if (group == VOLUME_GROUP_NONE) {
2729 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002730 return BAD_VALUE;
2731 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002732 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002733 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002734 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002735 VolumeSource vs = toVolumeSource(group);
2736 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2737
2738 status = setVolumeCurveIndex(index, device, curves);
2739 if (status != NO_ERROR) {
2740 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2741 return status;
2742 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002743
jiabin9a3361e2019-10-01 09:38:30 -07002744 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002745 auto curCurvAttrs = curves.getAttributes();
2746 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2747 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002748 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002749 } else if (!curves.getStreamTypes().empty()) {
2750 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002751 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002752 } else {
2753 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2754 return BAD_VALUE;
2755 }
jiabin9a3361e2019-10-01 09:38:30 -07002756 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2757 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002758
François Gaffiecfe17322018-11-07 13:41:29 +01002759 // update volume on all outputs and streams matching the following:
2760 // - The requested stream (or a stream matching for volume control) is active on the output
2761 // - The device (or devices) selected by the engine for this stream includes
2762 // the requested device
2763 // - For non default requested device, currently selected device on the output is either the
2764 // requested device or one of the devices selected by the engine for this stream
2765 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2766 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002767 for (size_t i = 0; i < mOutputs.size(); i++) {
2768 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002769 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002770
jiabin9a3361e2019-10-01 09:38:30 -07002771 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2772 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002773 }
François Gaffieed91f582020-01-31 10:35:37 +01002774 if (!(desc->isActive(vs) || isInCall())) {
2775 continue;
2776 }
2777 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2778 curDevices.find(device) == curDevices.end()) {
2779 continue;
2780 }
2781 bool applyVolume = false;
2782 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2783 curSrcDevices.insert(device);
2784 applyVolume = (curSrcDevices.find(
2785 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2786 } else {
2787 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2788 }
2789 if (!applyVolume) {
2790 continue; // next output
2791 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002792 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2793 // If a higher priority strategy is active, and the output is routed to a device with a
2794 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002795 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002796 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002797 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2798 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2799 false /*preferredDevice*/);
2800 if (activeClients.empty()) {
2801 continue;
2802 }
2803 bool isPreempted = false;
2804 bool isHigherPriority = productStrategy < strategy;
2805 for (const auto &client : activeClients) {
2806 if (isHigherPriority && (client->volumeSource() != vs)) {
2807 ALOGV("%s: Strategy=%d (\nrequester:\n"
2808 " group %d, volumeGroup=%d attributes=%s)\n"
2809 " higher priority source active:\n"
2810 " volumeGroup=%d attributes=%s) \n"
2811 " on output %zu, bailing out", __func__, productStrategy,
2812 group, group, toString(attributes).c_str(),
2813 client->volumeSource(), toString(client->attributes()).c_str(), i);
2814 applyVolume = false;
2815 isPreempted = true;
2816 break;
2817 }
2818 // However, continue for loop to ensure no higher prio clients running on output
2819 if (client->volumeSource() == vs) {
2820 applyVolume = true;
2821 }
2822 }
2823 if (isPreempted || applyVolume) {
2824 break;
2825 }
2826 }
2827 if (!applyVolume) {
2828 continue; // next output
2829 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002830 }
François Gaffieed91f582020-01-31 10:35:37 +01002831 //FIXME: workaround for truncated touch sounds
2832 // delayed volume change for system stream to be removed when the problem is
2833 // handled by system UI
2834 status_t volStatus = checkAndSetVolume(
2835 curves, vs, index, desc, curDevices,
2836 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2837 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2838 if (volStatus != NO_ERROR) {
2839 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002840 }
2841 }
François Gaffiecfe17322018-11-07 13:41:29 +01002842 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2843 return status;
2844}
2845
François Gaffieaaac0fd2018-11-22 17:56:39 +01002846status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002847 audio_devices_t device,
2848 IVolumeCurves &volumeCurves)
2849{
2850 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2851 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002852 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2853 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002854 (index > volumeCurves.getVolumeIndexMax())) {
2855 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2856 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2857 return BAD_VALUE;
2858 }
2859 if (!audio_is_output_device(device)) {
2860 return BAD_VALUE;
2861 }
2862
2863 // Force max volume if stream cannot be muted
2864 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2865
François Gaffieaaac0fd2018-11-22 17:56:39 +01002866 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002867 volumeCurves.addCurrentVolumeIndex(device, index);
2868 return NO_ERROR;
2869}
2870
2871status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2872 int &index,
2873 audio_devices_t device)
2874{
2875 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2876 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002877 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002878 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002879 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
2880 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01002881 }
jiabin9a3361e2019-10-01 09:38:30 -07002882 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01002883}
2884
2885status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2886 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07002887 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01002888{
jiabin9a3361e2019-10-01 09:38:30 -07002889 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01002890 return BAD_VALUE;
2891 }
jiabin9a3361e2019-10-01 09:38:30 -07002892 index = curves.getVolumeIndex(deviceTypes);
2893 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01002894 return NO_ERROR;
2895}
2896
2897status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2898 int &index)
2899{
2900 index = getVolumeCurves(attr).getVolumeIndexMin();
2901 return NO_ERROR;
2902}
2903
2904status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2905 int &index)
2906{
2907 index = getVolumeCurves(attr).getVolumeIndexMax();
2908 return NO_ERROR;
2909}
2910
Eric Laurent36829f92017-04-07 19:04:42 -07002911audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002912{
2913 // select one output among several suitable for global effects.
2914 // The priority is as follows:
2915 // 1: An offloaded output. If the effect ends up not being offloadable,
2916 // AudioFlinger will invalidate the track and the offloaded output
2917 // will be closed causing the effect to be moved to a PCM output.
2918 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002919 // 3: The primary output
2920 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002921
François Gaffiec005e562018-11-06 15:04:49 +01002922 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2923 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01002924 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002925
Eric Laurent36829f92017-04-07 19:04:42 -07002926 if (outputs.size() == 0) {
2927 return AUDIO_IO_HANDLE_NONE;
2928 }
Eric Laurente552edb2014-03-10 17:42:56 -07002929
Eric Laurent36829f92017-04-07 19:04:42 -07002930 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2931 bool activeOnly = true;
2932
2933 while (output == AUDIO_IO_HANDLE_NONE) {
2934 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2935 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2936 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2937
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002938 for (audio_io_handle_t output : outputs) {
2939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07002940 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002941 continue;
2942 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002943 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2944 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07002945 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002946 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002947 }
2948 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002949 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002950 }
2951 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002952 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07002953 }
2954 }
2955 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2956 output = outputOffloaded;
2957 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2958 output = outputDeepBuffer;
2959 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2960 output = outputPrimary;
2961 } else {
2962 output = outputs[0];
2963 }
2964 activeOnly = false;
2965 }
2966
2967 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07002968 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07002969 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2970 mMusicEffectOutput = output;
2971 }
2972
2973 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002974 return output;
2975}
2976
Eric Laurent36829f92017-04-07 19:04:42 -07002977audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2978{
2979 return selectOutputForMusicEffects();
2980}
2981
Eric Laurente0720872014-03-11 09:30:41 -07002982status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002983 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08002984 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002985 int session,
2986 int id)
2987{
Eric Laurentb82e6b72019-11-22 17:25:04 -08002988 if (session != AUDIO_SESSION_DEVICE) {
2989 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07002990 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08002991 index = mInputs.indexOfKey(io);
2992 if (index < 0) {
2993 ALOGW("registerEffect() unknown io %d", io);
2994 return INVALID_OPERATION;
2995 }
Eric Laurente552edb2014-03-10 17:42:56 -07002996 }
2997 }
François Gaffiec005e562018-11-06 15:04:49 +01002998 return mEffects.registerEffect(desc, io, session, id,
2999 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3000 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003001}
3002
Eric Laurentc241b0d2018-11-28 09:08:49 -08003003status_t AudioPolicyManager::unregisterEffect(int id)
3004{
3005 if (mEffects.getEffect(id) == nullptr) {
3006 return INVALID_OPERATION;
3007 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003008 if (mEffects.isEffectEnabled(id)) {
3009 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3010 setEffectEnabled(id, false);
3011 }
3012 return mEffects.unregisterEffect(id);
3013}
3014
3015status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3016{
3017 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3018 if (effect == nullptr) {
3019 return INVALID_OPERATION;
3020 }
3021
3022 status_t status = mEffects.setEffectEnabled(id, enabled);
3023 if (status == NO_ERROR) {
3024 mInputs.trackEffectEnabled(effect, enabled);
3025 }
3026 return status;
3027}
3028
Eric Laurent6c796322019-04-09 14:13:17 -07003029
3030status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3031{
3032 mEffects.moveEffects(ids, io);
3033 return NO_ERROR;
3034}
3035
Eric Laurentc75307b2015-03-17 15:29:32 -07003036bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3037{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003038 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003039}
3040
3041bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3042{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003043 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003044}
3045
Eric Laurente0720872014-03-11 09:30:41 -07003046bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003047{
3048 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003049 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003050 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003051 return true;
3052 }
3053 }
3054 return false;
3055}
3056
Eric Laurent275e8e92014-11-30 15:14:47 -08003057// Register a list of custom mixes with their attributes and format.
3058// When a mix is registered, corresponding input and output profiles are
3059// added to the remote submix hw module. The profile contains only the
3060// parameters (sampling rate, format...) specified by the mix.
3061// The corresponding input remote submix device is also connected.
3062//
3063// When a remote submix device is connected, the address is checked to select the
3064// appropriate profile and the corresponding input or output stream is opened.
3065//
3066// When capture starts, getInputForAttr() will:
3067// - 1 look for a mix matching the address passed in attribtutes tags if any
3068// - 2 if none found, getDeviceForInputSource() will:
3069// - 2.1 look for a mix matching the attributes source
3070// - 2.2 if none found, default to device selection by policy rules
3071// At this time, the corresponding output remote submix device is also connected
3072// and active playback use cases can be transferred to this mix if needed when reconnecting
3073// after AudioTracks are invalidated
3074//
3075// When playback starts, getOutputForAttr() will:
3076// - 1 look for a mix matching the address passed in attribtutes tags if any
3077// - 2 if none found, look for a mix matching the attributes usage
3078// - 3 if none found, default to device and output selection by policy rules.
3079
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003080status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003081{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003082 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3083 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003084 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003085 sp<HwModule> rSubmixModule;
3086 // examine each mix's route type
3087 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003088 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003089 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3090 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3091 ALOGE("Unsupported Policy Mix %zu of %zu: "
3092 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3093 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003094 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003095 break;
3096 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003097 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3098 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003099 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003100 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3101 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003102 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003103 rSubmixModule = mHwModules.getModuleFromName(
3104 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3105 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003106 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003107 i);
3108 res = INVALID_OPERATION;
3109 break;
3110 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003111 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003112
Eric Laurent97ac8712018-07-27 18:59:02 -07003113 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003114 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003115 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003116 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003117 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3118 } else {
3119 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3120 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003121 }
François Gaffie036e1e92015-03-19 10:16:24 +01003122
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003123 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003124 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003125 res = INVALID_OPERATION;
3126 break;
3127 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003128 audio_config_t outputConfig = mix.mFormat;
3129 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003130 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3131 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003132 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3133 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003134 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003135 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003136 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003137 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003138
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003139 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003140 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3141 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3142 ALOGE("Failed to set remote submix device available, type %u, address %s",
3143 mix.mDeviceType, address.string());
3144 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003145 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003146 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3147 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003148 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003149 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003150 i, mixes.size(), type, address.string());
3151
3152 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3153 mix.mDeviceType, mix.mDeviceAddress,
3154 String8(), AUDIO_FORMAT_DEFAULT);
3155 if (device == nullptr) {
3156 res = INVALID_OPERATION;
3157 break;
3158 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003159
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003160 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003161 // First try to find an already opened output supporting the device
3162 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003163 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003164
Eric Laurentc529cf62020-04-17 18:19:10 -07003165 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003166 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003167 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3168 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003169 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003170 } else {
3171 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003172 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003173 }
3174 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003175 // If no output found, try to find a direct output profile supporting the device
3176 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3177 sp<HwModule> module = mHwModules[i];
3178 for (size_t j = 0;
3179 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3180 j++) {
3181 sp<IOProfile> profile = module->getOutputProfiles()[j];
3182 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3183 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3184 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3185 address.string());
3186 res = INVALID_OPERATION;
3187 } else {
3188 foundOutput = true;
3189 }
3190 }
3191 }
3192 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003193 if (res != NO_ERROR) {
3194 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003195 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003196 res = INVALID_OPERATION;
3197 break;
3198 } else if (!foundOutput) {
3199 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003200 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003201 res = INVALID_OPERATION;
3202 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003203 } else {
3204 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003205 }
Eric Laurentc722f302014-12-10 11:21:49 -08003206 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003207 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003208 if (res != NO_ERROR) {
3209 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003210 } else if (checkOutputs) {
3211 checkForDeviceAndOutputChanges();
3212 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003213 }
3214 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003215}
3216
3217status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3218{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003219 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003220 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003221 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003222 sp<HwModule> rSubmixModule;
3223 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003224 for (const auto& mix : mixes) {
3225 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003226
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003227 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003228 rSubmixModule = mHwModules.getModuleFromName(
3229 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3230 if (rSubmixModule == 0) {
3231 res = INVALID_OPERATION;
3232 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003233 }
3234 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003235
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003236 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003237
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003238 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003239 res = INVALID_OPERATION;
3240 continue;
3241 }
3242
Kevin Rocard04ed0462019-05-02 17:53:24 -07003243 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3244 if (getDeviceConnectionState(device, address.string()) ==
3245 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3246 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3247 address.string(), "remote-submix",
3248 AUDIO_FORMAT_DEFAULT);
3249 if (res != OK) {
3250 ALOGE("Error making RemoteSubmix device unavailable for mix "
3251 "with type %d, address %s", device, address.string());
3252 }
3253 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003254 }
jiabin5740f082019-08-19 15:08:30 -07003255 rSubmixModule->removeOutputProfile(address.c_str());
3256 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003257
Kevin Rocard153f92d2018-12-18 18:33:28 -08003258 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003259 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003260 res = INVALID_OPERATION;
3261 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003262 } else {
3263 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003264 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003265 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003266 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003267 if (res == NO_ERROR && checkOutputs) {
3268 checkForDeviceAndOutputChanges();
3269 updateCallAndOutputRouting();
3270 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003271 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003272}
3273
Mikhail Naganov100f0122018-11-29 11:22:16 -08003274void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3275{
3276 size_t i = 0;
3277 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3278 for (const auto& fmt : mManualSurroundFormats) {
3279 if (i++ != 0) dst->append(", ");
3280 std::string sfmt;
3281 FormatConverter::toString(fmt, sfmt);
3282 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3283 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3284 }
3285}
3286
Eric Laurentc529cf62020-04-17 18:19:10 -07003287// Returns true if all devices types match the predicate and are supported by one HW module
3288bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003289 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003290 std::function<bool(audio_devices_t)> predicate,
3291 const char *context) {
3292 for (size_t i = 0; i < devices.size(); i++) {
3293 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003294 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003295 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003296 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003297 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003298 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003299 return false;
3300 }
3301 }
3302 return true;
3303}
3304
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003305status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003306 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003307 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003308 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3309 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003310 }
3311 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003312 if (res != NO_ERROR) {
3313 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3314 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003315 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003316
3317 checkForDeviceAndOutputChanges();
3318 updateCallAndOutputRouting();
3319
3320 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003321}
3322
3323status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3324 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003325 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3326 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003327 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003328 __FUNCTION__, uid);
3329 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003330 }
3331
Eric Laurentc529cf62020-04-17 18:19:10 -07003332 checkForDeviceAndOutputChanges();
3333 updateCallAndOutputRouting();
3334
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003335 return res;
3336}
3337
Eric Laurent2517af32020-11-25 15:31:27 +01003338
jiabin0a488932020-08-07 17:32:40 -07003339status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3340 device_role_t role,
3341 const AudioDeviceTypeAddrVector &devices) {
3342 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3343 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003344
Eric Laurentc529cf62020-04-17 18:19:10 -07003345 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003346 return BAD_VALUE;
3347 }
jiabin0a488932020-08-07 17:32:40 -07003348 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003349 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003350 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3351 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003352 return status;
3353 }
3354
3355 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003356
3357 bool forceVolumeReeval = false;
3358 // FIXME: workaround for truncated touch sounds
3359 // to be removed when the problem is handled by system UI
3360 uint32_t delayMs = 0;
3361 if (strategy == mCommunnicationStrategy) {
3362 forceVolumeReeval = true;
3363 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3364 updateInputRouting();
3365 }
3366 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003367
3368 return NO_ERROR;
3369}
3370
3371void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3372{
3373 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003374 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003375 // Only apply special touch sound delay once
3376 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003377 }
3378 for (size_t i = 0; i < mOutputs.size(); i++) {
3379 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3380 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3381 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3382 // As done in setDeviceConnectionState, we could also fix default device issue by
3383 // preventing the force re-routing in case of default dev that distinguishes on address.
3384 // Let's give back to engine full device choice decision however.
3385 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003386 // Only apply special touch sound delay once
3387 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003388 }
3389 if (forceVolumeReeval && !newDevices.isEmpty()) {
3390 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3391 }
3392 }
3393}
3394
Eric Laurent2517af32020-11-25 15:31:27 +01003395void AudioPolicyManager::updateInputRouting() {
3396 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303397 // Skip for hotword recording as the input device switch
3398 // is handled within sound trigger HAL
3399 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3400 continue;
3401 }
Eric Laurent2517af32020-11-25 15:31:27 +01003402 auto newDevice = getNewInputDevice(activeDesc);
3403 // Force new input selection if the new device can not be reached via current input
3404 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3405 setInputDevice(activeDesc->mIoHandle, newDevice);
3406 } else {
3407 closeInput(activeDesc->mIoHandle);
3408 }
3409 }
3410}
3411
jiabin0a488932020-08-07 17:32:40 -07003412status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3413 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003414{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003415 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003416
jiabin0a488932020-08-07 17:32:40 -07003417 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003418 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003419 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3420 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003421 return status;
3422 }
3423
3424 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003425
3426 bool forceVolumeReeval = false;
3427 // FIXME: workaround for truncated touch sounds
3428 // to be removed when the problem is handled by system UI
3429 uint32_t delayMs = 0;
3430 if (strategy == mCommunnicationStrategy) {
3431 forceVolumeReeval = true;
3432 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3433 updateInputRouting();
3434 }
3435 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003436
3437 return NO_ERROR;
3438}
3439
jiabin0a488932020-08-07 17:32:40 -07003440status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3441 device_role_t role,
3442 AudioDeviceTypeAddrVector &devices) {
3443 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003444}
3445
Jiabin Huang3b98d322020-09-03 17:54:16 +00003446status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3447 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3448 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3449 dumpAudioDeviceTypeAddrVector(devices).c_str());
3450
Mikhail Naganov55773032020-10-01 15:08:13 -07003451 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003452 return BAD_VALUE;
3453 }
3454 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3455 ALOGW_IF(status != NO_ERROR,
3456 "Engine could not set preferred devices %s for audio source %d role %d",
3457 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3458
3459 return status;
3460}
3461
3462status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3463 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3464 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3465 dumpAudioDeviceTypeAddrVector(devices).c_str());
3466
Mikhail Naganov55773032020-10-01 15:08:13 -07003467 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003468 return BAD_VALUE;
3469 }
3470 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3471 ALOGW_IF(status != NO_ERROR,
3472 "Engine could not add preferred devices %s for audio source %d role %d",
3473 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3474
Eric Laurent2517af32020-11-25 15:31:27 +01003475 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003476 return status;
3477}
3478
3479status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3480 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3481{
3482 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3483 dumpAudioDeviceTypeAddrVector(devices).c_str());
3484
Mikhail Naganov55773032020-10-01 15:08:13 -07003485 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003486 return BAD_VALUE;
3487 }
3488
3489 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3490 audioSource, role, devices);
3491 ALOGW_IF(status != NO_ERROR,
3492 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3493
Eric Laurent2517af32020-11-25 15:31:27 +01003494 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003495 return status;
3496}
3497
3498status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3499 device_role_t role) {
3500 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3501
3502 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3503 ALOGW_IF(status != NO_ERROR,
3504 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3505
Eric Laurent2517af32020-11-25 15:31:27 +01003506 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003507 return status;
3508}
3509
3510status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3511 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3512 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3513}
3514
Oscar Azucena90e77632019-11-27 17:12:28 -08003515status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003516 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003517 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003518 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3519 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003520 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003521 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3522 if (status != NO_ERROR) {
3523 ALOGE("%s() could not set device affinity for userId %d",
3524 __FUNCTION__, userId);
3525 return status;
3526 }
3527
3528 // reevaluate outputs for all devices
3529 checkForDeviceAndOutputChanges();
3530 updateCallAndOutputRouting();
3531
3532 return NO_ERROR;
3533}
3534
3535status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003536 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003537 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3538 if (status != NO_ERROR) {
3539 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3540 __FUNCTION__, userId);
3541 return status;
3542 }
3543
3544 // reevaluate outputs for all devices
3545 checkForDeviceAndOutputChanges();
3546 updateCallAndOutputRouting();
3547
3548 return NO_ERROR;
3549}
3550
Andy Hungc29d82b2018-10-05 12:23:17 -07003551void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003552{
Andy Hungc29d82b2018-10-05 12:23:17 -07003553 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3554 dst->appendFormat(" Primary Output: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003555 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003556 std::string stateLiteral;
3557 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003558 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003559 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3560 "communications", "media", "record", "dock", "system",
3561 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3562 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3563 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003564 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3565 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3566 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3567 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3568 dst->append(" (MANUAL: ");
3569 dumpManualSurroundFormats(dst);
3570 dst->append(")");
3571 }
3572 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003573 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003574 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3575 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003576 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003577 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003578
Andy Hungc29d82b2018-10-05 12:23:17 -07003579 mAvailableOutputDevices.dump(dst, String8("Available output"));
3580 mAvailableInputDevices.dump(dst, String8("Available input"));
3581 mHwModulesAll.dump(dst);
3582 mOutputs.dump(dst);
3583 mInputs.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003584 mEffects.dump(dst);
3585 mAudioPatches.dump(dst);
3586 mPolicyMixes.dump(dst);
3587 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003588
Kevin Rocardb99cc752019-03-21 20:52:24 -07003589 dst->appendFormat(" AllowedCapturePolicies:\n");
3590 for (auto& policy : mAllowedCapturePolicies) {
3591 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3592 }
3593
François Gaffiec005e562018-11-06 15:04:49 +01003594 dst->appendFormat("\nPolicy Engine dump:\n");
3595 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003596}
3597
3598status_t AudioPolicyManager::dump(int fd)
3599{
3600 String8 result;
3601 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003602 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003603 return NO_ERROR;
3604}
3605
Kevin Rocardb99cc752019-03-21 20:52:24 -07003606status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3607{
3608 mAllowedCapturePolicies[uid] = capturePolicy;
3609 return NO_ERROR;
3610}
3611
Eric Laurente552edb2014-03-10 17:42:56 -07003612// This function checks for the parameters which can be offloaded.
3613// This can be enhanced depending on the capability of the DSP and policy
3614// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003615audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003616{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003617 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003618 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003619 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003620 offloadInfo.format,
3621 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3622 offloadInfo.has_video);
3623
Andy Hung2ddee192015-12-18 17:34:44 -08003624 if (mMasterMono) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003625 return AUDIO_OFFLOAD_NOT_SUPPORTED; // no offloading if mono is set.
Andy Hung2ddee192015-12-18 17:34:44 -08003626 }
3627
Eric Laurente552edb2014-03-10 17:42:56 -07003628 // Check if offload has been disabled
Andy Hung0f6e6402018-09-06 11:20:45 -07003629 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003630 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3631 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003632 }
3633
3634 // Check if stream type is music, then only allow offload as of now.
3635 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3636 {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003637 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3638 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003639 }
3640
3641 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07003642 const bool allowOffloadWithVideo =
3643 property_get_bool("audio.offload.video", false /* default_value */);
3644 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003645 ALOGV("%s: has_video == true, returning false", __func__);
3646 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003647 }
3648
3649 //If duration is less than minimum value defined in property, return false
Andy Hung0f6e6402018-09-06 11:20:45 -07003650 const int min_duration_secs = property_get_int32(
3651 "audio.offload.min.duration.secs", -1 /* default_value */);
3652 if (min_duration_secs >= 0) {
3653 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003654 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3655 __func__, min_duration_secs);
3656 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003657 }
3658 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003659 ALOGV("%s: Offload denied by duration < default min(=%u)",
3660 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3661 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003662 }
3663
3664 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3665 // creating an offloaded track and tearing it down immediately after start when audioflinger
3666 // detects there is an active non offloadable effect.
3667 // FIXME: We should check the audio session here but we do not have it in this context.
3668 // This may prevent offloading in rare situations where effects are left active by apps
3669 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01003670 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003671 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003672 }
3673
3674 // See if there is a profile to support this.
3675 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003676 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003677 offloadInfo.sample_rate,
3678 offloadInfo.format,
3679 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003680 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3681 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003682 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3683 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3684 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003685 if (profile == nullptr) {
3686 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3687 }
3688 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3689 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3690 }
3691 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003692}
3693
Michael Chana94fbb22018-04-24 14:31:19 +10003694bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3695 const audio_attributes_t& attributes) {
3696 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003697 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
François Gaffie11d30102018-11-02 16:09:09 +01003698 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Michael Chana94fbb22018-04-24 14:31:19 +10003699 config.sample_rate,
3700 config.format,
3701 config.channel_mask,
3702 output_flags,
3703 true /* directOnly */);
3704 ALOGV("%s() profile %sfound with name: %s, "
3705 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3706 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003707 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003708 config.sample_rate, config.format, config.channel_mask, output_flags);
3709 return (profile != 0);
3710}
3711
Eric Laurent6a94d692014-05-20 11:18:06 -07003712status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3713 audio_port_type_t type,
3714 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003715 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003716 unsigned int *generation)
3717{
jiabin19cdba52020-11-24 11:28:58 -08003718 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3719 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003720 return BAD_VALUE;
3721 }
3722 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003723 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003724 *num_ports = 0;
3725 }
3726
3727 size_t portsWritten = 0;
3728 size_t portsMax = *num_ports;
3729 *num_ports = 0;
3730 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003731 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3732 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003733 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003734 for (const auto& dev : mAvailableOutputDevices) {
3735 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003736 continue;
3737 }
3738 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003739 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003740 }
3741 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003743 }
3744 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003745 for (const auto& dev : mAvailableInputDevices) {
3746 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003747 continue;
3748 }
3749 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003750 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003751 }
3752 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003753 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003754 }
3755 }
3756 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3757 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3758 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3759 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3760 }
3761 *num_ports += mInputs.size();
3762 }
3763 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07003764 size_t numOutputs = 0;
3765 for (size_t i = 0; i < mOutputs.size(); i++) {
3766 if (!mOutputs[i]->isDuplicated()) {
3767 numOutputs++;
3768 if (portsWritten < portsMax) {
3769 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3770 }
3771 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003772 }
Eric Laurent84c70242014-06-23 08:46:27 -07003773 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003774 }
3775 }
3776 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003777 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07003778 return NO_ERROR;
3779}
3780
jiabin19cdba52020-11-24 11:28:58 -08003781status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07003782{
Eric Laurent99fcae42018-05-17 16:59:18 -07003783 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3784 return BAD_VALUE;
3785 }
3786 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3787 if (dev != 0) {
3788 dev->toAudioPort(port);
3789 return NO_ERROR;
3790 }
3791 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3792 if (dev != 0) {
3793 dev->toAudioPort(port);
3794 return NO_ERROR;
3795 }
3796 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3797 if (out != 0) {
3798 out->toAudioPort(port);
3799 return NO_ERROR;
3800 }
3801 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3802 if (in != 0) {
3803 in->toAudioPort(port);
3804 return NO_ERROR;
3805 }
3806 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003807}
3808
François Gaffieafd4cea2019-11-18 15:50:22 +01003809status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
3810 audio_patch_handle_t *handle,
3811 uid_t uid, uint32_t delayMs,
3812 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07003813{
François Gaffieafd4cea2019-11-18 15:50:22 +01003814 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 if (handle == NULL || patch == NULL) {
3816 return BAD_VALUE;
3817 }
François Gaffieafd4cea2019-11-18 15:50:22 +01003818 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07003819
Mikhail Naganovac9858b2018-06-15 13:12:37 -07003820 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07003821 return BAD_VALUE;
3822 }
3823 // only one source per audio patch supported for now
3824 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003825 return INVALID_OPERATION;
3826 }
Eric Laurent874c42872014-08-08 15:13:39 -07003827
3828 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003829 return INVALID_OPERATION;
3830 }
Eric Laurent874c42872014-08-08 15:13:39 -07003831 for (size_t i = 0; i < patch->num_sinks; i++) {
3832 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3833 return INVALID_OPERATION;
3834 }
3835 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003836
3837 sp<AudioPatch> patchDesc;
3838 ssize_t index = mAudioPatches.indexOfKey(*handle);
3839
François Gaffieafd4cea2019-11-18 15:50:22 +01003840 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
3841 patch->sources[0].role,
3842 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003843#if LOG_NDEBUG == 0
3844 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003845 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
3846 patch->sinks[i].role,
3847 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07003848 }
3849#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07003850
3851 if (index >= 0) {
3852 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003853 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
3854 __func__, mUidCached, patchDesc->getUid(), uid);
3855 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003856 return INVALID_OPERATION;
3857 }
3858 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07003859 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07003860 }
3861
3862 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003863 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003864 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003865 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003866 return BAD_VALUE;
3867 }
Eric Laurent84c70242014-06-23 08:46:27 -07003868 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3869 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003870 if (patchDesc != 0) {
3871 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003872 ALOGV("%s source id differs for patch current id %d new id %d",
3873 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003874 return BAD_VALUE;
3875 }
3876 }
Eric Laurent874c42872014-08-08 15:13:39 -07003877 DeviceVector devices;
3878 for (size_t i = 0; i < patch->num_sinks; i++) {
3879 // Only support mix to devices connection
3880 // TODO add support for mix to mix connection
3881 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003882 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07003883 return INVALID_OPERATION;
3884 }
3885 sp<DeviceDescriptor> devDesc =
3886 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3887 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003888 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07003889 return BAD_VALUE;
3890 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003891
François Gaffie11d30102018-11-02 16:09:09 +01003892 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07003893 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01003894 NULL, // updatedSamplingRate
3895 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003896 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01003897 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003898 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01003899 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003900 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07003901 return INVALID_OPERATION;
3902 }
3903 devices.add(devDesc);
3904 }
3905 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003906 return INVALID_OPERATION;
3907 }
Eric Laurent874c42872014-08-08 15:13:39 -07003908
Eric Laurent6a94d692014-05-20 11:18:06 -07003909 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003910 ALOGV("%s setting device %s on output %d",
3911 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01003912 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003913 index = mAudioPatches.indexOfKey(*handle);
3914 if (index >= 0) {
3915 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003916 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003917 }
3918 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003919 patchDesc->setUid(uid);
3920 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003921 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003922 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003923 return INVALID_OPERATION;
3924 }
3925 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3926 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3927 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07003928 // only one sink supported when connecting an input device to a mix
3929 if (patch->num_sinks > 1) {
3930 return INVALID_OPERATION;
3931 }
François Gaffie53615e22015-03-19 09:24:12 +01003932 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003933 if (inputDesc == NULL) {
3934 return BAD_VALUE;
3935 }
3936 if (patchDesc != 0) {
3937 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3938 return BAD_VALUE;
3939 }
3940 }
François Gaffie11d30102018-11-02 16:09:09 +01003941 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07003942 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003943 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 return BAD_VALUE;
3945 }
3946
François Gaffie11d30102018-11-02 16:09:09 +01003947 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08003948 patch->sinks[0].sample_rate,
3949 NULL, /*updatedSampleRate*/
3950 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07003951 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003952 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07003953 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08003954 // FIXME for the parameter type,
3955 // and the NONE
3956 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003957 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003958 return INVALID_OPERATION;
3959 }
3960 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01003961 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01003962 device->toString().c_str(), inputDesc->mIoHandle);
3963 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07003964 index = mAudioPatches.indexOfKey(*handle);
3965 if (index >= 0) {
3966 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01003967 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003968 }
3969 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01003970 patchDesc->setUid(uid);
3971 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01003973 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 return INVALID_OPERATION;
3975 }
3976 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3977 // device to device connection
3978 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07003979 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003980 return BAD_VALUE;
3981 }
3982 }
François Gaffie11d30102018-11-02 16:09:09 +01003983 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07003984 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01003985 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07003986 return BAD_VALUE;
3987 }
Eric Laurent874c42872014-08-08 15:13:39 -07003988
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 //update source and sink with our own data as the data passed in the patch may
3990 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01003991 PatchBuilder patchBuilder;
3992 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11003993
3994 // if first sink is to MSD, establish single MSD patch
3995 if (getMsdAudioOutDevices().contains(
3996 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
3997 ALOGV("%s patching to MSD", __FUNCTION__);
3998 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
3999 goto installPatch;
4000 }
4001
François Gaffieafd4cea2019-11-18 15:50:22 +01004002 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4003 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004004
Eric Laurent874c42872014-08-08 15:13:39 -07004005 for (size_t i = 0; i < patch->num_sinks; i++) {
4006 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004007 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004008 return INVALID_OPERATION;
4009 }
François Gaffie11d30102018-11-02 16:09:09 +01004010 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004011 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004012 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004013 return BAD_VALUE;
4014 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004015 audio_port_config sinkPortConfig = {};
4016 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4017 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004018
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004019 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4020 // volume management purpose (tracking activity)
4021 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4022 // in config XML to reach the sink so that is can be declared as available.
4023 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4024 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4025 if (sourceDesc != nullptr) {
4026 // take care of dynamic routing for SwOutput selection,
4027 audio_attributes_t attributes = sourceDesc->attributes();
4028 audio_stream_type_t stream = sourceDesc->stream();
4029 audio_attributes_t resultAttr;
4030 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4031 config.sample_rate = sourceDesc->config().sample_rate;
4032 config.channel_mask = sourceDesc->config().channel_mask;
4033 config.format = sourceDesc->config().format;
4034 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4035 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4036 bool isRequestedDeviceForExclusiveUse = false;
4037 output_type_t outputType;
4038 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4039 &stream, sourceDesc->uid(), &config, &flags,
4040 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4041 nullptr, &outputType);
4042 if (output == AUDIO_IO_HANDLE_NONE) {
4043 ALOGV("%s no output for device %s",
4044 __FUNCTION__, sinkDevice->toString().c_str());
4045 return INVALID_OPERATION;
4046 }
4047 outputDesc = mOutputs.valueFor(output);
4048 if (outputDesc->isDuplicated()) {
4049 ALOGE("%s output is duplicated", __func__);
4050 return INVALID_OPERATION;
4051 }
4052 sourceDesc->setSwOutput(outputDesc);
4053 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004054 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004055 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004056 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004057 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004058 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4059 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004060 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4061 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004062 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4063 (sourceDesc != nullptr &&
4064 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004065 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004066 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004067 return INVALID_OPERATION;
4068 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004069 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004070 SortedVector<audio_io_handle_t> outputs =
4071 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4072 // if the sink device is reachable via an opened output stream, request to
4073 // go via this output stream by adding a second source to the patch
4074 // description
4075 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004076 if (output != AUDIO_IO_HANDLE_NONE) {
4077 outputDesc = mOutputs.valueFor(output);
4078 if (outputDesc->isDuplicated()) {
4079 ALOGV("%s output for device %s is duplicated",
4080 __FUNCTION__, sinkDevice->toString().c_str());
4081 return INVALID_OPERATION;
4082 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004083 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004084 }
4085 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004086 audio_port_config srcMixPortConfig = {};
4087 outputDesc->toAudioPortConfig(&srcMixPortConfig, &patch->sources[0]);
François Gaffieafd4cea2019-11-18 15:50:22 +01004088 // for volume control, we may need a valid stream
4089 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4090 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4091 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004092 }
Eric Laurent83b88082014-06-20 18:31:16 -07004093 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004094 }
4095 // TODO: check from routing capabilities in config file and other conflicting patches
4096
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004097installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004098 status_t status = installPatch(
4099 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004100 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004101 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004102 return INVALID_OPERATION;
4103 }
4104 } else {
4105 return BAD_VALUE;
4106 }
4107 } else {
4108 return BAD_VALUE;
4109 }
4110 return NO_ERROR;
4111}
4112
4113status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4114 uid_t uid)
4115{
4116 ALOGV("releaseAudioPatch() patch %d", handle);
4117
4118 ssize_t index = mAudioPatches.indexOfKey(handle);
4119
4120 if (index < 0) {
4121 return BAD_VALUE;
4122 }
4123 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004124 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4125 __func__, mUidCached, patchDesc->getUid(), uid);
4126 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004127 return INVALID_OPERATION;
4128 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004129 return releaseAudioPatchInternal(handle);
4130}
Eric Laurent6a94d692014-05-20 11:18:06 -07004131
François Gaffieafd4cea2019-11-18 15:50:22 +01004132status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4133 uint32_t delayMs)
4134{
4135 ALOGV("%s patch %d", __func__, handle);
4136 if (mAudioPatches.indexOfKey(handle) < 0) {
4137 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4138 return BAD_VALUE;
4139 }
4140 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004141 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004142 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004143 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004144 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004145 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004147 return BAD_VALUE;
4148 }
4149
François Gaffie11d30102018-11-02 16:09:09 +01004150 setOutputDevices(outputDesc,
4151 getNewOutputDevices(outputDesc, true /*fromCache*/),
4152 true,
4153 0,
4154 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4156 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004157 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004158 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004159 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004160 return BAD_VALUE;
4161 }
4162 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004163 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004164 true,
4165 NULL);
4166 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004167 status_t status =
4168 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4169 ALOGV("%s patch panel returned %d patchHandle %d",
4170 __func__, status, patchDesc->getAfHandle());
4171 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004173 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004174 // SW Bridge
4175 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4176 sp<SwAudioOutputDescriptor> outputDesc =
4177 mOutputs.getOutputFromId(patch->sources[1].id);
4178 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004179 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4180 // releaseOutput has already called closeOuput in case of direct output
4181 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004182 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004183 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4184 // force SwOutput patch removal as AF counter part patch has already gone.
4185 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4186 removeAudioPatch(outputDesc->getPatchHandle());
4187 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004188 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4189 setOutputDevices(outputDesc,
4190 getNewOutputDevices(outputDesc, true /*fromCache*/),
4191 true, /*force*/
4192 0,
4193 NULL);
4194 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 } else {
4196 return BAD_VALUE;
4197 }
4198 } else {
4199 return BAD_VALUE;
4200 }
4201 return NO_ERROR;
4202}
4203
4204status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4205 struct audio_patch *patches,
4206 unsigned int *generation)
4207{
François Gaffie53615e22015-03-19 09:24:12 +01004208 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004209 return BAD_VALUE;
4210 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004211 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004212 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004213}
4214
Eric Laurente1715a42014-05-20 11:30:42 -07004215status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004216{
Eric Laurente1715a42014-05-20 11:30:42 -07004217 ALOGV("setAudioPortConfig()");
4218
4219 if (config == NULL) {
4220 return BAD_VALUE;
4221 }
4222 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4223 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004224 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4225 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004226 }
4227
Eric Laurenta121f902014-06-03 13:32:54 -07004228 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004229 if (config->type == AUDIO_PORT_TYPE_MIX) {
4230 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004232 if (outputDesc == NULL) {
4233 return BAD_VALUE;
4234 }
Eric Laurent84c70242014-06-23 08:46:27 -07004235 ALOG_ASSERT(!outputDesc->isDuplicated(),
4236 "setAudioPortConfig() called on duplicated output %d",
4237 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004238 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004239 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004240 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004241 if (inputDesc == NULL) {
4242 return BAD_VALUE;
4243 }
Eric Laurenta121f902014-06-03 13:32:54 -07004244 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004245 } else {
4246 return BAD_VALUE;
4247 }
4248 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4249 sp<DeviceDescriptor> deviceDesc;
4250 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4251 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4252 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4253 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4254 } else {
4255 return BAD_VALUE;
4256 }
4257 if (deviceDesc == NULL) {
4258 return BAD_VALUE;
4259 }
Eric Laurenta121f902014-06-03 13:32:54 -07004260 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004261 } else {
4262 return BAD_VALUE;
4263 }
4264
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004265 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004266 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4267 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004268 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004269 audioPortConfig->toAudioPortConfig(&newConfig, config);
4270 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004271 }
Eric Laurenta121f902014-06-03 13:32:54 -07004272 if (status != NO_ERROR) {
4273 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004274 }
Eric Laurente1715a42014-05-20 11:30:42 -07004275
4276 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004277}
4278
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004279void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4280{
Eric Laurentd60560a2015-04-10 11:31:20 -07004281 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004282 clearAudioPatches(uid);
4283 clearSessionRoutes(uid);
4284}
4285
Eric Laurent6a94d692014-05-20 11:18:06 -07004286void AudioPolicyManager::clearAudioPatches(uid_t uid)
4287{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004288 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004289 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004290 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004291 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 }
4293 }
4294}
4295
François Gaffiec005e562018-11-06 15:04:49 +01004296void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004297{
François Gaffiec005e562018-11-06 15:04:49 +01004298 // Take the first attributes following the product strategy as it is used to retrieve the routed
4299 // device. All attributes wihin a strategy follows the same "routing strategy"
4300 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4301 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004302 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004303 for (size_t j = 0; j < mOutputs.size(); j++) {
4304 if (mOutputs.keyAt(j) == ouptutToSkip) {
4305 continue;
4306 }
4307 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004308 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004309 continue;
4310 }
4311 // If the default device for this strategy is on another output mix,
4312 // invalidate all tracks in this strategy to force re connection.
4313 // Otherwise select new device on the output mix.
4314 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004315 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4316 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004317 }
4318 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004319 setOutputDevices(
4320 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004321 }
4322 }
4323}
4324
4325void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4326{
4327 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004328 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004329 for (size_t i = 0; i < mOutputs.size(); i++) {
4330 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004331 for (const auto& client : outputDesc->getClientIterable()) {
4332 if (client->hasPreferredDevice() && client->uid() == uid) {
4333 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004334 auto clientStrategy = client->strategy();
4335 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4336 end(affectedStrategies)) {
4337 continue;
4338 }
4339 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004340 }
4341 }
4342 }
4343 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004344 for (const auto& strategy : affectedStrategies) {
4345 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004346 }
4347
4348 // remove input routes associated with this uid
4349 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004350 for (size_t i = 0; i < mInputs.size(); i++) {
4351 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004352 for (const auto& client : inputDesc->getClientIterable()) {
4353 if (client->hasPreferredDevice() && client->uid() == uid) {
4354 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4355 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004356 }
4357 }
4358 }
4359 // reroute inputs if necessary
4360 SortedVector<audio_io_handle_t> inputsToClose;
4361 for (size_t i = 0; i < mInputs.size(); i++) {
4362 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004363 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004364 inputsToClose.add(inputDesc->mIoHandle);
4365 }
4366 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004367 for (const auto& input : inputsToClose) {
4368 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004369 }
4370}
4371
Eric Laurentd60560a2015-04-10 11:31:20 -07004372void AudioPolicyManager::clearAudioSources(uid_t uid)
4373{
4374 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004375 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4376 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004377 stopAudioSource(mAudioSources.keyAt(i));
4378 }
4379 }
4380}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004381
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004382status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4383 audio_io_handle_t *ioHandle,
4384 audio_devices_t *device)
4385{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004386 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4387 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004388 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004389 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004390
François Gaffiedf372692015-03-19 10:43:27 +01004391 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004392}
4393
Eric Laurentd60560a2015-04-10 11:31:20 -07004394status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004395 const audio_attributes_t *attributes,
4396 audio_port_handle_t *portId,
4397 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004398{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004399 ALOGV("%s", __FUNCTION__);
4400 *portId = AUDIO_PORT_HANDLE_NONE;
4401
4402 if (source == NULL || attributes == NULL || portId == NULL) {
4403 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4404 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004405 return BAD_VALUE;
4406 }
4407
Eric Laurentd60560a2015-04-10 11:31:20 -07004408 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4409 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004410 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4411 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004412 return INVALID_OPERATION;
4413 }
4414
François Gaffie11d30102018-11-02 16:09:09 +01004415 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004416 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004417 String8(source->ext.device.address),
4418 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004419 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004420 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004421 return BAD_VALUE;
4422 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004423
jiabin4ef93452019-09-10 14:29:54 -07004424 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004425
François Gaffieaaac0fd2018-11-22 17:56:39 +01004426 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004427 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004428 mEngine->getStreamTypeForAttributes(*attributes),
4429 mEngine->getProductStrategyForAttributes(*attributes),
4430 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004431
4432 status_t status = connectAudioSource(sourceDesc);
4433 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004434 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004435 }
4436 return status;
4437}
4438
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004439status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004440{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004441 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004442
4443 // make sure we only have one patch per source.
4444 disconnectAudioSource(sourceDesc);
4445
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004446 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004447 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4448 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4449 sourceDesc->srcDevice()->type(),
4450 String8(sourceDesc->srcDevice()->address().c_str()),
4451 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004452 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004453 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004454 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004455 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004456 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4457 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4458 return INVALID_OPERATION;
4459 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004460 PatchBuilder patchBuilder;
4461 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4462 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4463 status_t status =
4464 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4465 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4466 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4467 return INVALID_OPERATION;
4468 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004469 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004470 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4471 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4472 if (swOutput != 0) {
4473 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004474 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004475 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004476 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004477 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004478 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004479 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004480 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004482 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004483 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004484 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004485 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4486 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004487 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004488 if (delayMs != 0) {
4489 usleep(delayMs * 1000);
4490 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004491 } else {
4492 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4493 if (hwOutputDesc != 0) {
4494 // create Hwoutput and add to mHwOutputs
4495 } else {
4496 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4497 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004498 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004499 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004500
4501FailureSourceActive:
4502 swOutput->stop();
4503 releaseOutput(sourceDesc->portId());
4504FailureSourceAdded:
4505 sourceDesc->setSwOutput(nullptr);
4506FailureReleasePatch:
4507 releaseAudioPatchInternal(handle);
4508 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004509}
4510
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004511status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004512{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004513 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4514 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004515 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004516 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004517 return BAD_VALUE;
4518 }
4519 status_t status = disconnectAudioSource(sourceDesc);
4520
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004521 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004522 return status;
4523}
4524
Andy Hung2ddee192015-12-18 17:34:44 -08004525status_t AudioPolicyManager::setMasterMono(bool mono)
4526{
4527 if (mMasterMono == mono) {
4528 return NO_ERROR;
4529 }
4530 mMasterMono = mono;
4531 // if enabling mono we close all offloaded devices, which will invalidate the
4532 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4533 // for recreating the new AudioTrack as non-offloaded PCM.
4534 //
4535 // If disabling mono, we leave all tracks as is: we don't know which clients
4536 // and tracks are able to be recreated as offloaded. The next "song" should
4537 // play back offloaded.
4538 if (mMasterMono) {
4539 Vector<audio_io_handle_t> offloaded;
4540 for (size_t i = 0; i < mOutputs.size(); ++i) {
4541 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4542 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4543 offloaded.push(desc->mIoHandle);
4544 }
4545 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004546 for (const auto& handle : offloaded) {
4547 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004548 }
4549 }
4550 // update master mono for all remaining outputs
4551 for (size_t i = 0; i < mOutputs.size(); ++i) {
4552 updateMono(mOutputs.keyAt(i));
4553 }
4554 return NO_ERROR;
4555}
4556
4557status_t AudioPolicyManager::getMasterMono(bool *mono)
4558{
4559 *mono = mMasterMono;
4560 return NO_ERROR;
4561}
4562
Eric Laurentac9cef52017-06-09 15:46:26 -07004563float AudioPolicyManager::getStreamVolumeDB(
4564 audio_stream_type_t stream, int index, audio_devices_t device)
4565{
jiabin9a3361e2019-10-01 09:38:30 -07004566 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004567}
4568
jiabin81772902018-04-02 17:52:27 -07004569status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4570 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004571 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004572{
Kriti Dang6537def2021-03-02 13:46:59 +01004573 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4574 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004575 return BAD_VALUE;
4576 }
Kriti Dang6537def2021-03-02 13:46:59 +01004577 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4578 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004579
4580 size_t formatsWritten = 0;
4581 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004582
Kriti Dang6537def2021-03-02 13:46:59 +01004583 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004584 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4585 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004586 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004587 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004588 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004589 bool formatEnabled = true;
4590 switch (forceUse) {
4591 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004592 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004593 break;
4594 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4595 formatEnabled = false;
4596 break;
4597 default: // AUTO or ALWAYS => true
4598 break;
jiabin81772902018-04-02 17:52:27 -07004599 }
4600 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4601 }
jiabin81772902018-04-02 17:52:27 -07004602 }
4603 return NO_ERROR;
4604}
4605
Kriti Dang6537def2021-03-02 13:46:59 +01004606status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4607 audio_format_t *surroundFormats) {
4608 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4609 return BAD_VALUE;
4610 }
4611 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4612 __func__, *numSurroundFormats, surroundFormats);
4613
4614 size_t formatsWritten = 0;
4615 size_t formatsMax = *numSurroundFormats;
4616 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4617
4618 // Return formats from all device profiles that have already been resolved by
4619 // checkOutputsForDevice().
4620 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4621 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4622 audio_devices_t deviceType = device->type();
4623 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4624 // returns formats reported by HDMI devices.
4625 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4626 continue;
4627 }
4628 // Formats reported by sink devices
4629 std::unordered_set<audio_format_t> formatset;
4630 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4631 formatset.insert(it->second.begin(), it->second.end());
4632 }
4633
4634 // Formats hard-coded in the in policy configuration file (if any).
4635 FormatVector encodedFormats = device->encodedFormats();
4636 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4637 // Filter the formats which are supported by the vendor hardware.
4638 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4639 if (mConfig.getSurroundFormats().count(*it) != 0) {
4640 formats.insert(*it);
4641 } else {
4642 for (const auto& pair : mConfig.getSurroundFormats()) {
4643 if (pair.second.count(*it) != 0) {
4644 formats.insert(pair.first);
4645 break;
4646 }
4647 }
4648 }
4649 }
4650 }
4651 *numSurroundFormats = formats.size();
4652 for (const auto& format: formats) {
4653 if (formatsWritten < formatsMax) {
4654 surroundFormats[formatsWritten++] = format;
4655 }
4656 }
4657 return NO_ERROR;
4658}
4659
jiabin81772902018-04-02 17:52:27 -07004660status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4661{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004662 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004663 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4664 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004665 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004666 return BAD_VALUE;
4667 }
4668
Mikhail Naganov100f0122018-11-29 11:22:16 -08004669 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4670 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004671 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004672 return INVALID_OPERATION;
4673 }
4674
Mikhail Naganov100f0122018-11-29 11:22:16 -08004675 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004676 return NO_ERROR;
4677 }
4678
Mikhail Naganov100f0122018-11-29 11:22:16 -08004679 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004680 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004681 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004682 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004683 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004684 }
4685 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004686 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004687 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004688 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004689 }
4690 }
4691
4692 sp<SwAudioOutputDescriptor> outputDesc;
4693 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004694 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4695 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004696 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4697 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004698 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004699 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004700 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4701 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4702 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004703 name.c_str(),
4704 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004705 if (status != NO_ERROR) {
4706 continue;
4707 }
4708 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4709 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
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 profileUpdated |= (status == NO_ERROR);
4714 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004715 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004716 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004717 AUDIO_DEVICE_IN_HDMI);
4718 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4719 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004720 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004721 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004722 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4723 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4724 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004725 name.c_str(),
4726 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004727 if (status != NO_ERROR) {
4728 continue;
4729 }
4730 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4731 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
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 profileUpdated |= (status == NO_ERROR);
4736 }
4737
jiabin81772902018-04-02 17:52:27 -07004738 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004739 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004740 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004741 }
4742
4743 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4744}
4745
Eric Laurent5ada82e2019-08-29 17:53:54 -07004746void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004747{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004748 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004749 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004750 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004751 }
4752}
4753
jiabin6012f912018-11-02 17:06:30 -07004754bool AudioPolicyManager::isHapticPlaybackSupported()
4755{
4756 for (const auto& hwModule : mHwModules) {
4757 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4758 for (const auto &outProfile : outputProfiles) {
4759 struct audio_port audioPort;
4760 outProfile->toAudioPort(&audioPort);
4761 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4762 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4763 return true;
4764 }
4765 }
4766 }
4767 }
4768 return false;
4769}
4770
Eric Laurent8340e672019-11-06 11:01:08 -08004771bool AudioPolicyManager::isCallScreenModeSupported()
4772{
4773 return getConfig().isCallScreenModeSupported();
4774}
4775
4776
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004777status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004778{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004779 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004780 if (!sourceDesc->isConnected()) {
4781 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
4782 return NO_ERROR;
4783 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004784 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4785 if (swOutput != 0) {
4786 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08004787 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004788 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08004789 }
jiabinbce0c1d2020-10-05 11:20:18 -07004790 if (releaseOutput(sourceDesc->portId())) {
4791 // The output descriptor is reopened to query dynamic profiles. In that case, there is
4792 // no need to release audio patch here but just return NO_ERROR.
4793 return NO_ERROR;
4794 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004795 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004796 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07004797 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004798 // close Hwoutput and remove from mHwOutputs
4799 } else {
4800 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4801 }
4802 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004803 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
4804 sourceDesc->disconnect();
4805 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07004806}
4807
François Gaffiec005e562018-11-06 15:04:49 +01004808sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4809 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07004810{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004811 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07004812 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004813 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004814 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01004815 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4816 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004817 source = sourceDesc;
4818 break;
4819 }
4820 }
4821 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07004822}
4823
Eric Laurente552edb2014-03-10 17:42:56 -07004824// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07004825// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07004826// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07004827uint32_t AudioPolicyManager::nextAudioPortGeneration()
4828{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08004829 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004830}
4831
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004832static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07004833 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
4834 !audioPolicyXmlConfigFile.empty()) {
4835 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
4836 if (ret == NO_ERROR) {
4837 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08004838 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004839 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07004840 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07004841 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004842}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09004843
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004844AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4845 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07004846 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07004847 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004848 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07004849 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07004850 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004851 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004852 mAudioPortGeneration(1),
4853 mBeaconMuteRefCount(0),
4854 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07004855 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08004856 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07004857 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08004858 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07004859{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004860}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004861
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004862AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4863 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4864{
4865 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004866}
François Gaffied1ab2bd2015-12-02 18:20:06 +01004867
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07004868void AudioPolicyManager::loadConfig() {
4869 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004870 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004871 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01004872 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004873}
4874
4875status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07004876 {
4877 auto engLib = EngineLibrary::load(
4878 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
4879 if (!engLib) {
4880 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
4881 return NO_INIT;
4882 }
4883 mEngine = engLib->createEngine();
4884 if (mEngine == nullptr) {
4885 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
4886 return NO_INIT;
4887 }
François Gaffie2110e042015-03-24 08:41:51 +01004888 }
4889 mEngine->setObserver(this);
4890 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004891 if (status != NO_ERROR) {
4892 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4893 return status;
4894 }
François Gaffie2110e042015-03-24 08:41:51 +01004895
Eric Laurent1d69c872021-01-11 18:53:01 +01004896 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
4897 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
4898
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004899 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07004900 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004901 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01004902
Eric Laurent3a4311c2014-03-17 12:00:47 -07004903 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01004904 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4905 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4906 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004907 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004908 }
jiabin9ff780e2018-03-19 18:19:52 -07004909 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07004910 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07004911 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07004912 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004913 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004914 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07004915 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07004916 }
4917 }
4918 }
Eric Laurente552edb2014-03-10 17:42:56 -07004919
Francois Gaffiebce7cd42020-10-14 16:13:20 +02004920 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07004921
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09004922 // Silence ALOGV statements
4923 property_set("log.tag." LOG_TAG, "D");
4924
Eric Laurente552edb2014-03-10 17:42:56 -07004925 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08004926 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07004927}
4928
Eric Laurente0720872014-03-11 09:30:41 -07004929AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07004930{
Eric Laurente552edb2014-03-10 17:42:56 -07004931 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004932 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004933 }
4934 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08004935 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07004936 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004937 mAvailableOutputDevices.clear();
4938 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004939 mOutputs.clear();
4940 mInputs.clear();
4941 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08004942 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004943 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004944}
4945
Eric Laurente0720872014-03-11 09:30:41 -07004946status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07004947{
Eric Laurent87ffa392015-05-22 10:32:38 -07004948 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004949}
4950
Eric Laurente552edb2014-03-10 17:42:56 -07004951// ---
4952
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004953void AudioPolicyManager::onNewAudioModulesAvailable()
4954{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07004955 DeviceVector newDevices;
4956 onNewAudioModulesAvailableInt(&newDevices);
4957 if (!newDevices.empty()) {
4958 nextAudioPortGeneration();
4959 mpClientInterface->onAudioPortListUpdate();
4960 }
4961}
4962
4963void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
4964{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004965 for (const auto& hwModule : mHwModulesAll) {
4966 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
4967 continue;
4968 }
4969 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4970 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4971 ALOGW("could not open HW module %s", hwModule->getName());
4972 continue;
4973 }
4974 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10004975 // open all output streams needed to access attached devices.
4976 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004977 // This also validates mAvailableOutputDevices list
4978 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4979 if (!outProfile->canOpenNewIo()) {
4980 ALOGE("Invalid Output profile max open count %u for profile %s",
4981 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4982 continue;
4983 }
4984 if (!outProfile->hasSupportedDevices()) {
4985 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4986 continue;
4987 }
4988 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4989 mTtsOutputAvailable = true;
4990 }
4991
Mikhail Naganovc0d04982020-03-02 21:02:28 +00004992 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4993 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
4994 sp<DeviceDescriptor> supportedDevice = 0;
4995 if (supportedDevices.contains(mDefaultOutputDevice)) {
4996 supportedDevice = mDefaultOutputDevice;
4997 } else {
4998 // choose first device present in profile's SupportedDevices also part of
4999 // mAvailableOutputDevices.
5000 if (availProfileDevices.isEmpty()) {
5001 continue;
5002 }
5003 supportedDevice = availProfileDevices.itemAt(0);
5004 }
5005 if (!mOutputDevicesAll.contains(supportedDevice)) {
5006 continue;
5007 }
5008 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5009 mpClientInterface);
5010 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5011 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
5012 AUDIO_STREAM_DEFAULT,
5013 AUDIO_OUTPUT_FLAG_NONE, &output);
5014 if (status != NO_ERROR) {
5015 ALOGW("Cannot open output stream for devices %s on hw module %s",
5016 supportedDevice->toString().c_str(), hwModule->getName());
5017 continue;
5018 }
5019 for (const auto &device : availProfileDevices) {
5020 // give a valid ID to an attached device once confirmed it is reachable
5021 if (!device->isAttached()) {
5022 device->attach(hwModule);
5023 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005024 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005025 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005026 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5027 }
5028 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005029 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005030 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5031 mPrimaryOutput = outputDesc;
5032 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005033 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
5034 outputDesc->close();
5035 } else {
5036 addOutput(output, outputDesc);
5037 setOutputDevices(outputDesc,
5038 DeviceVector(supportedDevice),
5039 true,
5040 0,
5041 NULL);
5042 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005043 }
5044 // open input streams needed to access attached devices to validate
5045 // mAvailableInputDevices list
5046 for (const auto& inProfile : hwModule->getInputProfiles()) {
5047 if (!inProfile->canOpenNewIo()) {
5048 ALOGE("Invalid Input profile max open count %u for profile %s",
5049 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5050 continue;
5051 }
5052 if (!inProfile->hasSupportedDevices()) {
5053 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5054 continue;
5055 }
5056 // chose first device present in profile's SupportedDevices also part of
5057 // available input devices
5058 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5059 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5060 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005061 ALOGV("%s: Input device list is empty! for profile %s",
5062 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005063 continue;
5064 }
5065 sp<AudioInputDescriptor> inputDesc =
5066 new AudioInputDescriptor(inProfile, mpClientInterface);
5067
5068 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5069 status_t status = inputDesc->open(nullptr,
5070 availProfileDevices.itemAt(0),
5071 AUDIO_SOURCE_MIC,
5072 AUDIO_INPUT_FLAG_NONE,
5073 &input);
5074 if (status != NO_ERROR) {
5075 ALOGW("Cannot open input stream for device %s on hw module %s",
5076 availProfileDevices.toString().c_str(),
5077 hwModule->getName());
5078 continue;
5079 }
5080 for (const auto &device : availProfileDevices) {
5081 // give a valid ID to an attached device once confirmed it is reachable
5082 if (!device->isAttached()) {
5083 device->attach(hwModule);
5084 device->importAudioPortAndPickAudioProfile(inProfile, true);
5085 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005086 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005087 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5088 }
5089 }
5090 inputDesc->close();
5091 }
5092 }
5093}
5094
Eric Laurent98e38192018-02-15 18:31:53 -08005095void AudioPolicyManager::addOutput(audio_io_handle_t output,
5096 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005097{
Eric Laurent1c333e22014-05-20 10:48:17 -07005098 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005099 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005100 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005101 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005102 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005103}
5104
François Gaffie53615e22015-03-19 09:24:12 +01005105void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5106{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005107 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5108 ALOGV("%s: removing primary output", __func__);
5109 mPrimaryOutput = nullptr;
5110 }
François Gaffie53615e22015-03-19 09:24:12 +01005111 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005112 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005113}
5114
Eric Laurent98e38192018-02-15 18:31:53 -08005115void AudioPolicyManager::addInput(audio_io_handle_t input,
5116 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005117{
Eric Laurent1c333e22014-05-20 10:48:17 -07005118 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005120}
Eric Laurente552edb2014-03-10 17:42:56 -07005121
François Gaffie11d30102018-11-02 16:09:09 +01005122status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005123 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005124 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005125{
François Gaffie11d30102018-11-02 16:09:09 +01005126 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005127 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005128 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005129
François Gaffie11d30102018-11-02 16:09:09 +01005130 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005131 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005132 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005133 }
Eric Laurente552edb2014-03-10 17:42:56 -07005134
Eric Laurent3b73df72014-03-11 09:06:29 -07005135 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005136 // first call getAudioPort to get the supported attributes from the HAL
5137 struct audio_port_v7 port = {};
5138 device->toAudioPort(&port);
5139 status_t status = mpClientInterface->getAudioPort(&port);
5140 if (status == NO_ERROR) {
5141 device->importAudioPort(port);
5142 }
5143
5144 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005145 for (size_t i = 0; i < mOutputs.size(); i++) {
5146 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005147 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005148 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005149 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5150 mOutputs.keyAt(i), device->toString().c_str());
5151 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005152 }
5153 }
5154 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005155 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005156 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005157 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5158 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005159 if (profile->supportsDevice(device)) {
5160 profiles.add(profile);
5161 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5162 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005163 }
5164 }
5165 }
5166
Eric Laurent7b279bb2015-12-14 10:18:23 -08005167 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005168
Eric Laurente552edb2014-03-10 17:42:56 -07005169 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005170 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005171 return BAD_VALUE;
5172 }
5173
5174 // open outputs for matching profiles if needed. Direct outputs are also opened to
5175 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5176 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005177 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005178
5179 // nothing to do if one output is already opened for this profile
5180 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005181 for (j = 0; j < outputs.size(); j++) {
5182 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005183 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005184 // matching profile: save the sample rates, format and channel masks supported
5185 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005186 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005187 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005188 }
Eric Laurente552edb2014-03-10 17:42:56 -07005189 break;
5190 }
5191 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005192 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005193 continue;
5194 }
5195
Eric Laurent3974e3b2017-12-07 17:58:43 -08005196 if (!profile->canOpenNewIo()) {
5197 ALOGW("Max Output number %u already opened for this profile %s",
5198 profile->maxOpenCount, profile->getTagName().c_str());
5199 continue;
5200 }
5201
Eric Laurent83efe1c2017-07-09 16:51:08 -07005202 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005203 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005204 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5205 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005206 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005207 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005208 profiles.removeAt(profile_index);
5209 profile_index--;
5210 } else {
5211 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005212 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005213 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005214 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5215 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005216 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005217 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005218
François Gaffie11d30102018-11-02 16:09:09 +01005219 if (device_distinguishes_on_address(deviceType)) {
5220 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5221 device->toString().c_str());
5222 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5223 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005224 }
Eric Laurente552edb2014-03-10 17:42:56 -07005225 ALOGV("checkOutputsForDevice(): adding output %d", output);
5226 }
5227 }
5228
5229 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005230 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005231 return BAD_VALUE;
5232 }
Eric Laurentd4692962014-05-05 18:13:44 -07005233 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005234 // check if one opened output is not needed any more after disconnecting one device
5235 for (size_t i = 0; i < mOutputs.size(); i++) {
5236 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005237 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005238 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005239 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005240 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005241 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005242 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005243 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5244 mOutputs.keyAt(i));
5245 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005246 }
Eric Laurente552edb2014-03-10 17:42:56 -07005247 }
5248 }
Eric Laurentd4692962014-05-05 18:13:44 -07005249 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005250 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005251 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5252 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005253 if (!profile->supportsDevice(device)) {
5254 continue;
5255 }
5256 ALOGV("checkOutputsForDevice(): "
5257 "clearing direct output profile %zu on module %s",
5258 j, hwModule->getName());
5259 profile->clearAudioProfiles();
5260 if (!profile->hasDynamicAudioProfile()) {
5261 continue;
5262 }
5263 // When a device is disconnected, if there is an IOProfile that contains dynamic
5264 // profiles and supports the disconnected device, call getAudioPort to repopulate
5265 // the capabilities of the devices that is supported by the IOProfile.
5266 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5267 if (supportedDevice == device ||
5268 !mAvailableOutputDevices.contains(supportedDevice)) {
5269 continue;
5270 }
5271 struct audio_port_v7 port;
5272 supportedDevice->toAudioPort(&port);
5273 status_t status = mpClientInterface->getAudioPort(&port);
5274 if (status == NO_ERROR) {
5275 supportedDevice->importAudioPort(port);
5276 }
Eric Laurente552edb2014-03-10 17:42:56 -07005277 }
5278 }
5279 }
5280 }
5281 return NO_ERROR;
5282}
5283
François Gaffie11d30102018-11-02 16:09:09 +01005284status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005285 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005286{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005287 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005288
François Gaffie11d30102018-11-02 16:09:09 +01005289 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005290 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005291 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005292 }
5293
Eric Laurentd4692962014-05-05 18:13:44 -07005294 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005295 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005296 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005297 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005298 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005299 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005300 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005301 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005302
François Gaffie11d30102018-11-02 16:09:09 +01005303 if (profile->supportsDevice(device)) {
5304 profiles.add(profile);
5305 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5306 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005307 }
5308 }
5309 }
5310
Eric Laurent0dd51852019-04-19 18:18:58 -07005311 if (profiles.isEmpty()) {
5312 ALOGW("%s: No input profile available for device %s",
5313 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005314 return BAD_VALUE;
5315 }
5316
5317 // open inputs for matching profiles if needed. Direct inputs are also opened to
5318 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5319 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5320
Eric Laurent1c333e22014-05-20 10:48:17 -07005321 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005322
Eric Laurentd4692962014-05-05 18:13:44 -07005323 // nothing to do if one input is already opened for this profile
5324 size_t input_index;
5325 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5326 desc = mInputs.valueAt(input_index);
5327 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005328 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005329 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005330 }
Eric Laurentd4692962014-05-05 18:13:44 -07005331 break;
5332 }
5333 }
5334 if (input_index != mInputs.size()) {
5335 continue;
5336 }
5337
Eric Laurent3974e3b2017-12-07 17:58:43 -08005338 if (!profile->canOpenNewIo()) {
5339 ALOGW("Max Input number %u already opened for this profile %s",
5340 profile->maxOpenCount, profile->getTagName().c_str());
5341 continue;
5342 }
5343
Eric Laurentfe231122017-11-17 17:48:06 -08005344 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005345 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005346 status_t status = desc->open(nullptr,
5347 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005348 AUDIO_SOURCE_MIC,
5349 AUDIO_INPUT_FLAG_NONE,
5350 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005351
Eric Laurentcf2c0212014-07-25 16:20:43 -07005352 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005353 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005354 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005355 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005356 mpClientInterface->setParameters(input, String8(param));
5357 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005358 }
François Gaffie11d30102018-11-02 16:09:09 +01005359 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005360 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005361 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005362 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005363 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005364 }
5365
Eric Laurent0dd51852019-04-19 18:18:58 -07005366 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005367 addInput(input, desc);
5368 }
5369 } // endif input != 0
5370
Eric Laurentcf2c0212014-07-25 16:20:43 -07005371 if (input == AUDIO_IO_HANDLE_NONE) {
Pattye4981552021-11-04 21:01:03 +08005372 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005373 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005374 profiles.removeAt(profile_index);
5375 profile_index--;
5376 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005377 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005378 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005379 }
Eric Laurentd4692962014-05-05 18:13:44 -07005380 ALOGV("checkInputsForDevice(): adding input %d", input);
5381 }
5382 } // end scan profiles
5383
5384 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005385 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005386 return BAD_VALUE;
5387 }
5388 } else {
5389 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005390 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005391 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005392 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005393 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005394 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005395 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005396 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005397 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5398 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005399 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005400 }
5401 }
5402 }
5403 } // end disconnect
5404
5405 return NO_ERROR;
5406}
5407
5408
Eric Laurente0720872014-03-11 09:30:41 -07005409void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005410{
5411 ALOGV("closeOutput(%d)", output);
5412
François Gaffie1c878552018-11-22 16:53:21 +01005413 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5414 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005415 ALOGW("closeOutput() unknown output %d", output);
5416 return;
5417 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005418 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005419 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005420
Eric Laurente552edb2014-03-10 17:42:56 -07005421 // look for duplicated outputs connected to the output being removed.
5422 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005423 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5424 if (dupOutput->isDuplicated() &&
5425 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5426 sp<SwAudioOutputDescriptor> remainingOutput =
5427 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005428 // As all active tracks on duplicated output will be deleted,
5429 // and as they were also referenced on the other output, the reference
5430 // count for their stream type must be adjusted accordingly on
5431 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005432 const bool wasActive = remainingOutput->isActive();
5433 // Note: no-op on the closing output where all clients has already been set inactive
5434 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005435 // stop() will be a no op if the output is still active but is needed in case all
5436 // active streams refcounts where cleared above
5437 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005438 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005439 }
Eric Laurente552edb2014-03-10 17:42:56 -07005440 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5441 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5442
5443 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005444 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005445 }
5446 }
5447
Eric Laurent05b90f82014-08-27 15:32:29 -07005448 nextAudioPortGeneration();
5449
François Gaffie1c878552018-11-22 16:53:21 +01005450 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005451 if (index >= 0) {
5452 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005453 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5454 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005455 mAudioPatches.removeItemsAt(index);
5456 mpClientInterface->onAudioPatchListUpdate();
5457 }
5458
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005459 if (closingOutputWasActive) {
5460 closingOutput->stop();
5461 }
François Gaffie1c878552018-11-22 16:53:21 +01005462 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005463
François Gaffie53615e22015-03-19 09:24:12 +01005464 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005465 mPreviousOutputs = mOutputs;
Dean Wheatley3023b382018-08-09 07:42:40 +10005466
5467 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5468 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005469 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005470 bool directOutputOpen = false;
5471 for (size_t i = 0; i < mOutputs.size(); i++) {
5472 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5473 directOutputOpen = true;
5474 break;
5475 }
5476 }
5477 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005478 ALOGV("no direct outputs open, reset MSD patches");
5479 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5480 // how output devices for patching are resolved. Avoid by caching and reusing the
5481 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5482 // devices to patch to. This may be complicated by the fact that devices may become
5483 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005484 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005485 }
5486 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005487}
5488
5489void AudioPolicyManager::closeInput(audio_io_handle_t input)
5490{
5491 ALOGV("closeInput(%d)", input);
5492
5493 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5494 if (inputDesc == NULL) {
5495 ALOGW("closeInput() unknown input %d", input);
5496 return;
5497 }
5498
Eric Laurent6a94d692014-05-20 11:18:06 -07005499 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005500
François Gaffie11d30102018-11-02 16:09:09 +01005501 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005502 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005503 if (index >= 0) {
5504 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005505 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5506 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005507 mAudioPatches.removeItemsAt(index);
5508 mpClientInterface->onAudioPatchListUpdate();
5509 }
5510
Eric Laurentfe231122017-11-17 17:48:06 -08005511 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005512 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005513
François Gaffie11d30102018-11-02 16:09:09 +01005514 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5515 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005516 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005517 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005518 }
Eric Laurente552edb2014-03-10 17:42:56 -07005519}
5520
François Gaffie11d30102018-11-02 16:09:09 +01005521SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5522 const DeviceVector &devices,
5523 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005524{
5525 SortedVector<audio_io_handle_t> outputs;
5526
François Gaffie11d30102018-11-02 16:09:09 +01005527 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005528 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01005529 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005530 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01005531 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005532 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07005533 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01005534 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005535 outputs.add(openOutputs.keyAt(i));
5536 }
5537 }
5538 return outputs;
5539}
5540
Mikhail Naganov37977152018-07-11 15:54:44 -07005541void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5542{
5543 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5544 // output is suspended before any tracks are moved to it
5545 checkA2dpSuspend();
5546 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08005547 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005548 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07005549 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00005550 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11005551 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
5552 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
5553 // configuration changes will ultimately be rerouted correctly. We can still avoid
5554 // unnecessary rerouting by caching and reusing the arguments to
5555 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
5556 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005557 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11005558 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07005559 // an event that changed routing likely occurred, inform upper layers
5560 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07005561}
5562
François Gaffiec005e562018-11-06 15:04:49 +01005563bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5564 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07005565{
François Gaffiec005e562018-11-06 15:04:49 +01005566 return mEngine->getProductStrategyForAttributes(lAttr) ==
5567 mEngine->getProductStrategyForAttributes(rAttr);
5568}
5569
Francois Gaffieff1eb522020-05-06 18:37:04 +02005570void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
5571{
5572 for (size_t i = 0; i < mAudioSources.size(); i++) {
5573 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5574 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005575 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
5576 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02005577 connectAudioSource(sourceDesc);
5578 }
5579 }
5580}
5581
5582void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
5583{
5584 for (size_t i = 0; i < mAudioSources.size(); i++) {
5585 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5586 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
5587 && sourceDesc->swOutput().promote()->mIoHandle == output) {
5588 disconnectAudioSource(sourceDesc);
5589 }
5590 }
5591}
5592
François Gaffiec005e562018-11-06 15:04:49 +01005593void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5594{
5595 auto psId = mEngine->getProductStrategyForAttributes(attr);
5596
5597 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5598 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07005599
François Gaffie11d30102018-11-02 16:09:09 +01005600 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5601 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07005602
Eric Laurentc209fe42020-06-05 18:11:23 -07005603 uint32_t maxLatency = 0;
5604 bool invalidate = false;
5605 // take into account dynamic audio policies related changes: if a client is now associated
5606 // to a different policy mix than at creation time, invalidate corresponding stream
5607 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
5608 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
5609 if (desc->isDuplicated()) {
5610 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005611 }
Eric Laurentc209fe42020-06-05 18:11:23 -07005612 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
5613 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
5614 continue;
5615 }
5616 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005617 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5618 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07005619 if (status != OK) {
5620 continue;
5621 }
yucliuf4de36d2020-09-14 14:57:56 -07005622 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07005623 invalidate = true;
5624 if (desc->isStrategyActive(psId)) {
5625 maxLatency = desc->latency();
5626 }
5627 break;
5628 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08005629 }
5630 }
5631
Eric Laurentc209fe42020-06-05 18:11:23 -07005632 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005633 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5634 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07005635 for (audio_io_handle_t srcOut : srcOutputs) {
5636 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005637 if (desc == nullptr) continue;
5638
5639 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005640 maxLatency = desc->latency();
5641 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005642
5643 if (invalidate) continue;
5644
5645 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07005646 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07005647 // a client on a non direct outputs has necessarily a linear PCM format
5648 // so we can call selectOutput() safely
5649 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
5650 client->flags(),
5651 client->config().format,
5652 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07005653 client->config().sample_rate,
5654 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07005655 if (newOutput != srcOut) {
5656 invalidate = true;
5657 break;
5658 }
5659 } else {
5660 sp<IOProfile> profile = getProfileForOutput(newDevices,
5661 client->config().sample_rate,
5662 client->config().format,
5663 client->config().channel_mask,
5664 client->flags(),
5665 true /* directOnly */);
5666 if (profile != desc->mProfile) {
5667 invalidate = true;
5668 break;
5669 }
5670 }
5671 }
Eric Laurentac3a6902018-05-11 16:39:10 -07005672 }
Eric Laurentaa02db82019-09-05 17:31:49 -07005673
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005674 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01005675 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005676 std::to_string(srcOutputs[0]).c_str(),
5677 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07005678 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005679 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07005680 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07005681 if (desc == nullptr) continue;
5682
5683 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01005684 setStrategyMute(psId, true, desc);
5685 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01005686 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005687 }
François Gaffiec005e562018-11-06 15:04:49 +01005688 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005689 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005690 connectAudioSource(source);
5691 }
Eric Laurente552edb2014-03-10 17:42:56 -07005692 }
5693
François Gaffiec005e562018-11-06 15:04:49 +01005694 // Move effects associated to this stream from previous output to new output
5695 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07005696 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07005697 }
François Gaffiec005e562018-11-06 15:04:49 +01005698 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07005699 if (invalidate) {
5700 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5701 mpClientInterface->invalidateStream(stream);
5702 }
Eric Laurente552edb2014-03-10 17:42:56 -07005703 }
5704 }
5705}
5706
Eric Laurente0720872014-03-11 09:30:41 -07005707void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07005708{
François Gaffiec005e562018-11-06 15:04:49 +01005709 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5710 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5711 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02005712 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01005713 }
Eric Laurente552edb2014-03-10 17:42:56 -07005714}
5715
Kevin Rocard153f92d2018-12-18 18:33:28 -08005716void AudioPolicyManager::checkSecondaryOutputs() {
5717 std::set<audio_stream_type_t> streamsToInvalidate;
jiabinf042b9b2021-05-07 23:46:28 +00005718 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08005719 for (size_t i = 0; i < mOutputs.size(); i++) {
5720 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5721 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005722 sp<AudioPolicyMix> primaryMix;
5723 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005724 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
5725 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07005726 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5727 for (auto &secondaryMix : secondaryMixes) {
5728 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
5729 if (outputDesc != nullptr &&
5730 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
5731 secondaryDescs.push_back(outputDesc);
5732 }
5733 }
5734
jiabinf042b9b2021-05-07 23:46:28 +00005735 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08005736 streamsToInvalidate.insert(client->stream());
jiabinf042b9b2021-05-07 23:46:28 +00005737 } else if (!std::equal(
5738 client->getSecondaryOutputs().begin(),
5739 client->getSecondaryOutputs().end(),
5740 secondaryDescs.begin(), secondaryDescs.end())) {
5741 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
5742 std::vector<audio_io_handle_t> secondaryOutputIds;
5743 for (const auto& secondaryDesc : secondaryDescs) {
5744 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
5745 weakSecondaryDescs.push_back(secondaryDesc);
5746 }
5747 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
5748 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
Kevin Rocard153f92d2018-12-18 18:33:28 -08005749 }
5750 }
5751 }
jiabinf042b9b2021-05-07 23:46:28 +00005752 if (!trackSecondaryOutputs.empty()) {
5753 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
5754 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08005755 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabinf042b9b2021-05-07 23:46:28 +00005756 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08005757 mpClientInterface->invalidateStream(stream);
5758 }
5759}
5760
Eric Laurent2517af32020-11-25 15:31:27 +01005761bool AudioPolicyManager::isScoRequestedForComm() const {
5762 AudioDeviceTypeAddrVector devices;
5763 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
5764 for (const auto &device : devices) {
5765 if (audio_is_bluetooth_out_sco_device(device.mType)) {
5766 return true;
5767 }
5768 }
5769 return false;
5770}
5771
Eric Laurente0720872014-03-11 09:30:41 -07005772void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07005773{
François Gaffie53615e22015-03-19 09:24:12 +01005774 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08005775 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005776 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07005777 return;
5778 }
5779
Eric Laurent3a4311c2014-03-17 12:00:47 -07005780 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07005781 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
5782 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01005783 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07005784
5785 // if suspended, restore A2DP output if:
5786 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01005787 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07005788 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005789 //
Eric Laurentf732e072016-08-03 19:30:28 -07005790 // if not suspended, suspend A2DP output if:
5791 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01005792 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07005793 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07005794 //
5795 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07005796 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01005797 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07005798 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01005799 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005800
5801 mpClientInterface->restoreOutput(a2dpOutput);
5802 mA2dpSuspended = false;
5803 }
5804 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07005805 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01005806 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07005807 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01005808 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005809
5810 mpClientInterface->suspendOutput(a2dpOutput);
5811 mA2dpSuspended = true;
5812 }
5813 }
5814}
5815
François Gaffie11d30102018-11-02 16:09:09 +01005816DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5817 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07005818{
François Gaffie11d30102018-11-02 16:09:09 +01005819 DeviceVector devices;
5820
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005821 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005822 if (index >= 0) {
5823 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005824 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005825 ALOGV("%s device %s forced by patch %d", __func__,
5826 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5827 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07005828 }
5829 }
5830
Dean Wheatley514b4312020-06-17 21:45:00 +10005831 // Do not retrieve engine device for outputs through MSD
5832 // TODO: support explicit routing requests by resetting MSD patch to engine device.
5833 if (outputDesc->devices() == getMsdAudioOutDevices()) {
5834 return outputDesc->devices();
5835 }
5836
Eric Laurent97ac8712018-07-27 18:59:02 -07005837 // Honor explicit routing requests only if no client using default routing is active on this
5838 // input: a specific app can not force routing for other apps by setting a preferred device.
5839 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01005840 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01005841 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01005842 if (device != nullptr) {
5843 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07005844 }
5845
François Gaffiea807ef92018-11-05 10:44:33 +01005846 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5847 // of setForceUse / Default Bus device here
5848 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5849 if (device != nullptr) {
5850 return DeviceVector(device);
5851 }
5852
François Gaffiec005e562018-11-06 15:04:49 +01005853 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5854 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5855 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305856 auto hasStreamActive = [&](auto stream) {
5857 return hasStream(streams, stream) && isStreamActive(stream, 0);
5858 };
Eric Laurent484e9272018-06-07 17:29:23 -07005859
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305860 auto doGetOutputDevicesForVoice = [&]() {
5861 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
5862 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
5863 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02005864 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
5865 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305866 };
5867
5868 // With low-latency playing on speaker, music on WFD, when the first low-latency
5869 // output is stopped, getNewOutputDevices checks for a product strategy
5870 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00005871 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05305872 // devices are returned for STRATEGY_SONIFICATION without checking whether the
5873 // stream is associated to the output descriptor.
5874 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
5875 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
5876 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5877 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01005878 // Retrieval of devices for voice DL is done on primary output profile, cannot
5879 // check the route (would force modifying configuration file for this profile)
5880 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5881 break;
5882 }
Eric Laurente552edb2014-03-10 17:42:56 -07005883 }
François Gaffiec005e562018-11-06 15:04:49 +01005884 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01005885 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07005886}
5887
François Gaffie11d30102018-11-02 16:09:09 +01005888sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5889 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07005890{
François Gaffie11d30102018-11-02 16:09:09 +01005891 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07005892
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005893 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005894 if (index >= 0) {
5895 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005896 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01005897 ALOGV("getNewInputDevice() device %s forced by patch %d",
5898 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5899 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07005900 }
5901 }
5902
Eric Laurent97ac8712018-07-27 18:59:02 -07005903 // Honor explicit routing requests only if no client using default routing is active on this
5904 // input: a specific app can not force routing for other apps by setting a preferred device.
5905 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01005906 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5907 if (device != nullptr) {
5908 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07005909 }
5910
Eric Laurentdc95a252018-04-12 12:46:56 -07005911 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08005912 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08005913 audio_attributes_t attributes;
5914 uid_t uid;
5915 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
5916 if (topClient != nullptr) {
5917 attributes = topClient->attributes();
5918 uid = topClient->uid();
5919 } else {
5920 attributes = { .source = AUDIO_SOURCE_DEFAULT };
5921 uid = 0;
5922 }
5923
Francois Gaffie716e1432019-01-14 16:58:59 +01005924 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5925 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07005926 }
Francois Gaffie716e1432019-01-14 16:58:59 +01005927 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08005928 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08005929 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005930
Eric Laurente552edb2014-03-10 17:42:56 -07005931 return device;
5932}
5933
Eric Laurent794fde22016-03-11 09:50:45 -08005934bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5935 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08005936 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08005937}
5938
Eric Laurente0720872014-03-11 09:30:41 -07005939audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07005940 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01005941 // getOutputDevicesForStream's behavior for invalid streams.
5942 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5943 // device for music stream), but we want to return the empty set.
5944 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005945 return AUDIO_DEVICE_NONE;
5946 }
François Gaffie11d30102018-11-02 16:09:09 +01005947 DeviceVector activeDevices;
5948 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00005949 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
5950 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01005951 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08005952 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07005953 }
François Gaffiec005e562018-11-06 15:04:49 +01005954 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01005955 devices.merge(curDevices);
5956 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005957 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07005958 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01005959 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08005960 }
5961 }
Eric Laurente552edb2014-03-10 17:42:56 -07005962 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005963
Eric Laurentb0688d62018-08-14 15:49:18 -07005964 // Favor devices selected on active streams if any to report correct device in case of
5965 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01005966 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07005967 devices = activeDevices;
5968 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05005969 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5970 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07005971 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01005972 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07005973 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01005974 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05005975 }
jiabin9a3361e2019-10-01 09:38:30 -07005976 // FIXME: use DeviceTypeSet when Java layer is ready for it.
5977 return deviceTypesToBitMask(devices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005978}
5979
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005980status_t AudioPolicyManager::getDevicesForAttributes(
5981 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
5982 if (devices == nullptr) {
5983 return BAD_VALUE;
5984 }
5985 // check dynamic policies but only for primary descriptors (secondary not used for audible
5986 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07005987 sp<AudioPolicyMix> policyMix;
Dean Wheatleyf6537ae2022-02-04 11:10:48 +11005988 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
5989 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005990 if (status != OK) {
5991 return status;
5992 }
Eric Laurentc529cf62020-04-17 18:19:10 -07005993 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
5994 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
5995 devices->push_back(device);
5996 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005997 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08005998 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5999 for (const auto& device : curDevices) {
6000 devices->push_back(device->getDeviceTypeAddr());
6001 }
6002 return NO_ERROR;
6003}
6004
Eric Laurente0720872014-03-11 09:30:41 -07006005void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006006 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006007 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006008 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006009 updateDevicesAndOutputs();
6010 break;
6011 default:
6012 break;
6013 }
6014}
6015
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006016uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006017
6018 // skip beacon mute management if a dedicated TTS output is available
6019 if (mTtsOutputAvailable) {
6020 return 0;
6021 }
6022
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006023 switch(event) {
6024 case STARTING_OUTPUT:
6025 mBeaconMuteRefCount++;
6026 break;
6027 case STOPPING_OUTPUT:
6028 if (mBeaconMuteRefCount > 0) {
6029 mBeaconMuteRefCount--;
6030 }
6031 break;
6032 case STARTING_BEACON:
6033 mBeaconPlayingRefCount++;
6034 break;
6035 case STOPPING_BEACON:
6036 if (mBeaconPlayingRefCount > 0) {
6037 mBeaconPlayingRefCount--;
6038 }
6039 break;
6040 }
6041
6042 if (mBeaconMuteRefCount > 0) {
6043 // any playback causes beacon to be muted
6044 return setBeaconMute(true);
6045 } else {
6046 // no other playback: unmute when beacon starts playing, mute when it stops
6047 return setBeaconMute(mBeaconPlayingRefCount == 0);
6048 }
6049}
6050
6051uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6052 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6053 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6054 // keep track of muted state to avoid repeating mute/unmute operations
6055 if (mBeaconMuted != mute) {
6056 // mute/unmute AUDIO_STREAM_TTS on all outputs
6057 ALOGV("\t muting %d", mute);
6058 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006059 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006060 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006061 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006062 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006063 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006064 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006065 maxLatency = latency;
6066 }
6067 }
6068 mBeaconMuted = mute;
6069 return maxLatency;
6070 }
6071 return 0;
6072}
6073
Eric Laurente0720872014-03-11 09:30:41 -07006074void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006075{
François Gaffiec005e562018-11-06 15:04:49 +01006076 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006077 mPreviousOutputs = mOutputs;
6078}
6079
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006080uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006081 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006082 uint32_t delayMs)
6083{
6084 // mute/unmute strategies using an incompatible device combination
6085 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6086 // if unmuting, unmute only after the specified delay
6087 if (outputDesc->isDuplicated()) {
6088 return 0;
6089 }
6090
6091 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006092 DeviceVector devices = outputDesc->devices();
6093 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006094
François Gaffiec005e562018-11-06 15:04:49 +01006095 auto productStrategies = mEngine->getOrderedProductStrategies();
6096 for (const auto &productStrategy : productStrategies) {
6097 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6098 DeviceVector curDevices =
6099 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6100 curDevices = curDevices.filter(outputDesc->supportedDevices());
6101 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006102 bool doMute = false;
6103
François Gaffiec005e562018-11-06 15:04:49 +01006104 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006105 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006106 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6107 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006108 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006109 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006110 }
Eric Laurent99401132014-05-07 19:48:15 -07006111 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006112 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006113 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006114 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006115 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006116 continue;
6117 }
François Gaffiec005e562018-11-06 15:04:49 +01006118 ALOGVV("%s() %s (curDevice %s)", __func__,
6119 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6120 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6121 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006122 if (mute) {
6123 // FIXME: should not need to double latency if volume could be applied
6124 // immediately by the audioflinger mixer. We must account for the delay
6125 // between now and the next time the audioflinger thread for this output
6126 // will process a buffer (which corresponds to one buffer size,
6127 // usually 1/2 or 1/4 of the latency).
6128 if (muteWaitMs < desc->latency() * 2) {
6129 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006130 }
6131 }
6132 }
6133 }
6134 }
6135 }
6136
Eric Laurent99401132014-05-07 19:48:15 -07006137 // temporary mute output if device selection changes to avoid volume bursts due to
6138 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006139 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006140 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
6141 // temporary mute duration is conservatively set to 4 times the reported latency
6142 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
6143 if (muteWaitMs < tempMuteWaitMs) {
6144 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006145 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006146 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6147 // make sure that we do not start the temporary mute period too early in case of
6148 // delayed device change
6149 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6150 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006151 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006152 }
6153 }
6154
Eric Laurente552edb2014-03-10 17:42:56 -07006155 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6156 if (muteWaitMs > delayMs) {
6157 muteWaitMs -= delayMs;
6158 usleep(muteWaitMs * 1000);
6159 return muteWaitMs;
6160 }
6161 return 0;
6162}
6163
François Gaffie11d30102018-11-02 16:09:09 +01006164uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6165 const DeviceVector &devices,
6166 bool force,
6167 int delayMs,
6168 audio_patch_handle_t *patchHandle,
6169 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006170{
François Gaffie11d30102018-11-02 16:09:09 +01006171 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006172 uint32_t muteWaitMs;
6173
6174 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006175 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6176 nullptr /* patchHandle */, requiresMuteCheck);
6177 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6178 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006179 return muteWaitMs;
6180 }
Eric Laurente552edb2014-03-10 17:42:56 -07006181
6182 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006183 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006184 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006185
François Gaffie11d30102018-11-02 16:09:09 +01006186 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6187
6188 if (!filteredDevices.isEmpty()) {
6189 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006190 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006191
6192 // if the outputs are not materially active, there is no need to mute.
6193 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006194 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006195 } else {
6196 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6197 muteWaitMs = 0;
6198 }
Eric Laurente552edb2014-03-10 17:42:56 -07006199
Eric Laurent79ea9582020-06-11 18:49:24 -07006200 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6201 // output profile or if new device is not supported AND previous device(s) is(are) still
6202 // available (otherwise reset device must be done on the output)
6203 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6204 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6205 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6206 // restore previous device after evaluating strategy mute state
6207 outputDesc->setDevices(prevDevices);
6208 return muteWaitMs;
6209 }
6210
Eric Laurente552edb2014-03-10 17:42:56 -07006211 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006212 // the requested device is AUDIO_DEVICE_NONE
6213 // OR the requested device is the same as current device
6214 // AND force is not specified
6215 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006216 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006217 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006218 !force && outputDesc->getPatchHandle() != 0) {
6219 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6220 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006221 return muteWaitMs;
6222 }
6223
François Gaffie11d30102018-11-02 16:09:09 +01006224 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006225
Eric Laurente552edb2014-03-10 17:42:56 -07006226 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006227 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006228 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006229 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006230 PatchBuilder patchBuilder;
6231 patchBuilder.addSource(outputDesc);
6232 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6233 for (const auto &filteredDevice : filteredDevices) {
6234 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006235 }
6236
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006237 // Add half reported latency to delayMs when muteWaitMs is null in order
6238 // to avoid disordered sequence of muting volume and changing devices.
6239 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6240 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006241 }
Eric Laurente552edb2014-03-10 17:42:56 -07006242
6243 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006244 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006245
6246 return muteWaitMs;
6247}
6248
Eric Laurentc75307b2015-03-17 15:29:32 -07006249status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006250 int delayMs,
6251 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006252{
Eric Laurent6a94d692014-05-20 11:18:06 -07006253 ssize_t index;
6254 if (patchHandle) {
6255 index = mAudioPatches.indexOfKey(*patchHandle);
6256 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006257 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006258 }
6259 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006260 return INVALID_OPERATION;
6261 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006262 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006263 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006264 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006265 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006266 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006267 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006268 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006269 return status;
6270}
6271
6272status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006273 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006274 bool force,
6275 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006276{
6277 status_t status = NO_ERROR;
6278
Eric Laurent1f2f2232014-06-02 12:01:23 -07006279 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006280 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6281 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006282
François Gaffie11d30102018-11-02 16:09:09 +01006283 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006284 PatchBuilder patchBuilder;
6285 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006286 // AUDIO_SOURCE_HOTWORD is for internal use only:
6287 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006288 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6289 auto result = usecase;
6290 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6291 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6292 }
6293 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006294 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006295 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006296 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006297 }
6298 }
6299 return status;
6300}
6301
Eric Laurent6a94d692014-05-20 11:18:06 -07006302status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6303 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006304{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006305 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006306 ssize_t index;
6307 if (patchHandle) {
6308 index = mAudioPatches.indexOfKey(*patchHandle);
6309 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006310 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006311 }
6312 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006313 return INVALID_OPERATION;
6314 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006315 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006316 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006317 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006318 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006319 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006320 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006321 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006322 return status;
6323}
6324
François Gaffie11d30102018-11-02 16:09:09 +01006325sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006326 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006327 audio_format_t& format,
6328 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006329 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006330{
6331 // Choose an input profile based on the requested capture parameters: select the first available
6332 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006333 //
6334 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6335 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006336
Glenn Kasten730b9262018-03-29 15:01:26 -07006337 sp<IOProfile> firstInexact;
6338 uint32_t updatedSamplingRate = 0;
6339 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6340 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006341 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006342 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006343 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006344 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006345 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006346 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006347 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006348 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006349 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006350 &channelMask /*updatedChannelMask*/,
6351 // FIXME ugly cast
6352 (audio_output_flags_t) flags,
6353 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006354 return profile;
6355 }
François Gaffie11d30102018-11-02 16:09:09 +01006356 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006357 samplingRate,
6358 &updatedSamplingRate,
6359 format,
6360 &updatedFormat,
6361 channelMask,
6362 &updatedChannelMask,
6363 // FIXME ugly cast
6364 (audio_output_flags_t) flags,
6365 false /*exactMatchRequiredForInputFlags*/)) {
6366 firstInexact = profile;
6367 }
6368
Eric Laurente552edb2014-03-10 17:42:56 -07006369 }
6370 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006371 if (firstInexact != nullptr) {
6372 samplingRate = updatedSamplingRate;
6373 format = updatedFormat;
6374 channelMask = updatedChannelMask;
6375 return firstInexact;
6376 }
Eric Laurente552edb2014-03-10 17:42:56 -07006377 return NULL;
6378}
6379
François Gaffieaaac0fd2018-11-22 17:56:39 +01006380float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6381 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006382 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006383 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006384{
jiabin9a3361e2019-10-01 09:38:30 -07006385 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006386
6387 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6388 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6389 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6390 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006391 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6392 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6393 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6394 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006395 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006396
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006397 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006398 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6399 mOutputs.isActive(ringVolumeSrc, 0)) {
6400 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006401 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006402 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006403 }
6404
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006405 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006406 if ((volumeSource != callVolumeSrc && (isInCall() ||
6407 mOutputs.isActiveLocally(callVolumeSrc))) &&
6408 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6409 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6410 volumeSource == alarmVolumeSrc ||
6411 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6412 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6413 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006414 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006415 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006416 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006417 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006418 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006419 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006420 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6421 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6422 // programmatically muted.
6423 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6424 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6425 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006426 bool exemptFromCapping =
6427 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6428 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006429 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6430 volumeSource, volumeDb);
6431 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006432 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6433 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6434 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006435 }
6436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437 // if a headset is connected, apply the following rules to ring tones and notifications
6438 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006439 // - always attenuate notifications volume by 6dB
6440 // - attenuate ring tones volume by 6dB unless music is not playing and
6441 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006442 // - if music is playing, always limit the volume to current music volume,
6443 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006444 if (!Intersection(deviceTypes,
6445 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6446 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006447 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6448 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006449 ((volumeSource == alarmVolumeSrc ||
6450 volumeSource == ringVolumeSrc) ||
6451 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6452 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6453 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6454 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6455 curves.canBeMuted()) {
6456
Eric Laurente552edb2014-03-10 17:42:56 -07006457 // when the phone is ringing we must consider that music could have been paused just before
6458 // by the music application and behave as if music was active if the last music track was
6459 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006460 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006461 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006462 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006463 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006464 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6465 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006466 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006467 float musicVolDb = computeVolume(musicCurves,
6468 musicVolumeSrc,
6469 musicCurves.getVolumeIndex(musicDevice),
6470 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006471 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6472 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6473 if (volumeDb > minVolDb) {
6474 volumeDb = minVolDb;
6475 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006476 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006477 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6478 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6479 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006480 // on A2DP, also ensure notification volume is not too low compared to media when
6481 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006482 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006483 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006484 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6485 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006486 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6487 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006488 }
6489 }
jiabin9a3361e2019-10-01 09:38:30 -07006490 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006491 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006492 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006493 }
6494 }
6495
François Gaffie43c73442018-11-08 08:21:55 +01006496 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006497}
6498
Eric Laurent3839bc02018-07-10 18:33:34 -07006499int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006500 VolumeSource fromVolumeSource,
6501 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006502{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006503 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006504 return srcIndex;
6505 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006506 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6507 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006508 float minSrc = (float)srcCurves.getVolumeIndexMin();
6509 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6510 float minDst = (float)dstCurves.getVolumeIndexMin();
6511 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07006512
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08006513 // preserve mute request or correct range
6514 if (srcIndex < minSrc) {
6515 if (srcIndex == 0) {
6516 return 0;
6517 }
6518 srcIndex = minSrc;
6519 } else if (srcIndex > maxSrc) {
6520 srcIndex = maxSrc;
6521 }
Eric Laurent3839bc02018-07-10 18:33:34 -07006522 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
6523}
6524
François Gaffieaaac0fd2018-11-22 17:56:39 +01006525status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
6526 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006527 int index,
6528 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006529 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006530 int delayMs,
6531 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006532{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006533 // do not change actual attributes volume if the attributes is muted
6534 if (outputDesc->isMuted(volumeSource)) {
6535 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
6536 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07006537 return NO_ERROR;
6538 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006539 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6540 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
6541 bool isVoiceVolSrc = callVolSrc == volumeSource;
6542 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
6543
Eric Laurent2517af32020-11-25 15:31:27 +01006544 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07006545 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01006546 // if sco and call follow same curves, bypass forceUseForComm
6547 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006548 ((isVoiceVolSrc && isScoRequested) ||
6549 (isBtScoVolSrc && !isScoRequested))) {
6550 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
6551 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07006552 // Do not return an error here as AudioService will always set both voice call
6553 // and bluetooth SCO volumes due to stream aliasing.
6554 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07006555 }
jiabin9a3361e2019-10-01 09:38:30 -07006556 if (deviceTypes.empty()) {
6557 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07006558 }
Eric Laurent275e8e92014-11-30 15:14:47 -08006559
jiabin9a3361e2019-10-01 09:38:30 -07006560 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
6561 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07006562 // Force VoIP volume to max for bluetooth SCO device except if muted
6563 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07006564 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07006565 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08006566 }
jiabin9a3361e2019-10-01 09:38:30 -07006567 outputDesc->setVolume(
6568 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07006569
Eric Laurente8f2c0f2021-08-17 11:17:19 +02006570 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006571 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07006572 // 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 +01006573 if (isVoiceVolSrc) {
6574 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07006575 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07006576 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07006577 }
Eric Laurent18fba842016-03-31 14:41:26 -07006578 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07006579 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
6580 mLastVoiceVolume = voiceVolume;
6581 }
6582 }
Eric Laurente552edb2014-03-10 17:42:56 -07006583 return NO_ERROR;
6584}
6585
Eric Laurentc75307b2015-03-17 15:29:32 -07006586void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006587 const DeviceTypeSet& deviceTypes,
6588 int delayMs,
6589 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07006590{
jiabincd510522020-01-22 09:40:55 -08006591 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01006592 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
6593 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
6594 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07006595 curves.getVolumeIndex(deviceTypes),
6596 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07006597 }
6598}
6599
François Gaffiec005e562018-11-06 15:04:49 +01006600void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
6601 bool on,
6602 const sp<AudioOutputDescriptor>& outputDesc,
6603 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006604 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006605{
François Gaffieaaac0fd2018-11-22 17:56:39 +01006606 std::vector<VolumeSource> sourcesToMute;
6607 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
6608 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
6609 toString(attributes).c_str(), on, outputDesc->getId());
6610 VolumeSource source = toVolumeSource(attributes);
6611 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
6612 sourcesToMute.push_back(source);
6613 }
Eric Laurente552edb2014-03-10 17:42:56 -07006614 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006615 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07006616 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006617 }
6618
Eric Laurente552edb2014-03-10 17:42:56 -07006619}
6620
François Gaffieaaac0fd2018-11-22 17:56:39 +01006621void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
6622 bool on,
6623 const sp<AudioOutputDescriptor>& outputDesc,
6624 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07006625 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006626{
jiabin9a3361e2019-10-01 09:38:30 -07006627 if (deviceTypes.empty()) {
6628 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07006629 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006630 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006631 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006632 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006633 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006634 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6635 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
6636 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07006637 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006638 }
6639 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006640 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
6641 // ignored
6642 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07006643 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006644 if (!outputDesc->isMuted(volumeSource)) {
6645 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07006646 return;
6647 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01006648 if (outputDesc->decMuteCount(volumeSource) == 0) {
6649 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07006650 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07006651 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07006652 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07006653 delayMs);
6654 }
6655 }
6656}
6657
François Gaffie53615e22015-03-19 09:24:12 +01006658bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
6659{
François Gaffiec005e562018-11-06 15:04:49 +01006660 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08006661 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
6662 return true;
6663 }
6664
6665 // has known usage?
6666 switch (paa->usage) {
6667 case AUDIO_USAGE_UNKNOWN:
6668 case AUDIO_USAGE_MEDIA:
6669 case AUDIO_USAGE_VOICE_COMMUNICATION:
6670 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6671 case AUDIO_USAGE_ALARM:
6672 case AUDIO_USAGE_NOTIFICATION:
6673 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6674 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6675 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6676 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6677 case AUDIO_USAGE_NOTIFICATION_EVENT:
6678 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6679 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6680 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6681 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08006682 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08006683 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08006684 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08006685 case AUDIO_USAGE_EMERGENCY:
6686 case AUDIO_USAGE_SAFETY:
6687 case AUDIO_USAGE_VEHICLE_STATUS:
6688 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08006689 break;
6690 default:
6691 return false;
6692 }
6693 return true;
6694}
6695
François Gaffie2110e042015-03-24 08:41:51 +01006696audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
6697{
6698 return mEngine->getForceUse(usage);
6699}
6700
6701bool AudioPolicyManager::isInCall()
6702{
6703 return isStateInCall(mEngine->getPhoneState());
6704}
6705
6706bool AudioPolicyManager::isStateInCall(int state)
6707{
6708 return is_state_in_call(state);
6709}
6710
Eric Laurent74b71512019-11-06 17:21:57 -08006711bool AudioPolicyManager::isCallAudioAccessible()
6712{
6713 audio_mode_t mode = mEngine->getPhoneState();
6714 return (mode == AUDIO_MODE_IN_CALL)
6715 || (mode == AUDIO_MODE_IN_COMMUNICATION)
6716 || (mode == AUDIO_MODE_CALL_SCREEN);
6717}
6718
Eric Laurentd60560a2015-04-10 11:31:20 -07006719void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
6720{
6721 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006722 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006723 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006724 sourceDesc->sinkDevice()->equals(deviceDesc))
6725 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006726 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006727 }
6728 }
6729
6730 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6731 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6732 bool release = false;
6733 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6734 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6735 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6736 source->ext.device.type == deviceDesc->type()) {
6737 release = true;
6738 }
6739 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006740 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07006741 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6742 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6743 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006744 sink->ext.device.type == deviceDesc->type() &&
6745 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
6746 || strncmp(sink->ext.device.address, address,
6747 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006748 release = true;
6749 }
6750 }
6751 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006752 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
6753 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07006754 }
6755 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006756
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006757 mInputs.clearSessionRoutesForDevice(deviceDesc);
6758
Francois Gaffie716e1432019-01-14 16:58:59 +01006759 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006760}
6761
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006762void AudioPolicyManager::modifySurroundFormats(
6763 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006764 std::unordered_set<audio_format_t> enforcedSurround(
6765 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006766 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6767 for (const auto& pair : mConfig.getSurroundFormats()) {
6768 allSurround.insert(pair.first);
6769 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6770 }
Phil Burk09bc4612016-02-24 15:58:15 -08006771
6772 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6773 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07006774 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006775 // This is the resulting set of formats depending on the surround mode:
6776 // 'all surround' = allSurround
6777 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6778 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6779 // 'manual surround' = mManualSurroundFormats
6780 // AUTO: formats v 'enforced surround'
6781 // ALWAYS: formats v 'all surround' v 'enforced surround'
6782 // NEVER: formats ^ 'non-surround'
6783 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08006784
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006785 std::unordered_set<audio_format_t> formatSet;
6786 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6787 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006788 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006789 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006790 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006791 formatSet.insert(*formatIter);
6792 }
6793 }
6794 } else {
6795 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6796 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006797 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006798
jiabin81772902018-04-02 17:52:27 -07006799 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006800 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006801 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6802 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6803 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08006804 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006805 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6806 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6807 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07006808 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006809 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08006810 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006811 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07006812 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006813 }
Phil Burk0709b0a2016-03-31 12:54:57 -07006814}
6815
jiabin06e4bab2019-07-29 10:13:34 -07006816void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
6817 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07006818 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6819 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6820
6821 // If NEVER, then remove support for channelMasks > stereo.
6822 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07006823 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
6824 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006825 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006826 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07006827 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07006828 } else {
jiabin06e4bab2019-07-29 10:13:34 -07006829 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07006830 }
6831 }
jiabin81772902018-04-02 17:52:27 -07006832 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6833 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6834 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006835 bool supports5dot1 = false;
6836 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006837 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07006838 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6839 supports5dot1 = true;
6840 break;
6841 }
6842 }
6843 // If not then add 5.1 support.
6844 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07006845 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01006846 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07006847 }
Phil Burk09bc4612016-02-24 15:58:15 -08006848 }
6849}
6850
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006851void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07006852 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01006853 AudioProfileVector &profiles)
6854{
6855 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006856 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07006857
François Gaffie112b0af2015-11-19 16:13:25 +01006858 // Format MUST be checked first to update the list of AudioProfile
6859 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006860 reply = mpClientInterface->getParameters(
6861 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07006862 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006863 AudioParameter repliedParameters(reply);
6864 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006865 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01006866 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6867 return;
6868 }
Phil Burk09bc4612016-02-24 15:58:15 -08006869 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01006870 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006871 if (device == AUDIO_DEVICE_OUT_HDMI
6872 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006873 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07006874 }
jiabin3e277cc2019-09-10 14:27:34 -07006875 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01006876 }
François Gaffie112b0af2015-11-19 16:13:25 +01006877
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006878 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07006879 ChannelMaskSet channelMasks;
6880 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01006881 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07006882 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01006883
6884 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07006885 reply = mpClientInterface->getParameters(
6886 ioHandle,
6887 requestedParameters.toString() + ";" +
6888 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01006889 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006890 AudioParameter repliedParameters(reply);
6891 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006892 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006893 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01006894 }
6895 }
6896 if (profiles.hasDynamicChannelsFor(format)) {
6897 reply = mpClientInterface->getParameters(ioHandle,
6898 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07006899 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01006900 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08006901 AudioParameter repliedParameters(reply);
6902 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07006903 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08006904 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08006905 if (device == AUDIO_DEVICE_OUT_HDMI
6906 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08006907 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07006908 }
François Gaffie112b0af2015-11-19 16:13:25 +01006909 }
6910 }
jiabin3e277cc2019-09-10 14:27:34 -07006911 addDynamicAudioProfileAndSort(
6912 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01006913 }
6914}
Eric Laurentd60560a2015-04-10 11:31:20 -07006915
Mikhail Naganovdc769682018-05-04 15:34:08 -07006916status_t AudioPolicyManager::installPatch(const char *caller,
6917 audio_patch_handle_t *patchHandle,
6918 AudioIODescriptorInterface *ioDescriptor,
6919 const struct audio_patch *patch,
6920 int delayMs)
6921{
6922 ssize_t index = mAudioPatches.indexOfKey(
6923 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6924 *patchHandle : ioDescriptor->getPatchHandle());
6925 sp<AudioPatch> patchDesc;
6926 status_t status = installPatch(
6927 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6928 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006929 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07006930 }
6931 return status;
6932}
6933
6934status_t AudioPolicyManager::installPatch(const char *caller,
6935 ssize_t index,
6936 audio_patch_handle_t *patchHandle,
6937 const struct audio_patch *patch,
6938 int delayMs,
6939 uid_t uid,
6940 sp<AudioPatch> *patchDescPtr)
6941{
6942 sp<AudioPatch> patchDesc;
6943 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6944 if (index >= 0) {
6945 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006946 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006947 }
6948
6949 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6950 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6951 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6952 if (status == NO_ERROR) {
6953 if (index < 0) {
6954 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01006955 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006956 } else {
6957 patchDesc->mPatch = *patch;
6958 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006959 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006960 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006961 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07006962 }
6963 nextAudioPortGeneration();
6964 mpClientInterface->onAudioPatchListUpdate();
6965 }
6966 if (patchDescPtr) *patchDescPtr = patchDesc;
6967 return status;
6968}
6969
jiabinbce0c1d2020-10-05 11:20:18 -07006970bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
6971{
6972 const TrackClientVector activeClients = output->getActiveClients();
6973 if (activeClients.empty()) {
6974 return true;
6975 }
6976 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
6977 if (index < 0) {
6978 ALOGE("%s, no audio patch found while there are active clients on output %d",
6979 __func__, output->getId());
6980 return false;
6981 }
6982 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6983 DeviceVector routedDevices;
6984 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
6985 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
6986 patchDesc->mPatch.sinks[i].id);
6987 if (device == nullptr) {
6988 ALOGE("%s, no audio device found with id(%d)",
6989 __func__, patchDesc->mPatch.sinks[i].id);
6990 return false;
6991 }
6992 routedDevices.add(device);
6993 }
6994 for (const auto& client : activeClients) {
6995 // TODO: b/175343099 only travel the valid client
6996 sp<DeviceDescriptor> preferredDevice =
6997 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
6998 if (mEngine->getOutputDevicesForAttributes(
6999 client->attributes(), preferredDevice, false) == routedDevices) {
7000 return false;
7001 }
7002 }
7003 return true;
7004}
7005
7006sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
7007 const sp<IOProfile>& profile, const DeviceVector& devices)
7008{
7009 for (const auto& device : devices) {
7010 // TODO: This should be checking if the profile supports the device combo.
7011 if (!profile->supportsDevice(device)) {
7012 return nullptr;
7013 }
7014 }
7015 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7016 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
7017 status_t status = desc->open(nullptr, devices,
7018 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7019 if (status != NO_ERROR) {
7020 return nullptr;
7021 }
7022
7023 // Here is where the out_set_parameters() for card & device gets called
7024 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7025 const audio_devices_t deviceType = device->type();
7026 const String8 &address = String8(device->address().c_str());
7027 if (!address.isEmpty()) {
7028 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7029 mpClientInterface->setParameters(output, String8(param));
7030 free(param);
7031 }
7032 updateAudioProfiles(device, output, profile->getAudioProfiles());
7033 if (!profile->hasValidAudioProfile()) {
7034 ALOGW("%s() missing param", __func__);
7035 desc->close();
7036 return nullptr;
7037 } else if (profile->hasDynamicAudioProfile()) {
7038 desc->close();
7039 output = AUDIO_IO_HANDLE_NONE;
7040 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7041 profile->pickAudioProfile(
7042 config.sample_rate, config.channel_mask, config.format);
7043 config.offload_info.sample_rate = config.sample_rate;
7044 config.offload_info.channel_mask = config.channel_mask;
7045 config.offload_info.format = config.format;
7046
7047 status = desc->open(&config, devices,
7048 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7049 if (status != NO_ERROR) {
7050 return nullptr;
7051 }
7052 }
7053
7054 addOutput(output, desc);
7055 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7056 sp<AudioPolicyMix> policyMix;
7057 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7058 policyMix->setOutput(desc);
7059 desc->mPolicyMix = policyMix;
7060 } else {
7061 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7062 address.string());
7063 }
7064
7065 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) && hasPrimaryOutput()) {
7066 // no duplicated output for direct outputs and
7067 // outputs used by dynamic policy mixes
7068 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7069
7070 //TODO: configure audio effect output stage here
7071
7072 // open a duplicating output thread for the new output and the primary output
7073 sp<SwAudioOutputDescriptor> dupOutputDesc =
7074 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7075 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7076 if (status == NO_ERROR) {
7077 // add duplicated output descriptor
7078 addOutput(duplicatedOutput, dupOutputDesc);
7079 } else {
7080 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7081 mPrimaryOutput->mIoHandle, output);
7082 desc->close();
7083 removeOutput(output);
7084 nextAudioPortGeneration();
7085 return nullptr;
7086 }
7087 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007088 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7089 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7090 mPrimaryOutput = desc;
7091 }
jiabinbce0c1d2020-10-05 11:20:18 -07007092 return desc;
7093}
7094
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007095} // namespace android